Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 3: Classical Machine LearningUnsupervised Learning

Principal Component Analysis

P3.C345 min●●○ IntermediateReviewed Dec 2, 2026

Why this matters for machine learning

PCA finds the few directions along which data vary most, so each example can be described by a handful of numbers instead of hundreds, with a known amount of information lost.

  • Distances become unreliable in many dimensions, and reducing the dimension first is one remedy, as long as the data lie near a lower-dimensional subspace. (P3.B1: k-Nearest Neighbors)
  • Drawing high-dimensional data starts with its first two components; nonlinear methods that make better maps are the next step. (P3.C4: t-SNE and UMAP)
  • An autoencoder is a nonlinear network that compresses its input and rebuilds it, the same job as PCA with a curved code. (P8.2: Autoencoders, coming soon)
  • The singular value decomposition is the stable way to compute PCA and gives the best low-rank approximation of any matrix. (P1.B13: Singular Value Decomposition)

Before this: Eigenvalues and eigenvectors, Covariance and the multivariate Gaussian, Projections and least squares

After this lesson you can

  • Centre a data matrix, form its covariance matrix, and find the direction of largest variance three ways, as a maximum over unit vectors, as the top eigenvector of the covariance matrix, and as the first right singular vector of the centred data
  • Compute explained variance ratios, read a scree plot, choose the number of components k, and project to k dimensions and reconstruct, knowing that the squared error is the sum of the discarded eigenvalues (times N − 1)
  • Explain PCA as the line of least perpendicular distance and say how it differs from the regression line
  • Decide when to standardize first, fit PCA on training data only, and name its limits

A photo of a handwritten digit in a small data set has 64 numbers, one per pixel. You cannot draw 64 axes, but you can draw 2. How many numbers do we have to keep before the digit is still recognizable? The answer is far fewer than 64, because neighbouring pixels move together: when one pixel is dark, the next one probably is too. Data with many features often really vary along only a few directions, and principal component analysis (PCA) finds them. This lesson ties together five ideas from Part 1, the covariance matrix (P1.D7), eigenvectors (P1.B12), the singular value decomposition (P1.B13), projections (P1.B11) and constrained optimization (P1.F7), and shows that they all describe one method.

Why reduce the dimension?

There are four common reasons.

  • Seeing. A person can look at 2 or 3 numbers per example, not 64. The first two components give a flat picture of the data.
  • Compressing. Storing 20 numbers per example instead of 64 saves space, and the loss is known in advance.
  • Removing noise. Directions along which the data barely vary are often noise. Dropping them can clean the data.
  • Speeding up. Models with fewer inputs train faster, and distance-based methods behave better when the distances are measured in fewer, more meaningful directions (P3.B1). This helps only if the data lie near a lower-dimensional subspace. Noise columns are not fixed by PCA: they add variance, and PCA may keep them.

Something is always lost. The question PCA answers is: which directions to keep so that the least is lost? It measures “lost” as squared distance, as we will see.

The picture: rotate a line

The widget shows 20 made-up points, already centred so that their average is the origin. A line passes through the origin. Each point is projected onto the line (the blue dot is the closest point on the line) and the red segment is the perpendicular distance from the point to the line. The bar splits the total variance into two parts: the variance of the blue dots (blue) and the sum of the squared red lengths divided by N−1N-1 (red). Both use N−1N-1 as the divisor, so they add up to the total variance, which does not depend on the angle.

Rotate a line, watch the variance

−6−4−20246−6−4−20246feature 1 (raw)feature 2 (raw)PC1PC2
data point its projection perpendicular error
Variance of the projections: 8.502
Squared perpendicular distances ÷ (N−1): 1.206
Sum = total variance 9.709 (the same at every angle). Share kept: 87.6%
Line angle: 20°
PC1 angle: 35.1°, PC2: 125.1°
Eigenvalues: 9.073 and 0.636
0204060801001201401601800510

Variance of the projections (up) against the line angle in degrees (across).

PC1 would give 9.073 blue and 0.636 red. Rotate until the blue part is as large as it can get. One direction is much longer than the other.

Drag the round handle, use the slider, or Tab to the handle and press the arrow keys (Shift for 10°). Grey dots are the centred points. Each blue dot is a point projected onto the line; each red segment is the perpendicular distance to the line. The bar shows the total variance split into the blue part (kept) and the red part (lost); the tick on the bar marks the largest the blue part can be. On the curve, the dot at the top is PC1 and the dot at the bottom is PC2.

