Project the points onto the long direction and they stay spread out. Project across it and they bunch up. Principal component analysis (PCA) picks the direction with the greatest projected variance first, then the best direction perpendicular to it, and so on.
Subtract each feature’s mean. With the centred observations as rows of the sample covariance matrix is
The diagonal gives the feature variances. The off-diagonal entries are covariances: positive if the two features tend to move together, negative if they move in opposite directions. If the features are measured on scales you don’t want to weight differently, divide each centred feature by its standard deviation before doing PCA.
For a unit direction the projected coordinates are so their variance is The principal directions are the orthonormal eigenvectors of ordered by decreasing eigenvalue. For an eigenvector with that variance is In practice, compute PCA from the SVD of the centred the right singular vectors give the directions with for each corresponding singular value
For a centred point store just its first dot products To get back to the original feature space, use where is the mean you subtracted. (If you also scaled the features, undo that scaling before adding the mean.) PCA gives the smallest total squared reconstruction error among -dimensional linear projections of the centred data.
How many directions are enough? Divide the sum of the eigenvalues you keep by the sum of all the eigenvalues. That is the fraction of variance explained. For example, has eigenvalues and The first direction is and it keeps of the variance.