MLDay 19 of 50Supervised and Unsupervised Learning
Compress Features with PCA
A scanned digit arrives as 64 pixel values, but neighbouring pixels mostly rise and fall together. Much of that is the same information stored twice. PCA swaps the 64 columns for a few new ones that keep most of what varies, so models run on less and you can plot the data in 2D.
The idea
The variance of a column is the average squared distance of its values from their mean: how spread out they are. (This is the data's spread, not the "high variance" of an overfit model from D10.) Spread is what tells rows apart. A column where every row has the same value carries no information.
Principal component analysis (PCA) finds new axes for the data:
- Subtract each column's mean, so the cloud of points is centred on 0.
- The first principal component (PC1) is the direction along which the points spread out the most.
- PC2 is the direction at right angles to PC1 that holds the most of the spread that's left, and so on. There are as many components as columns.
Projecting a point onto a component means dropping it straight onto that axis and reading off its position. Keep the first few components, drop the rest, and each row becomes a few numbers instead of many. The explained variance ratio of a component is the share of the total spread it holds.
Like k-means in D17, PCA never looks at the labels.
A tiny example
Four students' marks out of 10:
| Student | Maths | Physics | Centred (minus 5, 5) |
|---|---|---|---|
| A | 6 | 8 | (1, 3) |
| B | 8 | 6 | (3, 1) |
| C | 4 | 2 | (−1, −3) |
| D | 2 | 4 | (−3, −1) |
Both averages are 5. Maths has variance , and physics also has 5, so the total is 10. Each column alone holds half of it.
Now use the diagonal "both marks go up together" as the axis. A centred point sits at along it. For A that's , and the four positions are 2.83, 2.83, −2.83 and −2.83. Each squares to 8, so the variance along the diagonal is 8.
Across the diagonal, the positions are , which square to 2. That leaves 2. And 8 + 2 = 10: turning the axes moves the spread around without changing the total.
So the diagonal is PC1, and one number per student keeps 80% of the spread. It loses only what tells A from B, and C from D.
The formula
| Symbol | Meaning |
|---|---|
| the variance along component ("lambda") | |
| the sum over all components: the total variance | |
| which component: 1 for PC1, 2 for PC2 |
Worked: variances 8 and 2 give PC1 a ratio of , so it keeps 80%.
Try it
Find the direction with the most spread
Turn the axis. Each point drops onto it (the orange dots). Keep the direction where those dots spread out the most: it holds the most information about the points.
variance along the axis 19.517of total 328.781kept 5.9%
The axis starts across the cloud and captures about 6% of the variance. Turn it: lying flat (0°, maths alone) it captures 69%, and near 32° it peaks at about 94%. Press Snap to PC1 to check. The last 6% is the scatter across the line.
In code
scikit-learn's PCA centres the data and finds the components. On the four students:
# script_id: day_019_pca/tiny
import numpy as np
from sklearn.decomposition import PCA
marks = np.array([[6, 8], [8, 6], [4, 2], [2, 4]]) # maths, physics
pca = PCA().fit(marks)
print("PC1 direction:", pca.components_[0].round(3))
print("explained variance ratio:", pca.explained_variance_ratio_.round(3))
print("each student on PC1:", pca.transform(marks)[:, 0].round(2))
PC1 direction: [0.707 0.707]
explained variance ratio: [0.8 0.2]
each student on PC1: [ 2.83 2.83 -2.83 -2.83]
The direction is the diagonal, at unit length, and the numbers match the hand calculation.
Now the digits dataset that ships with scikit-learn: 1,797 handwritten digits, each an 8×8 image of
brightness values from 0 to 16. With the default n_components=None, PCA keeps all 64 components.
# script_id: day_019_pca/digits
import os
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
X, y = load_digits(return_X_y=True) # 64 pixel columns; y is the digit 0-9
ratio = PCA().fit(X).explained_variance_ratio_
print("PC1, PC2 keep:", ratio[:2].round(3))
print("first 2 keep:", ratio[:2].sum().round(3), "| first 10 keep:", ratio[:10].sum().round(3))
print("components for 90%:", np.argmax(ratio.cumsum() >= 0.90) + 1)
FIG_DIR = Path(os.environ.get("ML_FIG_DIR", "figures"))
FIG_DIR.mkdir(exist_ok=True)
Z = PCA(n_components=2).fit_transform(X) # each image becomes 2 numbers
fig, ax = plt.subplots(figsize=(6, 4))
ax.scatter(Z[:, 0], Z[:, 1], c=y, cmap="tab10", s=6)
for d in range(10): # write each digit at the middle of its points
ax.text(*np.median(Z[y == d], axis=0), str(d), fontsize=13, weight="bold")
ax.set(title="Two components pull 0s, 3s and 4s apart; 5s and 8s overlap", xlabel="PC1", ylabel="PC2")
fig.tight_layout()
fig.savefig(FIG_DIR / "digits_2d_map.png", dpi=120)
plt.close(fig)
PC1, PC2 keep: [0.149 0.136]
first 2 keep: 0.285 | first 10 keep: 0.738
components for 90%: 21

Two numbers per image keep only 28.5% of the variance, yet several digits already form their own patches.
Does a model need all 64 columns? This trains k-nearest neighbours
(D15) on 2, 10 and 64 components. A Pipeline
(D11) fits PCA on the training rows only, so the test rows
can't leak into the components (D06).
# script_id: day_019_pca/digits
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
for k in [2, 10, 64]:
model = make_pipeline(PCA(n_components=k), KNeighborsClassifier())
model.fit(X_train, y_train)
print(f"{k:2d} components: test accuracy {model.score(X_test, y_test):.3f}")
2 components: test accuracy 0.620
10 components: test accuracy 0.967
64 components: test accuracy 0.984
Ten components keep 73.8% of the variance and give up 1.7 points of accuracy. In return, every distance the model computes uses 10 numbers instead of 64. Keeping all 64 only turns the axes, so distances don't change and the score is the same as on the raw pixels.
Quick check
Quick check
1. Two components have variances 9 and 3. What share does PC1 keep?
2. Why does kNN score the same on all 64 components as on the raw pixels?
3. A table has income in dollars and age in years. You run PCA without scaling. What will PC1 be?
Next
Pixels are numbers already; Day 20 turns text into numbers with bag-of-words and TF-IDF.
Data: the Optical Recognition of Handwritten Digits dataset, bundled with scikit-learn as
load_digits.