Principal Component Analysis
A table with 64 pixel columns, or 30 blood measurements, or 13 chemical properties of wine, rarely has 64, 30 or 13 independent directions of variation: the columns move together. Principal component analysis (PCA) finds new axes, the principal components, ordered so that the first captures as much of the data's variance as possible, the second as much of the rest as possible while being perpendicular to the first, and so on. Keeping the first few gives a compact description of the data for plotting, compression, denoising or as input to another model. The Machine Learning course applies it with scikit-learn; here you compute it two ways and see why both work.
Two equivalent definitions
Centre the data (subtract each column's mean), giving with covariance matrix .
Maximum variance. The first component is the unit vector along which the projected data has the largest variance:
With a Lagrange multiplier this becomes : the components are the eigenvectors of the covariance matrix, and the variance along each is its eigenvalue . Sorting by eigenvalue gives the order.
Minimum reconstruction error. Projecting onto the first components and mapping back loses as little as possible in squared error; the error left is the sum of the dropped eigenvalues, .
Both views give the same axes. Since is symmetric, its eigenvectors are orthogonal. In practice PCA is computed from the singular value decomposition : the rows of are the components and , without ever forming . Derivations: PCA: Maximum Variance, PCA: Minimum Reconstruction Error, Singular Value Decomposition, Eigendecomposition and Principal Component Analysis in Linear Algebra.
See it
The lab draws 120 centred points with correlation , turns the cloud onto its principal axes, and with drops every point onto the first component. The arrows are the components (twice the standard deviation along each), the bars the explained variance. At the start, , PC1 keeps 90.8 % of the variance (, ). Raise towards 0.95: almost all variance lies along PC1, and projecting onto it loses little. Set with equal spreads and there is no preferred direction at all.
From scratch, two routes
Three features: strongly correlated with , and a small independent :
import numpy as np
from sklearn.decomposition import PCA
rng = np.random.default_rng(0)
n = 200
x1 = rng.normal(size=n)
x2 = 0.8 * x1 + 0.6 * rng.normal(size=n) # correlation about 0.8
x3 = 0.3 * rng.normal(size=n) # a small independent direction
X = np.column_stack([x1, x2, x3])
Xc = X - X.mean(axis=0) # PCA works on centred data
# route 1: eigendecomposition of the covariance matrix
cov = Xc.T @ Xc / (n - 1)
lam, V = np.linalg.eigh(cov) # ascending order
lam, V = lam[::-1], V[:, ::-1]
# route 2: SVD of the centred data, Xc = U S W^T, eigenvalues = S^2 / (n - 1)
U, S, Wt = np.linalg.svd(Xc, full_matrices=False)
pca = PCA().fit(X)
print("eigenvalues ", lam.round(4))
print("from the SVD ", (S ** 2 / (n - 1)).round(4))
print("sklearn variances", pca.explained_variance_.round(4))
print("explained variance ratio:", pca.explained_variance_ratio_.round(3))
same_dirs = np.allclose(np.abs(V.T), np.abs(pca.components_)) # equal up to the sign of each axis
print("same axes as sklearn (up to sign):", same_dirs)
print("first axis:", pca.components_[0].round(3))
Z = Xc @ V[:, :2] # project onto the first two axes
X_back = Z @ V[:, :2].T # reconstruct
err = ((Xc - X_back) ** 2).sum() / (n - 1)
print("reconstruction error with 2 axes:", round(err, 4), " = third eigenvalue:", round(lam[2], 4))eigenvalues [1.6255 0.2166 0.0896]
from the SVD [1.6255 0.2166 0.0896]
sklearn variances [1.6255 0.2166 0.0896]
explained variance ratio: [0.841 0.112 0.046]
same axes as sklearn (up to sign): True
first axis: [0.711 0.703 0.019]
reconstruction error with 2 axes: 0.0896 = third eigenvalue: 0.0896
The eigendecomposition, the SVD and scikit-learn give the same variances and the same axes; an axis and its negative describe the same line, so signs are arbitrary (scikit-learn fixes them by a convention). The first component, , is essentially "" and carries 84.1 % of the variance. Dropping the third component loses exactly its eigenvalue, 0.0896, as the minimum-error view predicts.
Using the components
transformgives the scores , the coordinates on the first axes; use them for plots or as features.inverse_transformmaps scores back to the original space, a denoised or compressed version of the data.explained_variance_ratio_tells you how much each component keeps; its cumulative sum guides the choice of .components_are the loadings: how each original feature contributes to each component, the key to interpreting them.
PCA in Practice covers scaling, choosing and PCA inside a model pipeline.
Strengths, weaknesses, when to use it
| Strengths | Weaknesses |
|---|---|
| exact, fast (one SVD), no hyperparameters except | only linear structure; curved manifolds need kernel PCA, t-SNE, UMAP or autoencoders |
| components are uncorrelated | depends on feature scales |
| reconstruction error is known exactly | components mix all features, so they can be hard to interpret |
| denoises by dropping small components | high variance is not the same as useful for prediction |
Use it to visualise high-dimensional data in 2-D, to compress correlated features, to remove noise, and to speed up or stabilise models that suffer from many correlated inputs. Its unsupervised cousins are in Data Preparation (dimensionality reduction), its neural generalisation in Autoencoders.
Pitfalls
- Not centring. PCA without centring finds the direction of the mean, not of the variance.
PCAcentres for you; a hand-made SVD must too. - Fitting PCA on all the data before a train/test split. It is a fitted transformation; put it in the pipeline.
- Assuming the top components predict the target. A low-variance direction can be the one that separates the classes.
Practice
- A 2-D data set has covariance matrix . What are the components and the explained variance ratios?
Answer
The matrix is diagonal, so its eigenvectors are the axes: PC1 with , PC2 with . Ratios and .
- In the example, what reconstruction error would one component leave?
Answer
The sum of the dropped eigenvalues: , which is % of the total variance.
Test yourself
What are the principal components of centred data?
- The columns with the largest values
- The eigenvectors of the covariance matrix, ordered by eigenvalue
- The cluster centroids
- The rows of the data
Keeping the first of components, what is the squared reconstruction error (per )?
- The sum of the kept eigenvalues
- The sum of the dropped eigenvalues
- Zero
How do the SVD and the eigenvalues of the covariance relate?
- They are unrelated