Principal Component Analysis is a technique for simplifying datasets. It is a linear transformation that transforms the data into a new coordinate system such that the first largest variance of any data projection is in the first coordinate (called the first principal component), and the second largest variance is in the second coordinate (the second principal component). ingredients), and so on. Principal component analysis is often used to reduce the dimensionality of a dataset while maintaining the features of the dataset that contribute the most to the variance. This is done by keeping low-order principal components and ignoring high-order principal components. Such lower-order components tend to retain the most important aspects of the data.
Covariance matrix
Algorithms like PCA depend heavily on the covariance. Correlation coefficient tells us how variables are related and it is the covariance normalized to range [−11]. The covariance matrix is an m∗m-matrix (m is the number of variables) and it’s symmetric as covariance between x1 and x2 equals covariance between x2 and x1. The diagonal entries are the variances (the covariance
between x1 and x1 is the variance of x1). There two methods for calculating the covariance matrix, and they’re shown with the example below:
x1=⎝⎛234⎠⎞,xˉ1=3,x2=⎝⎛312⎠⎞,xˉ2=2
sample n= number of elements in xn=3, variable m= number of xn=2
Apply scaling on matrix Aˉ: A=(x1⊤−xˉ1x2⊤−xˉ2)=(−110−110)
C(x2,x1)=n−11AA⊤=21(2−1−12)=(1−1/2−1/21)
SVD and PCA
In SVD, A=UΣV⊤, then AV or UΣ represent data points’s principal components. U=(u1,⋯,un) are the left singular vectors of A (eigenvector of C) that represent the direction of the largest variance of the data, which can also be view principal directions. We can get eigenvalues of C from SVD of A: λi=n−11σi2, which is also the magnitude of data points. Eigenvalues λi represent the fraction of the total spread (variance) in the ui-direction.
Total variance = trace(C) = the sum of eigenvalues of C = the sum of diagonal elements of C, and the number of each eigenvalue to be divided by total variance tells how many percents that each principal component explains the total variance. For example: there are 2 eigenvalues λ1=28.9, λ2=0.1, and trace(C)=29, then trace(C)λ1=2928.9=0.997, so the first eigenvalue explains 99% of the total variance.
PCA in Python
1 2 3 4 5 6 7 8 9
import numpy as np Q = np.array([[5,5,0,4], [1,1,5,0], [3,2,0,4], [3,5,0,5], [0,0,4,0]]) A = Q-Q.mean(axis=0, keepdims=True) ATA = np.dot(A.T, A) eig1 = np.linalg.eig(ATA) AAT = np.dot(A, A.T) eig2 = np.linalg.eig(AAT) PCA = np.dot(A, eig1[1]) print(PCA, '\n')