Principal component analysis
Rotate to the directions of greatest variance and keep the few that matter.
Animated explanation
The idea
Data with many features is often secretly low-dimensional: height and arm span move together; pixel values in a face image are highly correlated. PCA finds new axes, the principal components, ordered by how much of the data's variance lies along them. The first points along the direction the data is most spread out; the second is the most spread direction perpendicular to it; and so on.
Keep the first few components and drop the rest: you have compressed the data while losing as little variance (information, in a squared-error sense) as possible. It is used to visualise high-dimensional data, to denoise, to speed up other models, and to remove multicollinearity.
Two equivalent views
Maximum variance: the first component maximises the variance of the projections . Minimum reconstruction error: it minimises the squared distance between points and their projections onto the line. By Pythagoras these are the same problem. The solution is the eigenvectors of the covariance matrix, computed stably with the SVD of the centred data.
Using PCA well
- Centre the data (PCA assumes zero mean) and usually standardise it, or features with large units dominate.
- Fit on training data only, then transform validation and test data with the same components.
- Components are linear combinations of all features, so they are harder to interpret. Look at the loadings.
- PCA only captures linear structure and variance. Class-separating directions can have low variance (use LDA), and curved manifolds need kernel PCA, t-SNE/UMAP or autoencoders.
The algorithm, step by step
- 1Standardise the features and centre them: .
- 2Compute the SVD (or eigen-decompose the covariance).
- 3Explained variance of component : ; choose from the cumulative ratio.
- 4Project: . Reconstruct: .
The maths
Covariance
Eigenproblem
Projection and reconstruction
Reconstruction error
Strengths and weaknesses
Strengths
- Fast, deterministic, no hyperparameters except k
- Optimal linear compression in squared error
- Decorrelates features; denoises; speeds up downstream models
Weaknesses
- Linear only
- Sensitive to feature scaling and outliers
- Components can be hard to interpret; variance ≠ usefulness
Reach for it when…
Check your understanding
Lambdian Lab
PCA by SVD
Implement PCA.
- fit_pca(X, k): centre X, take the SVD, return (mean, components (k × d), explained_variance (k), explained_variance_ratio (k)). Use variance with denominator n − 1.
- transform(X, mean, components) and inverse_transform(Z, mean, components).
- n_components_for(X, threshold): the smallest k whose cumulative explained ratio reaches the threshold.