Rotate a line through 20 centred, made-up points. Blue dots are the projections; red segments are the perpendicular errors. The bar splits the total variance into the part the projections keep (blue) and the part lost as perpendicular error (red), and the tick marks the most that can be kept. The curve shows the variance of the projections against the angle, with PC1 at the top and PC2 at the bottom. The Standardize box divides each feature by its standard deviation.

Things to try:

  • Rotate the line on the elongated cloud and watch the two numbers trade off. The blue part is largest, 9.0739.073, near 35°35° (the long axis of the cloud) and smallest, 0.6360.636, at the perpendicular angle, 125°125°. The red part does the opposite. “Snap to PC1” jumps to the best angle. The line at the best angle is the first principal component (PC1); the line at 90°90° to it is PC2.
  • Round cloud. The two spreads are almost equal (4.394.39 and 3.953.95), so every angle keeps almost the same variance, and the best direction means little. A few more points could turn PC1 to a very different angle. PCA has little to offer when the data spread evenly in all directions.
  • Unequal units. The points are heights in cm and weights in kg. Without standardizing, PC1 sits at 69°69° because kilograms vary more than centimetres. Tick “Standardize first”: PC1 moves to 45°45°. Which of the two is right depends on whether the units are arbitrary. The last section before the code explains the choice.
  • Keyboard. Tab to the round handle and press the arrow keys (1°1° steps, Shift for 10°10°).

Centring and the covariance matrix

PCA first centres the data: subtract each column’s mean, so that every column has mean 00 and the cloud is centred on the origin. In NumPy, X - X.mean(axis=0) does it by broadcasting, shapes (N,d)(N,d) and (d,)(d,) (P1.B14). Without it, the line through the origin would chase the mean of the data instead of the spread.

Here is the small example of P1.B12 and P1.B13 in raw form (the data are made up). Four people with two measurements each: (8,19)(8,19), (11,22)(11,22), (11,19)(11,19), (10,20)(10,20). After subtracting the means 1010 and 2020 we get exactly the centred points those lessons used:

X=(−2−1121−100).\mathbf{X}=\begin{pmatrix}-2&-1\\1&2\\1&-1\\0&0\end{pmatrix}.

The sample covariance matrix of centred data is Σ=1N−1X⊤X\boldsymbol\Sigma=\dfrac{1}{N-1}\mathbf{X}^\top\mathbf{X} (P1.D7). Here N=4N=4, so we divide by 33:

Σ=13(6336)=(2112).\boldsymbol\Sigma=\frac13\begin{pmatrix}6&3\\3&6\end{pmatrix}=\begin{pmatrix}2&1\\1&2\end{pmatrix}.

Each variance is 22 and the covariance is 11: the two features rise together. The total variance is the sum of the diagonal, 2+2=42+2=4 (the trace). Some books divide by NN; every number below would change by the same factor. scikit-learn divides by N−1N-1, and so does this lesson.

For a unit vector u\mathbf{u} (length 11), the variance of the projections of the data onto the line along u\mathbf{u} is

Var=u⊤Σu.\mathrm{Var}=\mathbf{u}^\top\boldsymbol\Sigma\mathbf{u}.

Why: the projection of the centred point xi\mathbf{x}_i is the number u⋅xi\mathbf{u}\cdot\mathbf{x}_i (P1.B11), these numbers have mean 00, and their mean square is 1N−1∑i(u⊤xi)2=u⊤(1N−1X⊤X)u\frac1{N-1}\sum_i(\mathbf{u}^\top\mathbf{x}_i)^2=\mathbf{u}^\top\bigl(\frac1{N-1}\mathbf{X}^\top\mathbf{X}\bigr)\mathbf{u}.

Three ways to the same direction

