Principal Component Analysis (PCA)
PCA finds the directions of greatest variance, which are also the best low-dimensional reconstruction. How scaling changes the answer, and what PCA cannot see.
Jump to a section
Eight points, one line
Take eight points in the plane, centred on the origin and stretched along the 45° diagonal. Along that diagonal they sit at . Across it, at 135°, they sit at . Project every point onto the 45° line and you keep 95.3% of their total squared distance from the mean, with one number per point instead of two.
Principal component analysis finds that line automatically, in any number of dimensions. The first principal component is the unit direction along which centred data has the greatest variance. The second is the direction of greatest remaining variance orthogonal to the first, and so on. Keeping the leading components gives a -dimensional representation that keeps as much variance as any orthogonal projection to dimensions can.
Rotate the projection. Measure what survives.
Project a centered cloud onto a line. The principal direction preserves the most squared distance from the mean.
Reduced motion is on. Use Previous and Next to inspect each state.
x̂ = u(uᵀx)
Choose a projection direction
Project eight centered points onto a horizontal line. Violet points are data; green points are reconstructions.
Explore the inputs and calculations
Violet dots are original points. Green dots are reconstructions. The connecting segments are discarded components, perpendicular to the line.
Inspect the projection
u = [0.707, 0.707]. Each reconstruction is u(uᵀx). The mean is zero, so total squared length splits into retained length and reconstruction error.
| -1.167 | -1.662 |
| -1.662 | -1.167 |
| -0.46 | -0.955 |
| -0.955 | -0.46 |
| 0.955 | 0.46 |
| 0.46 | 0.955 |
| 1.662 | 1.167 |
| 1.167 | 1.662 |
| -1.414 | -1.414 |
| -1.414 | -1.414 |
| -0.707 | -0.707 |
| -0.707 | -0.707 |
| 0.707 | 0.707 |
| 0.707 | 0.707 |
| 1.414 | 1.414 |
| 1.414 | 1.414 |
Why is the direction at 225° just as good as 45°?
A principal component’s sign is arbitrary. Replacing u with −u leaves uuᵀx unchanged, so reconstruction and retained variance are identical.
The arithmetic for the eight points is short. Squared distances along 45° sum to , and across it to . The 45° line keeps . Rotate the line to 135° and it keeps only the transverse wobble, .
Maximum variance is minimum reconstruction error
For a centred point and a unit direction , the coordinate along the line is and the reconstruction is . The residual is perpendicular to , so Pythagoras applies:
Summed over the dataset, the left side is fixed: 20.98 for the eight points. Whatever the projection keeps, the reconstruction loses the rest. Keeping 20 means losing 0.98, a mean squared reconstruction error of per point; keeping 0.98 at 135° means losing 20. So "the direction of maximum variance" and "the line with minimum squared reconstruction error" are the same line, provided the data is centred and the projection is orthogonal.
That identity says nothing about which direction matters for a prediction. If the labels of the eight points depended on the 135° coordinate, the 4.7% that PCA throws away would be all of the signal. Variance retained is a property of the representation, not an accuracy score.
Eigenvectors, computed with the SVD
Given centred data , the covariance matrix is
The variance along a unit direction is . Maximising it subject to gives the eigenvectors of , ordered by eigenvalue:
Each eigenvalue is the variance captured by component . For the eight points, and . The fraction of variance explained by the top components is , and the usual way to choose is to keep enough components to reach a target such as 95%.
Keep the direction that carries the variation.
Move a three-dimensional point cloud onto its first principal component and inspect the lost directions.
The visual loads as you reach this section.
In practice nobody forms . The singular value decomposition of the centred data gives the same answer: the principal components are the columns of , and . Working on directly is more accurate because forming squares the condition number, and the smallest components are the first to lose precision.
In code
The four steps (centre, decompose, keep directions, project), checked on the eight points and on random correlated data in five dimensions.
1import numpy as np
2
3
4def pca(X, k):
5 Xc = X - X.mean(axis=0) # 1. center
6 U, S, Vt = np.linalg.svd(Xc, full_matrices=False) # 2. SVD
7 components = Vt[:k] # 3. top-k directions (k × d)
8 projected = Xc @ components.T # 4. project -> (n × k)
9 explained = (S**2) / (S**2).sum() # variance ratio per component
10 return projected, components, explained[:k]
11
12
13r2 = np.sqrt(2)
14diag, anti = np.array([1 / r2, 1 / r2]), np.array([-1 / r2, 1 / r2]) # 45° and 135°
15
16# The eight points: long axis at 45°, short axis at 135°
17points = np.array([a * diag + b * anti for a in (-2, -1, 1, 2) for b in (-0.35, 0.35)])
18z, comps, var = pca(points, k=1)
19assert abs(var[0] - 20 / 20.98) < 1e-12 # 95.3% retained
20assert abs(abs(comps[0] @ diag) - 1) < 1e-12 # the 45° line, up to sign
21residual = points - z @ comps # what the projection drops
22assert abs((residual**2).sum() - 0.98) < 1e-12
23
24# One extra point, 5 units out along 135°, takes the first component
25_, comps, _ = pca(np.vstack([points, 5 * anti]), k=1)
26assert abs(abs(comps[0] @ anti) - 1) < 1e-9
27
28# Correlated 5-D data: singular values and covariance eigenvalues agree
29rng = np.random.default_rng(0)
30X = rng.normal(size=(500, 5)) @ rng.normal(size=(5, 5))
31proj, comps, var = pca(X, k=2)
32s = np.linalg.svd(X - X.mean(axis=0), compute_uv=False)
33eigenvalues = np.linalg.eigvalsh(np.cov(X, rowvar=False))[::-1]
34assert np.allclose(s**2 / (len(X) - 1), eigenvalues)
35assert np.allclose(comps @ comps.T, np.eye(2)) # orthonormal directions
36print(f"shape {proj.shape}, variance explained by top 2: {var.sum():.2%}")scikit-learn's PCA does the same work, and accepts a fraction such as n_components=0.95 to pick from an explained-variance target.
Scaling decides the answer
PCA ranks directions by variance, and variance depends on units. Record one feature in millimetres instead of metres and its variance grows by a factor of a million. Unless another feature varies on a similar scale, the first component will then point almost entirely along it, although nothing about the data changed except a unit label.
Standardising every feature to unit variance removes that dependence and gives each feature an equal say. It is a modelling choice, not a requirement. When features share meaningful units, such as pixel intensities, their natural scales carry information, and standardising can inflate a feature that is mostly low-variance noise to the same weight as real structure. Decide based on the units and the question, then fit the scaler and the PCA on training data only.
What PCA cannot see
Outliers. Every point contributes its squared distance, so one far-off point can outvote the rest. Add a ninth point 5 units out along 135° to the example: after re-centring, the squared distances along 135° sum to about 23.2, against 20 along 45°, and the first component swings to 135°. The code above checks this.
Curved structure. PCA only finds linear directions. Data on a curved surface, such as a spiral, can need many components to describe, and the leading components may not separate clusters that a nonlinear method would. t-SNE and UMAP preserve local neighbourhoods instead of global variance, and are usually used for two- or three-dimensional plots.
New data. A fitted PCA is a fixed linear map, so new points project with one matrix multiply, and a truncated reconstruction is available for any point. UMAP can also transform new samples with a fitted model. Standard t-SNE does not learn a reusable transform, so new points require rerunning it.
Sign and order. Each component is defined only up to sign, and components with nearly equal eigenvalues can swap or mix between runs. Compare subspaces, or align signs explicitly, before treating component 1 from two fits as the same feature.
Sources and further reading
- scikit-learn, Principal component analysis: centering, SVD, and dimensionality reduction.
- scikit-learn, Importance of feature scaling: how scaling changes principal components.
- UMAP documentation, Transforming new data: using a fitted UMAP model on new samples.
Keep going
Ask your own question about Principal Component Analysis (PCA), or start a guided session on it: six short pages, from the big picture to code you can run.