◆ AI All-in-One

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
↗ Plan a path here

Read first

Eigenvectors and SVDUnsupervised Learning

This leads to

t-SNE and UMAP
The full path from zero — 7 concepts before this one
  1. What Is AI?
  2. Vectors
  3. How Machines Learn
  4. Matrices and Matrix Multiplication
  5. Supervised, Unsupervised and Reinforcement Learning
  6. Eigenvectors and SVD
  7. Unsupervised Learning
  8. 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.

PC1 PC2 arrow length = 2 standard deviations along that direction PC1: the direction of most spread keeps 92% of the variance PC2: at right angles to PC1 the remaining 8% position along PC1 Keep only PC1 each point becomes one number instead of two, losing only 8%
Fig. 1 A cloud of 2D points with its two principal components. PC1 (orange) points along the direction of greatest spread and captures 92% of the variance. PC2 (green), at right angles, captures the rest. Keeping only each point's position along PC1 replaces two numbers with one while losing only 8% of the variance.

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 C\mathbf{C} summarises how the features vary and co-vary. For dd features it is a d×dd \times d table. Entry CjjC_{jj} on the diagonal is the variance of feature jj; entry CjkC_{jk} off the diagonal is the covariance of features jj and kk: positive if they tend to rise together, negative if one rises as the other falls. For centred data in a matrix X\mathbf{X} with NN rows:

C=1N−1X⊤X\mathbf{C} = \frac{1}{N - 1} \mathbf{X}^\top \mathbf{X}