Way 1: maximize over unit vectors (P1.F7). With u=(cos⁡θ,sin⁡θ)\mathbf{u}=(\cos\theta,\sin\theta) and Σ\boldsymbol\Sigma above, u⊤Σu=2cos⁡2θ+2cos⁡θsin⁡θ+2sin⁡2θ=2+sin⁡2θ\mathbf{u}^\top\boldsymbol\Sigma\mathbf{u}=2\cos^2\theta+2\cos\theta\sin\theta+2\sin^2\theta=2+\sin2\theta. This is 22 at 0°0°, 2.8662.866 at 30°30°, 33 at 45°45° and 22 again at 90°90°. The largest value is 33, at θ=45°\theta=45°, and the smallest is 11, at 135°135°. The widget’s curve is this kind of function. The general problem is “maximize u⊤Σu\mathbf{u}^\top\boldsymbol\Sigma\mathbf{u} with ∥u∥=1\lVert\mathbf{u}\rVert=1”, the constrained problem of P1.F7; the Go-deeper box below shows that its solutions are eigenvectors of Σ\boldsymbol\Sigma.

Way 2: the top eigenvector of Σ\boldsymbol\Sigma (P1.B12). The eigenvalues of (2112)\begin{pmatrix}2&1\\1&2\end{pmatrix} are 33 and 11, with eigenvectors along (1,1)/2(1,1)/\sqrt2 and (1,−1)/2(1,-1)/\sqrt2. The eigenvalue is the variance: along (1,1)/2(1,1)/\sqrt2, the 45°45° direction, the variance is 33; along the perpendicular direction it is 11. The eigenvalues add up to 44, the trace and the total variance. PCA is exactly this eigen-decomposition of the covariance matrix of the centred data: the eigenvectors, sorted by eigenvalue, are the principal components.

Way 3: the SVD of the centred data (P1.B13). Write X=USV⊤\mathbf{X}=\mathbf{U}\mathbf{S}\mathbf{V}^\top with singular values s1≥s2≥⋯s_1\ge s_2\ge\cdots. (P1.B13 writes the singular-value matrix as Σ\boldsymbol\Sigma; this lesson keeps Σ\boldsymbol\Sigma for the covariance, so the singular-value matrix is S\mathbf{S}.) Then Σ=V S⊤SN−1 V⊤\boldsymbol\Sigma=\mathbf{V}\,\dfrac{\mathbf{S}^\top\mathbf{S}}{N-1}\,\mathbf{V}^\top. So the right singular vectors vi\mathbf{v}_i (the columns of V\mathbf{V}) are the principal directions, and the variance along vi\mathbf{v}_i is

λi=si2N−1.\lambda_i=\frac{s_i^2}{N-1}.

For the four points, the singular values are s1=3s_1=3 and s2=3≈1.732s_2=\sqrt3\approx1.732, so λ1=9/3=3\lambda_1=9/3=3 and λ2=3/3=1\lambda_2=3/3=1. The same numbers, the same directions. The SVD works on X\mathbf{X} directly and never forms X⊤X\mathbf{X}^\top\mathbf{X}, which squares the condition number (P1.B11), so it is what software uses. The coordinates of the data along the directions are the columns of XV=US\mathbf{X}\mathbf{V}=\mathbf{U}\mathbf{S}.

Orthogonal, uncorrelated, and the later components

The second principal component is the direction of largest variance among the directions perpendicular to the first, the third among those perpendicular to both, and so on. Because Σ\boldsymbol\Sigma is symmetric, the spectral theorem (P1.B10, P1.B12) says its eigenvectors can be chosen perpendicular: the components form an orthonormal set. In the example PC1 =(1,1)/2=(1,1)/\sqrt2 and PC2 =(−1,1)/2=(-1,1)/\sqrt2. (Their signs are arbitrary: the negatives of these vectors are just as valid, and different programs will print either.)

The coordinates along the components, called scores, are uncorrelated: their covariance matrix is diag(3,1)\mathrm{diag}(3,1), as in the example of P1.D7. The score of the first person (−2,−1)(-2,-1) on PC1 is −3/2=−2.121-3/\sqrt2=-2.121 and on PC2 is 1/2=0.7071/\sqrt2=0.707. Rotating onto the eigenvectors turns correlated features into uncorrelated ones. The two scores can still depend on each other in other ways: uncorrelated is not independent.

The picture of P1.D7 helps: the data of a Gaussian-looking cloud fill an ellipse. Its axes are the principal components, and the semi-axis lengths are proportional to λi\sqrt{\lambda_i} (here 3=1.73\sqrt3=1.73 and 11).

Explained variance, scree plots and choosing k

