Back to Tutorials
Machine Learning
Intermediate

PCA for Dimensionality Reduction

Keep most of what your data says with far fewer numbers. Turn a line through a cloud by hand, compress a picture, and meet the units mistake that breaks it.

10 minInteractive: drag, click and try things as you read


Real datasets have dozens, sometimes thousands, of columns, and many of them say nearly the same thing. PCA finds the few directions your data really varies in, so you can describe each row with a handful of numbers instead of all of them. It keeps as much of the spread in your data as possible while throwing away as many numbers as possible. Here you’ll find those directions by hand, compress a picture with them, and meet the one mistake that quietly breaks it.

Two numbers into one#

Here are 60 people, with two measurements each: height and arm span. The two go together, since tall people tend to have long arms, so the points form a narrow cloud running diagonally.

Suppose you could only keep one number per person. One way to choose it: draw a line through the middle of the cloud and drop each point onto it at a right angle. Each person’s new number is where they land along the line. What survives is the spread along the line; what’s lost is the spread across it, the red lines. Statisticians measure spread as variance: the average squared distance from the middle.

Predict first

Which line keeps the most of the spread?

Try it
The 60 people are made up for the demo. Drag on the chart, or use the slider, to turn the line; every point drops onto it at a right angle. The bar shows how much of the total spread survives.

Keeping only height keeps 47.7% of the spread, and only arm span keeps 52.3%. The best line, at about 46°, keeps 95.9%: one number per person instead of two, and barely anything lost. That line is called the first principal component. The first principal component is the direction in which the data spreads out the most. Here it’s something like “overall size”: people far along it are tall and long-armed.

Watch the red lines as you turn: they’re shortest exactly when the bar is greenest. That’s not a coincidence. Each point’s distance from the middle is fixed, and by Pythagoras it splits into a part along the line and a part across it. Keeping the most and losing the least are the same goal.

The 4.1% that’s left lives along the second principal component, at right angles to the first: whose arms are long or short for their height. Two measurements give two components. Fifty give fifty, each at right angles to all the ones before it, each holding less of the spread than the last. PCA is just this: turn your axes to line up with the data, then drop the ones the data barely moves along.

How many components should you keep?#

With two columns the answer is easy. With many, PCA gives you a ranking and you pick where to stop. To see it, here’s a picture of 48 × 48 pixels, treated as data: each of its 48 rows of pixels is one data point with 48 numbers. PCA finds 48 components. Keep the first few, throw away the rest, and rebuild the picture from what’s left.

Predict first

Out of 48 components, how many do you need before the picture is clearly recognisable?

Try it
The picture is drawn by code for the demo. PCA runs on its rows in your browser; drag the slider, or tap a bar, to keep more components.

One component keeps 27.3% of the variance and gives a blurry ghost. By 8 components it’s 88.6% and the face, the wink and the sun are all there; by 13 it’s 95.7%. The bars underneath are a scree plot: the share of the variance each component holds (scikit-learn calls it the explained variance ratio). Each bar is smaller than the one before, and the useful place to stop is usually where they flatten out.

A common starting point is to keep enough components for 90–95% of the variance, then check that whatever you use the data for still works. One honest catch: storing the components costs numbers too. From 24 components on, you’d be storing more numbers than the picture had in the first place. Real image formats use other tricks; this picture is here to show the idea.

The mistake that breaks it: units#

PCA chases variance, and variance depends on the units your numbers happen to be in. That causes trouble whenever your columns are measured in different units.

Predict first

Same 60 people, but now height is typed in metres (1.59) while arm span stays in centimetres (155.3). What does the first principal component become?

Try it
The same 60 people. The chart shows the numbers the way PCA sees them, with both axes on the same scale, and the yellow line is the first principal component.

In metres, the first component is 100% arm span and claims to keep 100.0% of the variance. It looks perfect, and it has simply ignored height. Switch to millimetres and it flips to 99% height. Same people, opposite answers.

The fix is to standardise first: subtract each column’s average and divide by its spread, so every column has a spread of 1 (that’s what scikit-learn’s StandardScaler does). Tick the box and the answer stops depending on the units: a 50/50 mix keeping 95.9%, whichever unit you pick. Standardise your columns before PCA unless they already share a unit. The picture didn’t need it, because every pixel is measured the same way.

When PCA helps, and when it doesn’t#

It earns its place in a few common jobs:

  • Seeing your data. Squash dozens of columns down to two and plot them, to spot groups and outliers you can’t see in a table.
  • Fewer, cleaner inputs. Feed a model ten components instead of a hundred columns that overlap. It trains faster, and dropping the smallest components can drop some noise with them.

And it has limits worth knowing:

  • Components are mixtures of your columns, so they’re harder to explain than the columns themselves.
  • It only finds straight-line directions. Data that curves needs other tools; t-SNE and UMAP are popular for plotting it.
  • Big spread isn’t always what matters. The direction that separates the groups you care about can be a small one, and PCA might throw it away.
  • Fit the scaler and the PCA on your training data only, then apply them to the test data, or information from the test set leaks into training.

In code#

scikit-learn includes a small real dataset of 178 wines with 13 chemical measurements each, in very different units. Here’s PCA without scaling, then with it:

from sklearn.datasets import load_wine
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler

X, y = load_wine(return_X_y=True)                  # 178 wines x 13 measurements

raw = PCA().fit(X)
print(raw.explained_variance_ratio_[:2].round(3))  # [0.998 0.002]  one column wins

X_scaled = StandardScaler().fit_transform(X)
pca = PCA(n_components=0.95).fit(X_scaled)          # keep 95% of the variance
print(pca.n_components_)                            # 10
print(pca.explained_variance_ratio_[:2].round(3))   # [0.362 0.192]
reduced = pca.transform(X_scaled)                   # 178 x 10

Without scaling, the first component holds 99.8% of the variance and is almost entirely one column, proline, whose values run into the hundreds and thousands. After scaling, the spread is shared out: ten components keep 95%, and the first two keep about 55%, enough to plot the wines and see them group by grape.

What to remember

  • PCA finds the directions your data spreads out along most, ranked from most to least, each at right angles to the others.
  • Keep the first few components and you keep most of the variance with far fewer numbers; the scree plot shows where to stop.
  • Variance depends on units, so standardise your columns first unless they already share one.

Keep going

Sign in to save your place and keep a learning streak. Free, with Google.