Level 3 In-Depth AI · Classical Machine Learning
PCA and Dimensionality Reduction
Principal component analysis finds the directions in which your data varies most, so you can describe each example with a few numbers instead of hundreds while losing as little as possible. Used to compress, denoise, speed up and visualise data.
- Level
- ●●●●● Intermediate
- Reading
- 13 min
- To learn it well
- 1 hour to read, an afternoon to practise
- Builds on
- 7 concepts →
- Quiz
- 5 questions ↓
This leads to
t-SNE and UMAPThe full path from zero — 7 concepts before this one
- What Is AI?
- Vectors
- How Machines Learn
- Matrices and Matrix Multiplication
- Supervised, Unsupervised and Reinforcement Learning
- Eigenvectors and SVD
- Unsupervised Learning
- PCA and Dimensionality Reduction
Read them roughly in this order. See it on the concept map →
Why it matters
Real datasets often have far more columns than they need. A gene-expression study measures 20,000 genes per patient. A small 28×28 image has 784 pixel values. A sensor rig logs 300 readings per second. These features are rarely independent. Neighbouring pixels move together; genes act in pathways; sensors on the same machine respond to the same vibration. So the data, though recorded with many numbers, really varies in far fewer ways.
Dimensionality reduction finds a shorter description. Principal component analysis (PCA) is the oldest, fastest and most widely used method. It is used to:
- Visualise high-dimensional data by projecting it onto the two or three most informative directions.
- Compress data while keeping most of the information.
- Speed up and stabilise other models. Fewer, uncorrelated inputs mean faster training and less Overfitting and the Bias–Variance Tradeoff, and they help distance-based methods like k-Nearest Neighbours and k-Means Clustering escape the curse of dimensionality.
- Denoise data, since small-variance directions are often mostly noise.
- Understand data: the main directions of variation often have a meaning, like "overall size" or "sweet versus dry".
PCA is also linear algebra you will meet again. It is the singular value decomposition of Eigenvectors and SVD applied to data, the same low-rank idea behind matrix factorisation and LoRA.
The intuition
Think of the shadow of an object. Shine a light on a teapot from the side and its shadow shows the spout, body and handle: a good 2D summary of a 3D object. Shine it from directly above and the shadow is a featureless circle. Some directions of projection preserve far more of the shape than others.
PCA finds the best direction to "shine the light" for your data. It looks for the direction along which the points are most spread out, because that is where they differ most from each other and so where most of the information is. That direction is the first principal component (PC1). The second principal component is the direction of most remaining spread, at right angles to the first. And so on, for as many dimensions as the data has.
Then you keep only the first few components. Each point is described by its position along those few directions, and the small leftover wiggles in the other directions are dropped.
Key idea PCA rotates your coordinate axes to line up with the directions of greatest variance in the data, ordered from most to least. Keeping only the first few gives the best possible low-dimensional linear summary, in the sense of losing the least squared error.
How it works
Step 1: centre the data
Subtract the mean of each feature, so the cloud of points is centred on the origin. PCA is about spread around the centre, so this step is essential. If features are in different units (centimetres and kilograms), also divide each by its standard deviation (standardise), or the feature with the biggest numbers will dominate.
Step 2: the covariance matrix
The covariance matrix summarises how the features vary and co-vary. For features it is a table. Entry on the diagonal is the variance of feature ; entry off the diagonal is the covariance of features and : positive if they tend to rise together, negative if one rises as the other falls. For centred data in a matrix with rows:
(Some texts divide by instead of . For PCA it makes no difference to the directions.)
Step 3: eigenvectors are the principal components
The variance of the data along a unit-length direction is . We want the direction that makes this largest. The answer, a classic result of linear algebra, is the eigenvector of with the largest eigenvalue:
The eigenvector is the first principal component, and its eigenvalue ("lambda one") is the variance along it. The eigenvector with the second-largest eigenvalue is PC2, and so on. Because is symmetric, its eigenvectors are all at right angles to each other.
The explained variance of component is its share of the total:
Step 4: project
To reduce to dimensions, stack the first eigenvectors as the columns of a matrix (size ) and multiply:
Each row of holds the new coordinates, or scores, of one example. To go back, multiply by the transpose and add the mean back: . The difference between and is the reconstruction error. PCA's components are exactly the ones that make this error (summed squared) as small as possible for any given , so "maximise variance kept" and "minimise reconstruction error" are the same goal.
A worked example by hand
Five students' scores in maths and physics:
| Student | Maths | Physics | Centred maths | Centred physics |
|---|---|---|---|---|
| 1 | 67 | 68 | −3 | −2 |
| 2 | 68 | 67 | −2 | −3 |
| 3 | 70 | 70 | 0 | 0 |
| 4 | 72 | 73 | 2 | 3 |
| 5 | 73 | 72 | 3 | 2 |
Both means are 70. To keep the arithmetic short we divide by .
Covariance matrix. Variance of maths: . Physics is the same, 5.2. Covariance: . So:
Eigenvectors. Try : . So it is an eigenvector with . Try : , so .
- PC1 : "overall ability", both scores up together. Explained variance .
- PC2 : "better at maths than physics". Only .
Scores. Student 1's PC1 score is the dot product of their centred scores with PC1: . The five PC1 scores are . Their variance, , is , as promised.
Reconstruction from PC1 alone. Student 1: , plus the mean, gives . The real scores were : off by half a point each. One number per student instead of two, and almost nothing lost.
Doing it with the SVD
In practice nobody forms the covariance matrix. The singular value decomposition of the centred data matrix gives the same answer more accurately and quickly:
The columns of (rows of ) are the principal components, and the singular values on the diagonal of give the variances: . The scores are . This is what scikit-learn does. For huge datasets it uses a randomised SVD that computes only the top components.
How many components?
- Cumulative explained variance. Keep enough components to explain, say, 90% or 95% of the variance.
- The scree plot. Plot each component's explained variance and look for the point where the curve flattens into "scree" (the rubble at the bottom of a cliff).
- Downstream performance. If PCA feeds a classifier, choose by Cross-Validation on the classifier's score.
- Two or three, if the goal is a picture.
Whitening
The scores along different components have very different spreads (10 and 0.4 in the example). Whitening divides each component's scores by its standard deviation, , so every component has variance 1. The result is uncorrelated features on the same scale, which some algorithms prefer. In scikit-learn, pass whiten=True. Be careful: whitening also blows up the low-variance components, which are often mostly noise.
In code
PCA from scratch via the SVD, on the wine dataset (13 chemical measurements for 178 wines), checked against scikit-learn:
import numpy as np
from sklearn.datasets import load_wine
from sklearn.decomposition import PCA
X, y = load_wine(return_X_y=True) # 178 wines x 13 measurements
X = (X - X.mean(axis=0)) / X.std(axis=0) # centre and standardise each feature
# PCA from scratch via the singular value decomposition
U, S, Vt = np.linalg.svd(X, full_matrices=False) # X = U @ diag(S) @ Vt
components = Vt # rows = principal directions
variance = S ** 2 / (len(X) - 1) # variance along each direction
ratio = variance / variance.sum()
Z = X @ Vt[:2].T # project onto the first 2 components
print("explained variance ratio:", ratio[:4].round(3))
print("first component:", components[0].round(2))
print("projected shape:", Z.shape)
pca = PCA(n_components=2).fit(X)
print("scikit-learn ratio: ", pca.explained_variance_ratio_.round(3))
print("same direction (up to sign):", np.allclose(np.abs(pca.components_[0]), np.abs(Vt[0])))
# explained variance ratio: [0.362 0.192 0.111 0.071]
# first component: [-0.14 0.25 0. 0.24 -0.14 -0.39 -0.42 0.3 -0.31 0.09 -0.3 -0.38
# -0.29]
# projected shape: (178, 2)
# scikit-learn ratio: [0.362 0.192]
# same direction (up to sign): True
The first two components explain 55% of the variance of 13 measurements. Plot Z coloured by y and the three grape varieties separate cleanly, though PCA never saw the labels. Note the sign: an eigenvector and its negative are equally valid, so libraries may flip signs. That is expected, not a bug.
Choosing the number of components, and measuring what compression costs, on the digits:
import numpy as np
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
X, _ = load_digits(return_X_y=True) # 1,797 images x 64 pixels
pca = PCA(n_components=0.95).fit(X) # keep enough components for 95% of the variance
print("components for 95% variance:", pca.n_components_)
for k in (2, 10, 20, 40):
p = PCA(n_components=k).fit(X)
X_back = p.inverse_transform(p.transform(X)) # compress to k numbers, then decompress
err = np.mean((X - X_back) ** 2)
print(f"k={k:2d} variance kept {p.explained_variance_ratio_.sum():.1%} reconstruction MSE {err:.2f}")
# components for 95% variance: 29
# k= 2 variance kept 28.5% reconstruction MSE 13.42
# k=10 variance kept 73.8% reconstruction MSE 4.91
# k=20 variance kept 89.4% reconstruction MSE 1.98
# k=40 variance kept 98.8% reconstruction MSE 0.22
Passing a fraction between 0 and 1 as n_components tells scikit-learn to keep just enough components for that share of the variance. Inside a modelling pipeline, write make_pipeline(StandardScaler(), PCA(n_components=0.95), LogisticRegression()) so that PCA is fitted only on training data.
Common pitfalls
- Forgetting to standardise. If one feature is income in dollars and another is age in years, PCA's first component will simply be "income", because it has the largest variance in raw units. Standardise unless all features share meaningful units (like pixels).
- Fitting PCA on all data before splitting. That leaks test-set information into training. Put PCA inside a pipeline.
- Assuming high variance means important. PCA keeps the directions of most spread, not the directions most useful for predicting your label. A tiny-variance direction can be the one that separates the classes. If you have labels, check downstream performance, or consider a supervised method such as linear discriminant analysis.
- Expecting it to unfold curved structure. PCA is linear: it can only rotate and drop axes. Data lying on a curved surface (a "Swiss roll") needs nonlinear methods. See t-SNE and UMAP, kernel PCA, or Autoencoders.
- Over-interpreting components. Component directions are mixtures of all features and can flip sign between runs. Naming them ("PC1 is quality") is tempting but often shaky, especially beyond the first two.
- Outliers. A few extreme points can grab a whole component. Look at the data first.
Watch out PCA keeps the directions where the data varies most, which are not necessarily the directions that matter for your task. Dropping the "small" components can throw away exactly the signal a classifier needed. When PCA feeds a model, choose the number of components by the model's validation score, not by explained variance alone.
Where it leads
- t-SNE and UMAP draw high-dimensional data as 2D maps that preserve neighbourhoods rather than variance, and handle curved structure. Running PCA to about 50 dimensions first is a standard speed-up. See t-SNE and UMAP.
- Autoencoders are nonlinear PCA: a neural network that compresses to a small code and reconstructs. A linear autoencoder with squared error learns the same subspace as PCA. See Autoencoders.
- Matrix factorisation for recommendations uses the same low-rank idea on a ratings matrix. See Recommender Systems.
- Truncated SVD / latent semantic analysis applies the SVD directly to sparse word-count matrices, an early way to get word and document vectors (see Word Embeddings).
- Low-rank adaptation fine-tunes huge models by learning low-rank weight updates. See LoRA and Parameter-Efficient Fine-Tuning.
- Anomaly detection: points with a large reconstruction error don't fit the main pattern. See Anomaly Detection.
A bit of history
Karl Pearson introduced the idea in 1901, in a paper titled On lines and planes of closest fit to systems of points in space: he wanted the line minimising the squared perpendicular distances to a cloud of points, exactly the PCA objective. Harold Hotelling independently developed it in 1933 as a tool for psychology, and gave it the name "principal components". The mathematics is closely related to the Karhunen–Loève transform used in signal processing.
PCA needed computers to become practical on real data. In 1991 Matthew Turk and Alex Pentland used it for face recognition with "eigenfaces", principal components of face images, one of the first successful automatic face recognisers. Today PCA is a standard first step in fields from genetics, where the top components of genome data famously reproduce a rough map of Europe, to finance and climate science.
Try it
- In the hand example, compute PC1 scores and reconstructions for students 4 and 5. What is the total squared reconstruction error over all five students? Check that it equals .
- Run the wine code without standardising (remove the scaling line). What does the first component become, and why? Look at
X.std(axis=0)for a hint.- Harder: scatter-plot the first two wine components coloured by
y. Then train a logistic regression on 2, 5 and 13 components and compare cross-validated accuracy.Hint for 1: each student's error is their PC2 score squared, and the PC2 scores are or 0.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Principal Component Analysis, Explained Visually
Interactive point clouds that show what PCA's directions of greatest spread are.
StatQuest
Short, cheerful, very clear videos on statistics and nearly every ML algorithm.
A Tutorial on Principal Component Analysis
A careful, readable derivation of PCA and its link to the SVD, aimed at newcomers.
An Introduction to Statistical Learning (with Python)
The friendliest rigorous introduction to classical ML, with Python labs. Free PDF.
scikit-learn: Decomposing Signals (PCA and friends)
PCA, incremental and randomised PCA, kernel PCA, NMF and truncated SVD.
Mathematics for Machine Learning
The linear algebra, calculus, probability and optimisation that ML uses, in one free book.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/ml/pca.md