The explained variance ratio of component ii is its share of the total variance: λi/∑jλj\lambda_i\big/\sum_j\lambda_j. In the example, 3/4=75%3/4=75\% and 1/4=25%1/4=25\%. A scree plot draws the eigenvalues, or their ratios, in decreasing order; a cumulative version adds them up. How many components should we keep? There is no single rule. Common choices:

  • Keep enough components to reach a target share of the variance, often 9090 to 95%95\%. This is a convention, not a theorem, and the right level depends on the task.
  • Look for an “elbow” in the scree plot, where the eigenvalues stop falling steeply. It is a judgement, and some data have no clear elbow.
  • Treat kk as a hyperparameter and pick it by the score of the model that uses the components, measured on validation data (P3.A4).

Eigenvalues also tell the rank (P1.B7). Four centred points in 3-D that lie exactly in the plane x3=x1+x2x_3=x_1+x_2, for example (1,0,1)(1,0,1), (−1,0,−1)(-1,0,-1), (0,1,1)(0,1,1), (0,−1,−1)(0,-1,-1), have rank 22, and the covariance eigenvalues are 22, 0.6670.667 and 00: two directions describe everything. Real data are noisy, so the last eigenvalue is small but not 00. What PCA reports is an effective dimension: how many directions carry most of the variation.

Projecting and reconstructing

Keep the first kk components as the columns of a d×kd\times k matrix W\mathbf{W} with orthonormal columns. The kk scores of a centred example x\mathbf{x} are W⊤x\mathbf{W}^\top\mathbf{x}, and the point of the kk-dimensional subspace closest to it is x^=WW⊤x\hat{\mathbf{x}}=\mathbf{W}\mathbf{W}^\top\mathbf{x}, the projection of P1.B11. For the whole data matrix, the codes are XW\mathbf{X}\mathbf{W} and the reconstruction is XWW⊤\mathbf{X}\mathbf{W}\mathbf{W}^\top. To get back to the original units, add the mean again.

With k=1k=1 in the example, the four points are rebuilt as (−1.5,−1.5)(-1.5,-1.5), (1.5,1.5)(1.5,1.5), (0,0)(0,0) and (0,0)(0,0). Their squared errors are 0.50.5, 0.50.5, 22 and 00: the total is 33, and divided by N−1=3N-1=3 it is 11. That is the discarded eigenvalue, λ2=1\lambda_2=1. This holds in general:

1N−1∑i∥xi−x^i∥2=λk+1+⋯+λd.\begin{aligned} &\frac1{N-1}\sum_i\lVert\mathbf{x}_i-\hat{\mathbf{x}}_i\rVert^2\\ &=\lambda_{k+1}+\cdots+\lambda_d. \end{aligned}

The error is the sum of the discarded eigenvalues, and the share of variance kept is 11 minus the error over the total. Keeping the top kk directions is the best rank-kk approximation of the data matrix (the Eckart–Young theorem of P1.B13): no other kk-dimensional subspace leaves less squared error.

The line of least perpendicular distance

There is a second way to say what the first component is. For each centred point, Pythagoras gives ∥xi∥2=(u⋅xi)2+di2\lVert\mathbf{x}_i\rVert^2=(\mathbf{u}\cdot\mathbf{x}_i)^2+d_i^2, where did_i is the perpendicular distance to the line. The left side does not depend on the line. So the sum of squared projections plus the sum of squared perpendicular distances is a constant: here 12=3×412=3\times4, which is (N−1)(N-1) times the total variance. Maximizing the first sum is the same as minimizing the second. PCA’s line is the line of least squared perpendicular distance, and also the line of greatest projected variance. This is the bar of the widget: its two colours always add up to the same total.

This is not the regression line of P3.A2. Linear regression minimizes vertical distances, the errors in predicting yy. For the four points, the regression of yy on xx has slope Cov/Var(x)=0.5\mathrm{Cov}/\mathrm{Var}(x)=0.5 and a vertical squared error of 4.54.5. Regressing xx on yy gives a line with slope 22 in the (x,y)(x,y) plane. The PC1 line has slope 11, between them, and its perpendicular squared error is 33, lower than the 3.63.6 that the regression line has when measured the same way. The PC1 line is also called total least squares. Unlike the regression line, it changes if you rescale one of the features, which brings us to the next topic.

Standardizing: when the units decide

