PCA & Dimensionality Reduction
Many data sets have dozens or hundreds of features. More features mean slower training, harder visualisation and a greater risk of overfitting — and often many features are redundant (height in cm and height in inches carry the same information). Dimensionality reduction compresses the data into fewer features while keeping as much information as possible. The classic method is Principal Component Analysis (PCA).
The idea
PCA finds new axes, called principal components, that are combinations of the original features:
- the 1st component points in the direction where the data varies the most,
- the 2nd is perpendicular to the 1st and captures the most of the remaining variation,
- and so on.
Keeping only the first few components gives a compact summary of the data.
Two correlated features → one component
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
rng = np.random.default_rng(0)
height = rng.normal(170, 10, 200)
arm_span = height + rng.normal(0, 3, 200) # strongly tied to height
X = np.column_stack([height, arm_span])
pca = PCA(n_components=2).fit(X)
print("components (directions):")
print(pca.components_.round(3))
print("explained variance ratio:", pca.explained_variance_ratio_.round(4))
plt.scatter(X[:, 0], X[:, 1], s=10, alpha=0.6)
for length, vector in zip(pca.explained_variance_, pca.components_):
end = pca.mean_ + vector * 2 * np.sqrt(length)
plt.annotate("", end, pca.mean_, arrowprops=dict(arrowstyle="->", color="red", lw=2))
plt.axis("equal")
plt.xlabel("height (cm)")
plt.ylabel("arm span (cm)")
plt.show()components (directions):
[[ 0.696 0.718]
[ 0.718 -0.696]]
explained variance ratio: [0.9754 0.0246]
The first component points along the diagonal (roughly equal weights on both features — "overall body size") and explains almost all the variance. The second component (the arm span relative to height) carries very little. Dropping it loses almost nothing.
Visualising high-dimensional data
The digits data set holds 1 797 handwritten digits as 8×8 images — 64 features each. We can't plot 64 dimensions, but we can plot the first two principal components:
import matplotlib.pyplot as plt
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
X, y = load_digits(return_X_y=True)
X2 = PCA(n_components=2, random_state=0).fit_transform(X)
print("original shape:", X.shape, " reduced:", X2.shape)
plt.figure(figsize=(7, 6))
points = plt.scatter(X2[:, 0], X2[:, 1], c=y, cmap="tab10", s=8)
plt.colorbar(points, label="digit")
plt.xlabel("PC 1")
plt.ylabel("PC 2")
plt.show()
print("Digits projected onto 2 principal components")original shape: (1797, 64) reduced: (1797, 2)
Digits projected onto 2 principal components
Even in two dimensions, many digits form recognisable groups (the 0s gather at the bottom, the 4s and 6s on the right), though others overlap heavily in the middle.
How many components?
explained_variance_ratio_ tells you how much of the total variance each component keeps. Its cumulative sum shows how many you need for, say, 90 %:
import numpy as np
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
X, _ = load_digits(return_X_y=True)
pca = PCA().fit(X)
cumulative = np.cumsum(pca.explained_variance_ratio_)
for n in [2, 5, 10, 20, 30, 40]:
print(f"{n:2} components keep {cumulative[n - 1] * 100:5.1f} % of the variance")
pca90 = PCA(n_components=0.90).fit(X)
print("components needed for 90 %:", pca90.n_components_) 2 components keep 28.5 % of the variance
5 components keep 54.5 % of the variance
10 components keep 73.8 % of the variance
20 components keep 89.4 % of the variance
30 components keep 95.9 % of the variance
40 components keep 98.8 % of the variance
components needed for 90 %: 21
Passing a fraction like n_components=0.90 lets PCA pick the number for you.
PCA before a model
Using PCA as a preprocessing step can shrink the input dramatically with little loss in accuracy. Since PCA is variance-based, standardize first when features have different units (pixels here all share the same 0–16 scale, so we skip it):
from sklearn.datasets import load_digits
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
X, y = load_digits(return_X_y=True)
for n in [5, 10, 20, 40]:
model = make_pipeline(PCA(n_components=n, random_state=0), LogisticRegression(max_iter=3000))
score = cross_val_score(model, X, y, cv=3).mean()
print(f"{n:2} components -> CV accuracy {score:.3f}") 5 components -> CV accuracy 0.811
10 components -> CV accuracy 0.886
20 components -> CV accuracy 0.905
40 components -> CV accuracy 0.929
With 20 components (less than a third of the 64 pixels) accuracy is already above 90 %; more components still help a little, so the right number is a trade-off between size and accuracy.
Reconstructing from fewer components
inverse_transform maps compressed data back to the original space. The result is an approximation — a form of lossy compression:
import numpy as np
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
X, y = load_digits(return_X_y=True)
for n in [5, 15, 40]:
pca = PCA(n_components=n, random_state=0).fit(X)
restored = pca.inverse_transform(pca.transform(X))
error = np.mean((X - restored) ** 2)
print(f"{n:2} components: mean squared reconstruction error = {error:.2f}") 5 components: mean squared reconstruction error = 8.54
15 components: mean squared reconstruction error = 3.09
40 components: mean squared reconstruction error = 0.22
Note: Principal components are mixtures of all original features, so they're hard to interpret. If you need to know which original features matter, use feature selection instead (a later lesson). For visualising clusters, non-linear methods like t-SNE (
sklearn.manifold.TSNE) often separate groups better than PCA.
Go further: PCA in Practice: Scaling, Components and Pipelines covers the three decisions every PCA needs: whether to scale, how many components and how to use them in a pipeline.
Test yourself
What does the first principal component capture?
- The feature with the largest values
- The direction of greatest variance in the data
- The class labels
- The mean of each feature
What does PCA(n_components=0.95) do?
- Keeps 95 components
- Keeps as many components as needed to explain 95 % of the variance
- Removes 5 % of the rows
- Scales the data to 0..0.95
Why should you usually standardize features before PCA?
- PCA only accepts values between 0 and 1
- Otherwise features with large units dominate the variance
- It makes PCA supervised
- It is never needed