(Some texts divide by NN instead of N−1N - 1. 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 v\mathbf{v} is v⊤C v\mathbf{v}^\top \mathbf{C}\, \mathbf{v}. We want the direction that makes this largest. The answer, a classic result of linear algebra, is the eigenvector of C\mathbf{C} with the largest eigenvalue:

C v1=λ1v1\mathbf{C}\,\mathbf{v}_1 = \lambda_1 \mathbf{v}_1

The eigenvector v1\mathbf{v}_1 is the first principal component, and its eigenvalue λ1\lambda_1 ("lambda one") is the variance along it. The eigenvector with the second-largest eigenvalue is PC2, and so on. Because C\mathbf{C} is symmetric, its eigenvectors are all at right angles to each other.

The explained variance of component jj is its share of the total:

explained variance ratioj=λjλ1+λ2+⋯+λd\text{explained variance ratio}_j = \frac{\lambda_j}{\lambda_1 + \lambda_2 + \dots + \lambda_d}

Step 4: project

To reduce to kk dimensions, stack the first kk eigenvectors as the columns of a matrix Vk\mathbf{V}_k (size d×kd \times k) and multiply:

Z=X Vk\mathbf{Z} = \mathbf{X}\,\mathbf{V}_k

Each row of Z\mathbf{Z} holds the kk new coordinates, or scores, of one example. To go back, multiply by the transpose and add the mean back: X^=Z Vk⊤+mean\hat{\mathbf{X}} = \mathbf{Z}\,\mathbf{V}_k^\top + \text{mean}. The difference between X\mathbf{X} and X^\hat{\mathbf{X}} is the reconstruction error. PCA's components are exactly the ones that make this error (summed squared) as small as possible for any given kk, 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 N=5N = 5.

Covariance matrix. Variance of maths: (9+4+0+4+9)/5=5.2(9 + 4 + 0 + 4 + 9)/5 = 5.2. Physics is the same, 5.2. Covariance: (6+6+0+6+6)/5=4.8(6 + 6 + 0 + 6 + 6)/5 = 4.8. So:

C=(5.24.84.85.2)\mathbf{C} = \begin{pmatrix} 5.2 & 4.8 \\ 4.8 & 5.2 \end{pmatrix}

Eigenvectors. Try v=(1,1)/2\mathbf{v} = (1, 1)/\sqrt{2}: C(1,1)=(5.2+4.8,  4.8+5.2)=(10,10)=10×(1,1)\mathbf{C}(1, 1) = (5.2 + 4.8, \; 4.8 + 5.2) = (10, 10) = 10 \times (1, 1). So it is an eigenvector with λ1=10\lambda_1 = 10. Try (1,−1)/2(1, -1)/\sqrt{2}: C(1,−1)=(0.4,−0.4)=0.4×(1,−1)\mathbf{C}(1, -1) = (0.4, -0.4) = 0.4 \times (1, -1), so λ2=0.4\lambda_2 = 0.4.

  • PC1 =(0.707,0.707)= (0.707, 0.707): "overall ability", both scores up together. Explained variance 10/10.4=96.2%10 / 10.4 = 96.2\%.
  • PC2 =(0.707,−0.707)= (0.707, -0.707): "better at maths than physics". Only 3.8%3.8\%.

Scores. Student 1's PC1 score is the dot product of their centred scores with PC1: (−3)(0.707)+(−2)(0.707)=−3.54(-3)(0.707) + (-2)(0.707) = -3.54. The five PC1 scores are −3.54,−3.54,0,3.54,3.54-3.54, -3.54, 0, 3.54, 3.54. Their variance, 4×12.5/5=104 \times 12.5 / 5 = 10, is λ1\lambda_1, as promised.

Reconstruction from PC1 alone. Student 1: −3.54×(0.707,0.707)=(−2.5,−2.5)-3.54 \times (0.707, 0.707) = (-2.5, -2.5), plus the mean, gives (67.5,67.5)(67.5, 67.5). The real scores were (67,68)(67, 68): 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:

X=U Σ V⊤\mathbf{X} = \mathbf{U}\,\boldsymbol{\Sigma}\,\mathbf{V}^\top

The columns of V\mathbf{V} (rows of V⊤\mathbf{V}^\top) are the principal components, and the singular values σj\sigma_j on the diagonal of Σ\boldsymbol{\Sigma} give the variances: λj=σj2/(N−1)\lambda_j = \sigma_j^2 / (N - 1). The scores are UΣ\mathbf{U}\boldsymbol{\Sigma}. This is what scikit-learn does. For huge datasets it uses a randomised SVD that computes only the top kk 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 kk by Cross-Validation on the classifier's score.
  • Two or three, if the goal is a picture.
29 components reach 95% 0% 50% 95% 100% 1 10 20 30 40 50 64 principal component number (digits data, 64 pixels) bars: share of variance per component the first few carry the most line: cumulative share
Fig. 2 Explained variance for the 64-pixel handwritten digits. Each bar is one component's share; the line is the running total. The first component explains about 15%, the first ten about 74%, and 29 components reach 95%.
1 component 15% of variance 2 components 29% of variance 5 components 54% of variance 10 components 74% of variance 20 components 89% of variance all 64 (original) 100% of variance one handwritten 0, compressed to k numbers by PCA and rebuilt
Fig. 3 One handwritten zero compressed to k numbers and rebuilt. With 1 or 2 components it is a blur; with 10 the shape is clear; with 20 it is close to the original 64 pixels.

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, λj\sqrt{\lambda_j}, 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

  1. 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 N×λ2=5×0.4N \times \lambda_2 = 5 \times 0.4.
  2. 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.
  3. 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 ±0.71\pm 0.71 or 0.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. You run PCA on raw customer data where income is in dollars and age is in years. PC1 turns out to be almost exactly "income". Why?

  2. Maths and physics scores give a covariance matrix with eigenvalues 10 and 0.4. What share of the variance does PC1 explain?

  3. You keep only the high-variance components before a classifier, and accuracy drops sharply. What is the likely reason?

  4. Your data lies on a curved "Swiss roll" surface. What can PCA do with it?

  5. Keeping more components lowers the reconstruction error. How are "variance kept" and "reconstruction error" related in PCA?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Video

StatQuest

Josh Starmer · Beginner · Free

Short, cheerful, very clear videos on statistics and nearly every ML algorithm.

Book

Mathematics for Machine Learning

Deisenroth, Faisal & Ong · 2020 · Intermediate · Free

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