PCA looks for the largest variance, and the size of a variance depends on the unit. Measure the second feature of the four-point example in units that are 10001000 times smaller (grams instead of kilograms, say). The covariance matrix becomes (2100010002 000 000)\begin{pmatrix}2&1000\\1000&2\,000\,000\end{pmatrix}, the eigenvalues are 1.51.5 and 2 000 000.52\,000\,000.5, and PC1 is almost exactly the second axis, (0.0005,1)(0.0005,1), with 99.9999%99.9999\% of the variance. Nothing about the people changed, only a unit. The widget’s unequal-units preset shows the same effect.

The remedy is to standardize each column first (subtract the mean, divide by the standard deviation, P3.A11), then run PCA. The covariance matrix of standardized data is the correlation matrix, so this is also called correlation PCA. For the example the correlation is 0.50.5 and the matrix is (10.50.51)\begin{pmatrix}1&0.5\\0.5&1\end{pmatrix}, with eigenvalues 1.51.5 and 0.50.5: shares of 75%75\% and 25%25\%, whatever the units. With two features the first component of standardized data is always at 45°45° (or 135°135° for a negative correlation), unless the correlation is exactly 00, when every direction ties. A correlation near 00 makes that direction very unstable. Only the shares, 1±r1\pm r over 22, carry information. The total variance of standardized data is dd, the number of features.

When to standardize? If the features have different units or arbitrary scales, standardize. If they share a natural unit whose differences in size are meaningful, such as the pixels of an image, centring alone is usual. This is a choice, and the two give different components; neither is wrong, they answer different questions.

PCA in practice, with real output

The code below uses scikit-learn, which the in-browser runner does not have, so it is shown as a static block with real output from a local run (scikit-learn 1.8). The two data sets, iris (150 flowers, 4 measurements in cm) and digits (1797 images of 8×8=648\times8=64 pixels), come bundled with scikit-learn; no data are copied into this site.

import numpy as np
from sklearn.datasets import load_iris, load_digits
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split

X, _ = load_iris(return_X_y=True)
print("iris raw", PCA().fit(X).explained_variance_ratio_.round(4))
Xs = StandardScaler().fit_transform(X)
print("iris std", PCA().fit(Xs).explained_variance_ratio_.round(4))

d, y = load_digits(return_X_y=True)
pca = PCA().fit(d)
cum = pca.explained_variance_ratio_.cumsum()
print("digits, first two:", pca.explained_variance_ratio_[:2].round(4))
for t in (0.90, 0.95, 0.99):
    print(f"  components for {t:.0%}:", int(np.searchsorted(cum, t) + 1))

p2 = PCA(n_components=2).fit(d)
err = ((d - p2.inverse_transform(p2.transform(d))) ** 2).sum() / (len(d) - 1)
print("k=2 error/(N-1):", err.round(2))
print("discarded eigenvalues:", pca.explained_variance_[2:].sum().round(2))

Xtr, Xte, ytr, yte = train_test_split(d, y, test_size=0.25, random_state=0, stratify=y)
full = LogisticRegression(max_iter=5000).fit(Xtr, ytr)
model = make_pipeline(PCA(n_components=0.95),
                      LogisticRegression(max_iter=5000)).fit(Xtr, ytr)
print("64 pixels, test accuracy:", round(full.score(Xte, yte), 4))
print("PCA components kept:", model[0].n_components_)
print("PCA test accuracy:", round(model.score(Xte, yte), 4))
iris raw [0.9246 0.0531 0.0171 0.0052]
iris std [0.7296 0.2285 0.0367 0.0052]
digits, first two: [0.1489 0.1362]
  components for 90%: 21
  components for 95%: 29
  components for 99%: 41
k=2 error/(N-1): 859.42
discarded eigenvalues: 859.42
64 pixels, test accuracy: 0.96
PCA components kept: 28
PCA test accuracy: 0.9556

What the output shows:

  • Iris. The raw features are all in cm, but their spreads differ (standard deviations from 0.440.44 to 1.771.77). The first component takes 92.5%92.5\% of the variance, and most of it is the feature with the largest spread, the petal length. After standardizing, the first takes 73.0%73.0\% and the second 22.9%22.9\%: the answer depends on whether you standardize.
  • Digits. The first two components together hold only 28.5%28.5\% of the variance, so a 2-D picture of the digits is a rough view. It takes 2121 components for 90%90\%, 2929 for 95%95\% and 4141 for 99%99\%. So 2121 of the 6464 components, about a third, hold 90%90\% of the variance.
  • Reconstruction. With k=2k=2 the error divided by N−1N-1 is 859.42859.42, exactly the sum of the other 6262 eigenvalues, as the formula above says.
  • A pipeline. The logistic regression on all 6464 pixels scores 0.960.96 on the held-out test set. With PCA keeping 2828 components (enough for 95%95\% of the training variance) it scores 0.95560.9556. This is one split of one data set: it shows that far fewer inputs lose little, not that PCA helps accuracy.

