Lesson 16 · Structure without labels
Principal component analysis
The problem
The shop knows what each of its 150 regular customers likes. For every customer it has a taste profile: the share of their orders in each of 6 topping groups.
| Customer | meat | veg | cheese | spicy | fruit | fish |
|---|---|---|---|---|---|---|
| 1 | 0.30 | 0.05 | 0.10 | 0.37 | 0.06 | 0.12 |
| 2 | 0.01 | 0.64 | 0.17 | 0.06 | 0.05 | 0.07 |
| 5 | 0.47 | 0.02 | 0.27 | 0.11 | 0.11 | 0.02 |
The numbers are made up for this book. The manager wants a picture of all 150 customers, to see what kinds there are. But each customer is 6 numbers, and a page has 2 directions.
There is no right answer to learn here, no label like "late" or "complaint". The data is all there is. Finding structure in data that comes with no labels is unsupervised learning. It's the other half of machine learning from supervised learning, which this course has done so far.
This lesson's job is to describe each customer with fewer numbers while losing as little as possible. That's called dimensionality reduction. The method here finds the directions in which the customers differ most, and keeps only those.
Spread along a direction
Start with 2 of the 6 numbers: the share of meat and the share of veg, as percentages. Each customer is a point. To describe each one with one number, pick a line through the middle of the cloud and drop every point onto it. Each customer's number is its position along the line.
Some lines are better than others. If the dropped points bunch up, the line has thrown away how the customers differ. If they spread out, it has kept most of it.
Spread is measured by variance: the average squared distance from the mean. So the question becomes: which line gives the dropped points the biggest variance?
Predict first
Meat lovers order lots of meat and little veg; veggies the opposite. Which line spreads the customers out most?
Angle 0°: variance along the line 372 · best so far 372 at 0°
Drag the purple handle round the centre, or the one on the angle axis. ● meat lover · ■ veggie · ▲ adventurous. The small dots on the line are the points dropped onto it.
Things to notice:
- At 0° the line is the meat axis, and the variance is the variance of meat: 372.
- The best line, at about 135°, gives 667. The worst, at right angles to it, gives only 85.
- The two lines are at right angles. That's not a coincidence, as we'll see.
How do you drop a point onto a line? Take a unit vector pointing along the line. Subtract the cloud's mean from the point, then take the dot product with . The answer is the point's position along the line.
Covariance: how two numbers move together
Spinning a line is slow. To find the best line directly, we need one more number about the cloud.
Variance says how much each feature spreads on its own. It can't tell a cloud tilted up from one tilted down. For that, look at whether the two features rise and fall together.
Worked example
Five points
The points are , , , and . Both means are 0, so each point is already its distance from the mean.
That last number is the covariance of and :
Here and are the sample means. Read it back: for each point, multiply how far it is from the mean in by how far it is in , then average. Positive means the two rise together, negative means one falls as the other rises, and near 0 means no straight-line link. The covariance of a feature with itself is its variance.
Why and not ? Dividing by makes the estimate a little bigger. That corrects for measuring spread around the sample's own mean, which sits a little closer to the points than the true mean. By default, scikit-learn and PyTorch divide by . With 150 customers the difference is under 1%.
Put every pair's covariance in a table, with the variances on the diagonal. For the five points:
This is the covariance matrix, written (capital sigma). Row , column holds the covariance of feature with feature . Swapping and gives the same number, so it's a symmetric matrix. With 6 features it's .
Covariance matrix [[2.50, 1.50], [1.50, 2.50]]
v₁: eigenvalue 4.00, direction (0.71, 0.71) · v₂: eigenvalue 1.00
The first direction holds 80.0% of the total variance.
Drag the points, or use the arrow keys on one. Each arrow is √(eigenvalue) long: one standard deviation along its direction. The ellipse is one standard deviation all round.
Things to notice:
- Positive covariance tilts the ellipse up and to the right. "Tilted down" makes it negative, and the ellipse tilts the other way.
- With "No tilt", the covariance is 0 and the ellipse lines up with the axes.
- Drag one point far away. It pulls the covariance and swings the long arrow towards itself. Squared distances make far points count a lot.
The meat-vs-veg cloud has covariance matrix
The covariance is strongly negative: customers who order more meat order less veg.
The best direction is an eigenvector
The arrows in the figure are the covariance matrix's eigenvectors: the directions the matrix only stretches. And the long one is exactly the line with the most spread.
Here's why, on the five points. has the same shape as the matrix in the eigenvectors lesson, so the same steps work.
Worked example
Eigenvalues and eigenvectors of the five points' covariance
Solve : , so . The eigenvalues are and .
That holds in general. The variance of the points dropped onto a unit vector is
If is an eigenvector, , so this is . Along an eigenvector, the variance is its eigenvalue.
Why can't another direction beat the top eigenvector? is symmetric, so its eigenvectors are at right angles. Any unit vector is a mix of them: with . Its variance comes out as a weighted average of the eigenvalues:
An average can't be bigger than its biggest part. So the most spread is , on , and the least is , on . The curve in the spinning figure is this formula, swinging between 667 and 85.
The method is now clear:
- Subtract the mean from every row.
- Compute the covariance matrix.
- Find its eigenvectors, and sort them by eigenvalue, largest first.
- Keep the first . Each one is a new axis, and each row's coordinates on those axes are its new numbers.
This is principal component analysis (PCA). The eigenvectors are the principal components, called PC1, PC2 and so on. A computer finds them with methods like power iteration, which finds the biggest-stretch direction first.
Predict first
A 2-D cloud has covariance matrix [[3, 2], [2, 3]]. What share of the total variance does the first principal component capture?
Keeping fewer numbers
Now drop each customer onto PC1 and keep only their position along it. Each customer is down from 2 numbers to 1. To see what was lost, rebuild each point from its one number: go that far along PC1 from the mean.
The 150 customers, each described by 2 numbers: meat and veg.
Kept: 88.7% of the variance (eigenvalue 667). Lost: 11.3% (eigenvalue 85), the spread at right angles to the line.
● meat lover · ■ veggie · ▲ adventurous. In the last step, faint rings mark where the points started. The strip’s up-and-down jitter is only there so the markers don’t overlap.
Things to notice:
- The rebuilt points all sit on the line. Everything at right angles to it is gone.
- The three types of customer still separate along the strip: veggies at one end, meat lovers at the other.
- The variance that's lost is the spread at right angles to the line: the second eigenvalue, 85.
The total variance is the sum of the variances on the diagonal, . It also equals the sum of the eigenvalues, : turning the axes doesn't change how spread out the cloud is. So PC1 keeps of it.
A component's eigenvalue divided by the sum of all the eigenvalues is its share of the total variance. That share is its explained variance (scikit-learn calls the share the explained variance ratio). It says how much of the spread you keep.
All six toppings
The same method works with all 6 numbers per customer. The covariance matrix is , with 6 eigenvalues. Drawn as bars, largest first, they make a scree plot, named after the loose stones at the foot of a cliff.
Grey bars: the customer’s real profile. Orange bars: rebuilt from 2 numbers.
2 components keep 87.9% of the variance; 12.1% is lost.
The sixth bar is almost 0: every profile adds up to 1, so the data has no spread in one direction.
Things to notice:
- PC1 captures 64.1% and PC2 23.8%. Two numbers keep 87.9% of the spread, so 12.1% is lost.
- After the first two, the bars drop off. That bend is the usual hint for how many to keep.
- With 2 components, each rebuilt profile is close to the real one. With 1, the meat lover and the adventurous eater come back almost the same, because PC1 only knows veg against meat.
- The last bar is almost 0. Every profile adds up to 1, so if you know 5 shares you know the sixth. In that one direction the data has no spread at all.
Now plot every customer by their two numbers.
● meat lover■ veggie▲ adventurous
| group | PC1 | PC2 |
|---|---|---|
| meat | −0.66 | −0.47 |
| veg | 0.71 | −0.18 |
| cheese | 0.11 | −0.44 |
| spicy | −0.19 | 0.63 |
| fruit | 0.07 | 0.07 |
| fish | −0.04 | 0.39 |
PC1 is mostly “veg minus meat”: veggies sit on the right, meat lovers on the left. PC2 is mostly “spicy and fish minus meat and cheese”, which lifts the adventurous eaters.
PCA never saw the customer types. The three groups appear because they are the biggest pattern in the data.
Things to notice:
- The three kinds of customer form three groups. PCA was never told the kinds; they are the biggest pattern in the data. Finding such groups directly is the next lesson, clustering.
- Each component is a recipe: a weighted mix of the original features. PC1 is about veg meat, plus small amounts of the rest.
- An eigenvector's sign is arbitrary. is the same direction as , so another program might flip an axis. The picture is the same, mirrored.
The neural-net course trains an autoencoder to squeeze these same profiles into 2 numbers. With straight-line layers, it loses exactly the same 12.1% as PCA. A bent one loses a little less.
DigressionScale first, or the feature with the biggest units winsMeasure distance in metres, and PCA sees nothing else. · 2 min
The taste profiles are all shares, in the same units, so they can go into PCA as they are. Mixed units are a different story. Variance grows with the square of the units, so a feature measured in big numbers swamps the rest.
Take four delivery features: distance, traffic level, hour and number of items. Measure distance in metres, so its numbers run into the thousands.
deliveries = pd.DataFrame(load("deliveries")["rows"])
D = deliveries[["distance_km", "traffic", "hour", "items"]].to_numpy()
D[:, 0] *= 1000 # distance in metres: its numbers are now about 1,000 times bigger
raw = PCA(n_components=2).fit(D)
print(raw.explained_variance_ratio_.round(4)) # [1. 0.]: one feature takes it all
print(raw.components_[0].round(3)) # [1. 0. -0. 0.]: PC1 is distance, and nothing else
scaled = make_pipeline(StandardScaler(), PCA(n_components=2)).fit(D)
print(scaled.named_steps["pca"].explained_variance_ratio_.round(3)) # [0.285 0.258]
print(scaled.named_steps["pca"].components_.round(2)) # every feature now has a say[1. 0.]
[ 1. 0. -0. 0.]
[0.285 0.258]
[[ 0.49 0.62 -0.24 0.57]
[-0.33 0.12 0.8 0.49]]Unscaled, PC1 is distance and nothing else, and it "explains" all the variance. That's only because metres are small units. After scaling each feature to mean 0 and standard deviation 1, every feature has a say.
The scaled shares are also a lesson: 28.5% and 25.8%. These four features are nearly unrelated, so no direction stands out, and PCA can't compress them much. PCA helps when features move together.
make_pipeline(StandardScaler(), PCA(...)) keeps the two steps together, so new data is scaled with the training data's numbers (more on pipelines later in this course).
DigressionWhere PCA comes fromKarl Pearson in 1901, Harold Hotelling in 1933. · 1 min
The statistician Karl Pearson described the idea in 1901. His paper was called "On lines and planes of closest fit to systems of points in space". He looked for the line or plane that stays closest to a cloud of points. That's the same answer as the line with the most spread, because the spread kept and the spread lost always add up to the total.
Harold Hotelling developed it again in 1933 and gave it the name "principal components".
In scikit-learn and PyTorch
scikit-learn's PCA is an estimator like the others in this course. fit finds the components, transform gives each row's coordinates, and inverse_transform rebuilds rows from them.
X, kind, groups = taste_profiles() # X: (150, 6); every feature is a share of orders, same units
pca = PCA(n_components=2)
Z = pca.fit_transform(X) # (150, 2): each customer's 2 coordinates
print(pca.explained_variance_ratio_.round(3)) # [0.641 0.238]: share of the spread each keeps
print(pca.explained_variance_ratio_.sum().round(3)) # 0.879, so 12.1% is lost
print(pd.DataFrame(pca.components_, columns=groups, index=["PC1", "PC2"]).round(2))
X_back = pca.inverse_transform(Z) # (150, 6): rebuilt from 2 numbers each
print(X[0].round(2), X_back[0].round(2)) # customer 0, before and after[0.641 0.238]
0.879
meat veg cheese spicy fruit fish
PC1 -0.66 0.71 0.11 -0.19 0.07 -0.04
PC2 -0.47 -0.18 -0.44 0.63 0.07 0.39
[0.3 0.05 0.1 0.37 0.06 0.12] [0.29 0.03 0.11 0.33 0.08 0.17]What to notice:
explained_variance_ratio_holds the shares: 64.1% and 23.8%, 87.9% together.components_holds one component per row. Each row is a unit vector over the 6 groups.PCAsubtracts the mean itself. It doesn't scale, which is right here, because every feature is a share.- Customer 1 rebuilt from 2 numbers is close to the original: 0.33 spicy instead of 0.37.
The same thing by hand: the covariance matrix and torch.linalg.eigh, which is made for symmetric matrices.
def pca_by_hand(X: torch.Tensor, k: int) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Top-k principal components from the covariance matrix: (eigenvalues, components, coordinates)."""
centred = X - X.mean(dim=0) # (n, d): move the cloud's centre to 0
cov = centred.T @ centred / (X.shape[0] - 1) # (d, d), the same as torch.cov(X.T)
values, vectors = torch.linalg.eigh(cov) # smallest first; eigenvectors are columns
order = values.argsort(descending=True)[:k]
components = vectors[:, order].T # (k, d): one unit row vector per component
return values[order], components, centred @ components.T # coordinates: (n, k)
Xt = torch.tensor(X, dtype=torch.float64)
values, components, Zt = pca_by_hand(Xt, k=2)
total = torch.cov(Xt.T).trace() # total variance: the sum of the diagonal
print((values / total).numpy().round(3)) # [0.641 0.238], as scikit-learn
# Eigenvectors have no fixed sign: v and −v are the same direction. Compare up to sign.
same = [torch.allclose(c, torch.tensor(s), atol=1e-8) or torch.allclose(-c, torch.tensor(s), atol=1e-8) for c, s in zip(components, pca.components_)]
print(same) # [True, True][0.641 0.238]
[True, True]eighreturns the eigenvalues smallest first, with the eigenvectors as columns. So the code sorts them, largest first, and transposes to get one component per row.centred.T @ centred / (n - 1)is the covariance matrix from the formula above.torch.cov(X.T)gives the same; it wants the features as rows, so the code passesX.T.- The components match scikit-learn's up to sign. Each one could come out as or .
DeeperPCA via the SVDLibraries usually skip the covariance matrix and factor the data directly. · 2 min
There's a second route to the same components. The singular value decomposition (SVD) factors any matrix into a rotation, a stretch and another rotation. This book doesn't teach the SVD itself, but here is the connection.
Apply it to the centred data. The second rotation's directions are the principal components, and each stretch squared, divided by , is an eigenvalue. This route never forms the covariance matrix, which makes it more accurate when features are nearly copies of each other.
scikit-learn's PCA chooses its method with the svd_solver setting. On tall, narrow data like the taste profiles (many more rows than columns) the default uses the covariance matrix, as this lesson does. Otherwise it usually uses the SVD.
# PCA via the SVD: the right singular vectors of the centred data are the components.
centred = Xt - Xt.mean(dim=0)
U, S, Vh = torch.linalg.svd(centred, full_matrices=False) # S: singular values, largest first
print((S**2 / (len(Xt) - 1) / total)[:2].numpy().round(3)) # [0.641 0.238] again
# torch.pca_lowrank does the same on large data, with a fast randomised method.
torch.manual_seed(0) # pca_lowrank draws random numbers
_, S_low, _ = torch.pca_lowrank(Xt, q=2) # centres the data itself (center=True)
print((S_low**2 / (len(Xt) - 1) / total).numpy().round(3)) # about [0.641 0.238][0.641 0.238]
[0.641 0.238]torch.linalg.svd gives the exact answer. torch.pca_lowrank finds only the top few components, with a fast method based on random numbers, so it's the one to use on large data. Like scikit-learn, it subtracts the mean for you.
DigressionBeyond PCA: t-SNE and UMAP make pictures, not featuresCurved maps of high-dimensional data, and why their distances can mislead. · 2 min
PCA can only rotate and flatten. If the data lies on a curved surface, a flat picture squashes it. Two popular methods bend instead: t-SNE (van der Maaten and Hinton, 2008) and UMAP (McInnes, Healy and Melville, 2018).
Both try to keep each point's nearest neighbours close in the picture, and care much less about far-apart points. They often show groups better than PCA, and they're widely used to explore data like images or gene measurements.
They have catches. The size of a group in the picture, and the distance between groups, often mean little. The picture changes with their settings and their random start.
Unlike PCA, t-SNE has no way to place new points. UMAP can place them, but not with a simple linear recipe like PCA's components. So use them to look, and use PCA (or an autoencoder) when you need features for another model.
Putting it together
PCA on the five worked-example points, start to finish:
- Centre: the means are already 0, so the points stay , , , , .
- Covariance matrix: . The total variance is .
- Eigenvectors: with eigenvalue 4, and with eigenvalue 1.
- Explained variance: PC1 keeps , PC2 the other 20%.
- One number per point: the positions along PC1 are , 0, 0, 0, .
- Rebuild: comes back as . It sat entirely in the PC2 direction, which was thrown away. comes back exactly, since it lies on PC1.
The taste profiles follow the same six steps, with a matrix: 2 numbers per customer keep 87.9% of the variance.
Common misconceptions
"PCA picks the most important features." It builds new ones. Each component is a mix of all the original features, like "veg minus meat". To drop features you'd need a different method.
"The direction with the most variance is the most useful for prediction." PCA never sees a label. A small direction can be the one that predicts lateness. PCA keeps spread, not usefulness.
"PCA's numbers don't depend on units." They do. A feature in metres swamps one in kilometres. Scale mixed features first.
"A component's sign means something." and are the same direction. Two programs can give opposite signs for the same data.
"Covariance near 0 means two features are unrelated." It means no straight-line link. Features in a U shape can have covariance 0 and still depend on each other strongly.
Recap
- Unsupervised learning finds structure in data without labels. Dimensionality reduction describes each example with fewer numbers.
- Drop points onto a line with a dot product; the variance of the dropped points measures how much spread the line keeps.
- Covariance says how two features move together. The covariance matrix holds every pair, with variances on the diagonal, and describes the cloud's ellipse.
- Along an eigenvector of the covariance matrix, the variance is its eigenvalue. The top eigenvector is the line with the most spread.
- PCA keeps the top eigenvectors (principal components) as new axes. Each one's explained variance is its eigenvalue over the total.
- On the taste profiles, 2 components keep 87.9% of the variance, and the three kinds of customer appear without being named.
- Names in this lesson: scikit-learn's
PCA(n_components,.explained_variance_ratio_,.components_,.transform,.inverse_transform) andStandardScaler; PyTorch'storch.cov,torch.linalg.eigh,torch.linalg.svdandtorch.pca_lowrank.