Traditional models · lesson 10 of 16
Parts in this lesson
AXc.T @ Xc / (len(X) - 1)the covariance matrix of centred data
Bnp.linalg.eigh(C)1.5: eigenvalues and eigenvectors of a symmetric matrix
CPCA(20).fit_transform(X)64 numbers down to 20
Dpca.explained_variance_ratio_how much variation each component keeps

Dimensionality reduction: PCA

Last updated

An 8 × 8 digit has 64 pixels, but it doesn't need 64 numbers: neighbouring pixels move together, and the corners are almost always blank. Principal component analysis finds the few directions in which the data really varies, and describes each example by where it lies along them. Twenty numbers keep 90% of a digit's variation. It's lesson 1.5's eigenvectors, put to work.

By the end of this lesson you can

  • Explain principal components as the directions of most variance
  • Compute them by hand from the covariance matrix, and with scikit-learn
  • Choose how many components to keep from the explained variance
  • Explain why PCA needs centred data

Many features, little information

Data often has more columns than it has information. A penguin's flipper length and body mass rise together, so knowing one tells you much of the other. A digit's 64 pixels aren't 64 independent facts: the corner pixels are nearly always 0, and each pixel is a lot like its neighbours.

Dimensionality reduction describes each example with fewer numbers while keeping as much of what matters as possible. Fewer numbers means faster models, plots you can draw, less noise, and for distance-based models like k-NN, distances that mean more (lesson 4.2's noisy features). Principal component analysis (PCA; Pearson 1901, Hotelling 1933) is the classic way: it keeps the directions in which the data varies most.

The direction of most variance

Take 80 points in 2-D, stretched along a diagonal, and centred on 0. Draw a line through the centre. Each point casts a shadow on the line, its projection (lesson 1.3), and the shadows have some spread. Turn the line:

Spinning axis80 points, centred
variance of the shadows0°90°180°angle of the line

The shadows (pink) spread with variance 1.07. The most possible is 3.86, at 29°. Turn the line to find it.

The spread is biggest along one direction, the first principal component: the line that keeps the most of how the points differ. The smallest spread is at right angles to it, the second component. Describe each point by its shadow on the first component alone, one number instead of two, and you keep most of the variation, losing only the small wobble across the line.

In more dimensions, the second component is the direction of most remaining variance at right angles to the first, the third at right angles to both, and so on: a new set of axes, ordered from most important to least.

Covariance and eigenvectors

The spread of the shadows along a unit vector u is u⊤Cu, where C is the covariance matrix of the centred data Xc:

C=1n−1Xc⊤Xc

Entry (j,k) of C says how features j and k vary together; the diagonal holds each feature's variance. And the u that makes u⊤Cu biggest is C's eigenvector with the biggest eigenvalue (lesson 1.5), and the eigenvalue is the variance along it. So the principal components are the eigenvectors of the covariance matrix, in order of their eigenvalues.

pca.ipynb

The eigenvalues are 4.63 and 0.21: along the first component the variance is 4.63, across it 0.21. The first component alone keeps 4.634.63+0.21=95.6% of the total variance. scikit-learn agrees:

pca.ipynb

The same variances, and the same direction, pointing the other way: an eigenvector's sign is arbitrary, since −u is the same line.

Wrong way: forgetting to centre

The cloud is centred at (2,10), not at 0. Skip the centring and find the "first direction" of the raw data:

pca.ipynb

(−0.22,−0.98), nearly straight up, nowhere near the cloud's real stretch, (0.89,0.46). Without centring, the biggest "variation" is the distance from the origin to the middle of the cloud, so the first direction just points at the cloud. That's why the covariance uses Xc, and why scikit-learn's PCA always subtracts the mean first.

Scaling matters too, for a different reason. If one feature is in grams and another in millimetres, the grams have the bigger variance and take over the first component. Unless the features share a unit, standardise them first (lesson 4.1).

Explained variance, and eigen-digits

On the 64-pixel digits, how many components keep how much?

pca.ipynb

5 components keep half the variance, 13 keep 80%, 21 keep 90% and 29 keep 95%. The components are themselves 64-pixel images, so they can be drawn:

pca.ipynb

The mean digit is a blurry smudge. Each component is red where it adds ink and blue where it takes ink away, and a digit is the mean plus some amount (positive or negative) of each component. These eigen-digits are the building blocks, the most useful first. Rebuild the first digit, a 0, from more and more of them:

pca.ipynb

From 2 numbers, a blurry ring: a 0 is one of the easiest digits, and the first two components already point towards it. From 5, clearly a 0. From 20, close to the original, which is all 64, with only small differences in the shading.

PCA before a model

PCA can go at the front of a pipeline, so the model sees fewer, less noisy features:

pca.ipynb

Logistic regression on 5 components: 82.3%; on 20: 89.5%; on all 64 pixels: 91.3%. Here PCA costs a little accuracy, and buys a model about three times smaller. On data with many noisy, overlapping features, it can help accuracy too. Whether it does is a question for cross-validation, with the number of components as one more setting to tune (lesson 4.13).

PCA only finds straight directions. Data on a curved surface, like a rolled-up sheet, needs a non-linear method; lesson 4.11 meets two, for drawing maps.

When to use it

When to use PCA

Good at

  • Compressing many overlapping features into a few
  • Removing noise before a distance-based model
  • A quick 2-D plot of high-dimensional data
  • Speeding up a slow model

Bad at

  • Curved structure: it only finds straight directions
  • Explaining a model: each component mixes every original feature
  • Features in different units, unless you standardise first

Needs from you

  • Centred data (scikit-learn does it), and usually standardised
  • The number of components: by explained variance, or by cross-validation

In scikit-learn

  • Classification: none: it transforms features; PCA, TruncatedSVD (for sparse data)
  • Regression: none

Check what you learned

What is the first principal component of a data set?
PCA on a table of height in centimetres and weight in kilograms gives a first component almost exactly along height. What’s the likely cause?
The explained variance ratios of a data set’s first three components are 0.70, 0.20 and 0.05. How much variance do the first two keep?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Machine Learning