Fit on the training data only

PCA learns from data: the means to subtract and the directions to keep. If it is fitted on all rows before a train and test split, the test rows have shaped the features, which is leakage (P3.A11, P3.A4). Fit on the training rows only, and apply the training mean and directions to validation and test rows: reduce(rows) = (rows - train_mean) @ W. In scikit-learn, put PCA in a pipeline, as above, and the pipeline does this each time it is fitted.

Limits

  • Only straight directions. PCA is linear. Data on a curve, such as a spiral or a ring, may need many components to describe, though a single number (the position along the curve) would do. Nonlinear maps are the subject of P3.C4 (t-SNE and UMAP), and autoencoders are neural networks that learn a curved code (P8.2).
  • Outliers. Variance is a sum of squares, so far-away points have a big say. Add one more person at (16,14)(16,14), which is (6,−6)(6,-6) after subtracting the old mean (10,20)(10,20). Centre all five points on their new mean and the covariance eigenvalues become 15.1515.15 and 2.252.25 with PC1 at 135°135°, turned by 90°90° from the 45°45° of before. Look for outliers before PCA.
  • Interpretation. Each component is a mixture of all the original features. A component may have no tidy meaning, and its signs are arbitrary.
  • Variance is not relevance. PCA never sees a label. The direction with the least variance can be the one that separates two classes. Whether to keep a component is a question for the task, which is why the number of components can be chosen on validation data.
  • It needs numbers that make sense to add. Categories encoded as integers, or columns with wildly different meanings, give components with no meaning.

Depth: three ways to see it

Intuition

Think of the shadow of a cloud of points on a wall. Turn the wall and the shadow changes: from a bad angle the points pile on top of each other and the shadow is short, from a good angle the shadow is long and the points stay spread out. PCA picks the wall angle with the longest, most spread-out shadow, then the next best angle at right angles, and so on. The analogy breaks because a real shadow is of a 3-D object on a 2-D wall, while PCA also works with 64 features and any number of kept directions, and because the shadow only shows straight projections.

Math

For centred X∈RN×d\mathbf{X}\in\mathbb{R}^{N\times d}, Σ=1N−1X⊤X=VΛV⊤\boldsymbol\Sigma=\frac{1}{N-1}\mathbf{X}^\top\mathbf{X}=\mathbf{V}\boldsymbol\Lambda\mathbf{V}^\top with λ1≥⋯≥λd≥0\lambda_1\ge\cdots\ge\lambda_d\ge0. The component v1=arg⁡max⁡∥u∥=1u⊤Σu\mathbf{v}_1=\arg\max_{\lVert\mathbf{u}\rVert=1}\mathbf{u}^\top\boldsymbol\Sigma\mathbf{u}, and vj\mathbf{v}_j maximizes the same quantity among unit vectors perpendicular to v1,…,vj−1\mathbf{v}_1,\dots,\mathbf{v}_{j-1}. Explained variance ratio λj/tr⁡Σ\lambda_j/\operatorname{tr}\boldsymbol\Sigma. Scores Z=XV\mathbf{Z}=\mathbf{X}\mathbf{V}, with covariance Λ\boldsymbol\Lambda. Reconstruction from kk components: X^=XVkVk⊤\hat{\mathbf{X}}=\mathbf{X}\mathbf{V}_k\mathbf{V}_k^\top, with 1N−1∥X−X^∥F2=∑j>kλj\frac1{N-1}\lVert\mathbf{X}-\hat{\mathbf{X}}\rVert_F^2=\sum_{j>k}\lambda_j. From the SVD X=USV⊤\mathbf{X}=\mathbf{U}\mathbf{S}\mathbf{V}^\top (S\mathbf{S} holds the singular values, called Σ\boldsymbol\Sigma in P1.B13): λj=sj2/(N−1)\lambda_j=s_j^2/(N-1) and Z=US\mathbf{Z}=\mathbf{U}\mathbf{S}.

