Lesson 17 of 228 min
PCA
Because measurements move together, a few directions hold most of how things differ: PCA keeps those directions and drops the rest.
After this lesson you can reduce dimensions by keeping the directions with the most variance, and read a t-SNE or UMAP map without being misled.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
Keep a share, not a count
Put the Palmer Penguins penguins.csv next to your notebook. A number between 0 and 1 in n_components keeps as many directions as it takes to reach that share of the variance. The penguins need 3 directions for 95%. The digits need 29 of their 64. PCA reference
import pandas as pd
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
four = ["bill_length_mm", "bill_depth_mm", "flipper_length_mm", "body_mass_g"]
penguins = pd.read_csv("penguins.csv").dropna(subset=four)
pca = make_pipeline(StandardScaler(), PCA(n_components=0.95)).fit(penguins[four])
print(pca[-1].n_components_, PCA(n_components=0.95).fit(load_digits().data).n_components_)3 29
Read what a direction is made of
components_ holds each direction's weights, one for each measurement. The first direction weighs all four about the same, with the bill's depth the other way: it is a penguin's size. The second is almost all bill: its shape. The signs of a whole row may flip from one version to the next, and that's fine.
pca = make_pipeline(StandardScaler(), PCA(n_components=2)).fit(penguins[four])
print(pd.DataFrame(pca[-1].components_.round(2), columns=four, index=["first", "second"]))bill_length_mm bill_depth_mm flipper_length_mm body_mass_g first 0.46 -0.4 0.58 0.55 second 0.60 0.8 0.00 0.08
Squash before a model
PCA in a pipeline sends the training rows and every new row through the same average, spread and directions. Here a model reads the digits as 21 numbers instead of 64, which keeps 90% of their variance, and it scores almost the same on pictures it never saw. The pixels share one unit, so they need no scaler.
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
digits = load_digits()
train_x, test_x, train_y, test_y = train_test_split(digits.data, digits.target, test_size=0.25, random_state=0)
for n in (64, 21):
model = make_pipeline(PCA(n_components=n), LogisticRegression(max_iter=5000))
print(n, round(model.fit(train_x, train_y).score(test_x, test_y), 3))64 0.951 21 0.947
A map's settings move its gaps
t-SNE's perplexity and UMAP's n_neighbors say how many neighbors each point looks at. Change them and the islands stay, but the gaps between them grow and shrink. This prints the distance between the middle of the zeros and the middle of the nines on each map. openTSNE and PaCMAP are newer map-makers with the same warning.
import numpy as np
import umap
from sklearn.manifold import TSNE
def gap(flat):
flat = (flat - flat.mean(0)) / flat.std()
zeros, nines = flat[digits.target == 0].mean(0), flat[digits.target == 9].mean(0)
return round(float(np.linalg.norm(zeros - nines)), 2)
for n in (5, 15, 100):
print("n_neighbors", n, gap(umap.UMAP(n_neighbors=n, random_state=0).fit_transform(digits.data)))n_neighbors 5 1.46 n_neighbors 15 2.57 n_neighbors 100 1.85
Look at a map, don't model on it
A t-SNE map is made for the rows it was given. It has no transform, so a new row has no place on it, and a new run moves every island. Cluster or train on the numbers themselves, or on PCA's directions. Use the map to look. t-SNE reference
tsne = TSNE(random_state=0).fit(digits.data)
print(hasattr(tsne, "transform"))False
How scikit-learn finds the directions
The chapter found them as the eigenvectors of the matrix of how the measurements move together. scikit-learn gets the same directions from the SVD of the table on one ruler, which is faster and more exact. Both give the same shares.
scaled = StandardScaler().fit_transform(penguins[four])
u, s, vt = np.linalg.svd(scaled, full_matrices=False)
print((s**2 / (s**2).sum()).round(4))
print(PCA().fit(scaled).explained_variance_ratio_.round(4))[0.6884 0.1931 0.0913 0.0271] [0.6884 0.1931 0.0913 0.0271]
Run on Python 3.13.3, pandas 3.1.1, scikit-learn 1.9.1 and umap-learn 0.6.0. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: Eigenvectors and eigenvalues
[[2, 1], [1, 2]] stretches [1, 1] three times. You move [1, 1] with this matrix, then move where it landed once more. What is the first number of where it ends?
2 of 3
PCA squashes the penguins' four measurements into two new numbers, and keeps 88% of how they differ, not half. Why so much?
3 of 3
On a UMAP map of the handwritten digits, every digit has its own tight island, and the 0s' island sits far from the 9s'. What can you trust from this map?
The ideas in this lesson
- PCA
- Find the directions with the most variance, each at a right angle to the last, and keep the first few.
- How much each keeps
- Each direction keeps a share of the total variance; add the shares to see what a few directions keep.
- Reading t-SNE and UMAP maps
- They keep each point's nearest neighbours near: trust the islands, not their tightness or the gaps between them.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
PCA
Here's a puzzle. Each penguin has four measurements. A flat picture can only show two. So we squash the four into two new numbers. How much of the difference between penguins is left? About half?
Keep your guess
Hold on to your guess.
Here are three hundred and forty-two penguins, of three kinds: Adelie, Chinstrap and Gentoo.
Each one has a bill length, a bill depth, a flipper length and a mass.
Most of it is left
Here they are, squashed into two new numbers and drawn as a flat map.
Eighty-eight percent of the difference between penguins is still there. Nearly nine tenths. And the kinds still show. The Gentoos stand apart, and the Chinstraps sit above the Adelies, even though nobody told the squash which penguin is which kind.
If you said half, two numbers out of four, that's the natural guess. So why is so much left?
They move together
Squashing many numbers into a few works for one reason.
The measurements move together. A penguin with a long flipper usually has a long bill. A penguin with a deep bill usually has a short flipper. A box can hold three measurements, so take three of the four.
First put them on one ruler: subtract each one's average, and divide by its spread. Now each penguin is a point in the box.
Turn the box. The penguins don't fill a round ball. They make a long, flat cloud.
Shadows on a line
Long in which direction?
And how do you even measure long?
Put a line through the middle of the cloud. Drop every penguin onto it, at a right angle, like a shadow on a wall. How much the shadows differ is their variance: their average squared distance from the cloud's middle. It says how much the penguins differ along that line.
One ruler makes each measurement's variance exactly one, so the three hold three in all. Along the flipper's own axis, the shadows hold one. A third. Can a line hold more?
The first direction
Turn the line, and watch the number. It climbs. At its highest... two.
Two thirds of the variance, on one line.
That line is the first direction. It mixes all three measurements: bills that are longer but less deep, and longer flippers. It runs from the Adelies to the Gentoos.
The second direction
What's left? At a right angle to the first, find the line that holds the most of the rest. It holds zero point seven seven of the three. About a quarter.
A flat map
The two directions make a flat sheet. Drop every penguin onto it, and turn to face it. How much of the variance will the flat map keep?
Ninety-two percent. Only the cloud's thickness is left out. Add up all three directions, and you get back the three we started with. Finding these directions, and keeping the first few, is called PCA.
That's short for principal component analysis, and the directions are its components. Squashing many numbers into a few is called dimensionality reduction.
Eigenvectors
Does the computer turn a line around and around to find them?
No. It builds one matrix, a grid of numbers: how each pair of measurements moves together.
Move the first direction's arrow with that matrix. The arrow lands on its own line, twice as long.
An arrow that a matrix only stretches is its eigenvector. And the stretch, two, is its eigenvalue.
It's the same two as the variance along that direction.
The other two directions are its other eigenvectors.
Shares add up
Each of PCA's directions holds a share of the variance.
Now back to all four measurements, and the flat map from the start. The first of their four directions keeps sixty-nine percent. The second, nineteen. The last two, very little. The first two, together?
Eighty-eight percent: the four measurements' flat map. So how many directions do you keep? Enough to hold most of the variance. Here, three keep ninety-seven percent.
Or keep just two, and draw a picture.
As measured
Now squash the four as they are, with the mass in grams.
The first direction keeps ninety-nine point nine nine percent. Is that a perfect squash?
No.
It's just the mass.
Grams are big numbers, so their variance is thousands of times bigger than the others'. Put every measurement on one ruler first.
Sixty-four numbers
To draw things with many numbers, you squash them into two.
These are handwritten digits: almost eighteen hundred pictures.
Each picture is sixty-four numbers. One for each pixel.
PCA keeps two directions and leaves out sixty-two.
Less than a third is left.
The digits pile on top of each other.
t-SNE and UMAP
So people use two other maps: t-SNE and UMAP. Look. An island for each digit. These maps don't keep any directions. They start with the points in random places. Then they move each picture next to the pictures that were nearest to it in the sixty-four numbers. On both maps, out of a picture's ten nearest on the map, ninety-eight in a hundred are the same digit. The islands are real.
Gaps are drawn
On this UMAP map, the zeros sit far from the nines. So are zeros and nines very different?
In the sixty-four numbers, the nines are the zeros' nearest digit. UMAP draws tight islands in a wide sea. In the sixty-four numbers, the groups are wide, and they sit much closer together. Run it again, from another random start, and the islands move. So read who's next to who, inside an island. And don't read anything into the gaps between the islands.
In code
In real code, with scikit-learn. A pipeline: a standard scaler, the one-ruler step, then PCA with two components. Run it on the four measurements. What shape comes out?
Three hundred and forty-two rows, with two numbers each.
And each direction's share, as decimals: the sixty-nine and the nineteen percent.
The two maps take one line each. A fixed random start gives the same map every time you run it.
The same lines draw maps of a model's vectors, with hundreds of numbers each. Tools for looking at embeddings offer these same three maps.
Three ideas
So: measurements move together. That's why a few directions hold most of the variance. PCA keeps the directions that hold the most, and their shares tell you how much is kept. t-SNE and UMAP only keep who's next to who. So you can trust the islands, but not the gaps between them.
The lab
That's the end of this unit. In the lab, you use these two lessons on the penguins, with their kinds hidden. You find their groups, and draw them on a flat map.
Keep the directions that hold the most
So PCA keeps the directions that hold the most. Now try it on this lesson's page, and take the quiz. Turn the line until it holds the least.
You use this lesson in Lab 6: The penguins' kinds, with the names hidden, which comes next.
Facts last checked on .