Code

import numpy as np

def pca_fit(X, k):
    mean = X.mean(axis=0)
    U, S, Vt = np.linalg.svd(X - mean, full_matrices=False)
    eig = S**2 / (len(X) - 1)             # variance along each component
    return mean, Vt[:k].T, eig            # mean, (d, k) directions, all eigenvalues

def pca_transform(X, mean, W):
    return (X - mean) @ W                 # always the TRAIN mean and directions

scikit-learn’s PCA does the same and adds transform, inverse_transform and explained_variance_ratio_. It centres the data but does not scale it.

Go deeper Why the top eigenvector maximizes the variance, and why the next one is perpendicular

Maximize u⊤Σu\mathbf{u}^\top\boldsymbol\Sigma\mathbf{u} subject to u⊤u=1\mathbf{u}^\top\mathbf{u}=1. The Lagrangian is u⊤Σu−μ(u⊤u−1)\mathbf{u}^\top\boldsymbol\Sigma\mathbf{u}-\mu(\mathbf{u}^\top\mathbf{u}-1), and setting its gradient to zero gives Σu=μu\boldsymbol\Sigma\mathbf{u}=\mu\mathbf{u}: u\mathbf{u} is an eigenvector and μ\mu an eigenvalue (P1.F7). At such a point the value is u⊤Σu=μ\mathbf{u}^\top\boldsymbol\Sigma\mathbf{u}=\mu, so the largest value is the largest eigenvalue. For the second component, add the constraint u⊥v1\mathbf{u}\perp\mathbf{v}_1. In the eigenbasis, write u=∑jcjvj\mathbf{u}=\sum_jc_j\mathbf{v}_j with ∑cj2=1\sum c_j^2=1. Then the variance is ∑jλjcj2\sum_j\lambda_jc_j^2, a weighted average of the eigenvalues, so it is largest when all the weight sits on the largest eigenvalue allowed. With c1=0c_1=0 that is λ2\lambda_2, at v2\mathbf{v}_2.

Go deeper Whitening

Dividing each score by λj\sqrt{\lambda_j} gives scores with variance 11 and covariance 00: a whitened version of the data. It is sometimes used before algorithms that assume a round cloud. Directions with tiny eigenvalues are mostly noise, and dividing by their small λj\sqrt{\lambda_j} boosts that noise, so whitening is usually combined with dropping them.

Try it in NumPy

In the first cell, the four points go through the three routes: a scan over angles, eigh on the covariance matrix and svd of the centred data. In the second cell, a made-up data set with five features that are mixtures of two hidden factors shows the explained ratios, a fit on the training rows only, and the reconstruction error as the sum of the discarded eigenvalues. np.linalg.eigh is for symmetric matrices and returns the eigenvalues in ascending order, so the code reverses them.

Try it: the four-point example three ways

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

To see the outlier of the limits section, add the row [16, 14] to raw (the point (6,−6)(6,-6) in centred coordinates, shifted by the old mean (10,20)(10,20)) and watch PC1 turn.

Try it: explained variance, fit on train only, reconstruction

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

The ratios show two strong directions, which matches the two hidden factors, and the three small ones are noise. The test error is about the same as the training error, because the directions describe the structure and not the particular rows. Notice that the test rows were centred with the training mean.

Common mistakes

Exercises

  1. A covariance matrix has eigenvalues 66, 33 and 11. Give the explained variance ratios, the smallest kk that reaches 90%90\%, and the error (divided by N−1N-1) when k=1k=1.
    Show answerThe total is 1010, so the ratios are 0.60.6, 0.30.3 and 0.10.1. One component gives 60%60\% and two give 90%90\%, so k=2k=2 reaches 90%90\%. With k=1k=1 the error is the sum of the discarded eigenvalues, 3+1=43+1=4.
  2. For Σ=(2112)\boldsymbol\Sigma=\begin{pmatrix}2&1\\1&2\end{pmatrix}, find the variance of the projections onto the unit vector u=(0.6,0.8)\mathbf{u}=(0.6,0.8).
    Show answeru⊤Σu=2(0.36)+2(1)(0.48)+2(0.64)=0.72+0.96+1.28=2.96\mathbf{u}^\top\boldsymbol\Sigma\mathbf{u}=2(0.36)+2(1)(0.48)+2(0.64)=0.72+0.96+1.28=2.96. This is between the smallest and largest eigenvalues, 11 and 33, as it must be.
  3. A centred data matrix with 200200 rows has singular values 2020 and 1010 (and no others). Find the two variances and the explained variance ratios.
    Show answerλi=si2/(N−1)\lambda_i=s_i^2/(N-1), so λ1=400/199=2.010\lambda_1=400/199=2.010 and λ2=100/199=0.503\lambda_2=100/199=0.503. The ratios are 400/500=0.8400/500=0.8 and 0.20.2; the divisor N−1N-1 cancels in a ratio.
  4. Two features have standard deviations 11 and 100100 and correlation 0.80.8. Which direction does PCA on the raw covariance follow, and what are the explained ratios of PCA on the standardized data?
    Show answerOn the raw data the variances are 11 and 10 00010\,000, so PC1 follows the second feature almost exactly. On standardized data the correlation matrix has eigenvalues 1.81.8 and 0.20.2, so the ratios are 0.90.9 and 0.10.1, with PC1 at 45°45°.
  5. Why must new rows be centred with the training mean, and not with their own mean?
    Show answerThe directions were learned for data centred on the training mean. A new row means the same thing only if it is shifted by the same amount. Centring each test set with its own mean would shift every test set differently (a single row would become the zero vector), and using test data to fit anything is leakage.
  6. Centred 3-D data have covariance eigenvalues 22, 0.6670.667 and 00. What is the rank of the data matrix, and what is the reconstruction error with k=2k=2?
    Show answerThe rank is 22, one eigenvalue being 00. With k=2k=2 the error is the discarded eigenvalue 00: the reconstruction is exact.
  7. The five points (−2,−1)(-2,-1), (1,2)(1,2), (1,−1)(1,-1), (0,0)(0,0) and (6,−6)(6,-6) have mean (1.2,−1.2)(1.2,-1.2). After centring them on that mean, the covariance eigenvalues are 15.1515.15 and 2.252.25. What share of the variance does PC1 explain?
    Show answer15.15/17.4=0.87115.15/17.4=0.871, so 87.1%87.1\%. The share is high, but PC1 now points along (1,−1)(1,-1), the outlier’s direction, which says more about one point than about the other four.

Check your understanding

  1. Which unit vector u\mathbf{u} gives the largest variance of the projections of centred data?

  2. A covariance matrix has eigenvalues 33 and 11. Keeping only the first component, what is the squared reconstruction error divided by N−1N-1?

  3. A data set has columns in kilograms and in grams, and you run PCA on the raw covariance matrix. What happens, and what is the usual fix?

  4. You want to test a model that uses 10 PCA components as inputs. Which procedure avoids leakage?

  5. How does the first principal component line differ from the least-squares regression line of yy on xx?

Next: P3.C4 draws data with curved, nonlinear maps and explains how to misread them. P3.C5 uses reconstruction error to find anomalies, and P8.2 replaces PCA’s straight directions with a neural network. P3.C1 and P3.C2 group the same kind of unlabelled data without reducing it.

Key takeaways

  • PCA centres the data and finds the direction along which the projections have the largest variance, then the largest variance among directions perpendicular to the first, and so on. The directions are orthonormal and the coordinates along them are uncorrelated.
  • Three routes give the same answer: maximize uᵀΣu over unit vectors, take the top eigenvector of the covariance matrix Σ = XᵀX/(N − 1), or take the first right singular vector of the centred X. The eigenvalue is the variance, λᵢ = sᵢ²/(N − 1). For the four-point example Σ = [[2, 1], [1, 2]], λ = 3 and 1, along 45° and 135°.
  • The explained variance ratio of component i is λᵢ divided by the sum of all eigenvalues (the trace, the total variance). Plot the eigenvalues (a scree plot) and keep k components, often enough for 90 to 95% of the variance: a rule of thumb, not a theorem.
  • Keeping k components and rebuilding leaves a squared error equal to the discarded eigenvalues (times N − 1). The same line minimizes the squared perpendicular distances and maximizes the projected variance. The regression line minimizes vertical distances instead, so it is a different line.
  • Features in different units must be standardized first, or the biggest numbers decide the answer. Fit the centring and the directions on training data only. PCA is linear, sensitive to outliers, its signs are arbitrary, and its components are mixtures that need not matter for the label.
Found a mistake? Tell us