Simple Algorithm
Machine Learning · Descent · 22 min

Dimensionality Reduction

Compressing many features into the few that matter.

A face photo has thousands of pixel values and a gene panel thousands of readings, yet most of those numbers move together. This lesson derives principal component analysis twice, as the directions of greatest variance and as the best linear compression, computes it with the singular value decomposition, and maps out where it fails and what nonlinear methods such as t-SNE, UMAP and autoencoders offer instead.

What you’ll learn

  • Derive the principal components as eigenvectors of the sample covariance, both by maximizing projected variance and by minimizing reconstruction error, and prove that the two problems are the same.
  • Compute PCA from the singular value decomposition of the centered data, read explained-variance shares, and choose the number of components.
  • Decide when to standardize, and explain how units, outliers and the absence of labels can mislead PCA.
  • Describe what t-SNE, UMAP and autoencoders optimize, how to read their output, and when a nonlinear method is the right tool.

Why fewer dimensions?

A dataset with dd features is a cloud of nn points in Rd\R^d, and real clouds rarely fill that space: neighboring pixels move together, thousands of genes rise and fall in a few coordinated programs. Dimensionality reduction replaces each x∈Rd\mathbf x\in\R^d by a shorter z∈Rk\mathbf z\in\R^k, k≪dk\ll d, that keeps what matters. It buys visualization (k=2k=2 or 33), compression (kk numbers instead of dd), denoising (if the signal lives in a few directions and the noise in all dd, dropping the weak directions drops mostly noise) and speed: later models get fewer inputs, and distance-based methods suffer less from the curse of dimensionality.

Feature selection keeps some of the original features (see Feature Engineering & Messy Data). This lesson is about feature extraction: new features built from all of them.

Think first Grayscale photos of one face, 64 × 64 pixels, are rendered while the head turns left–right and up–down and a single lamp moves along an arc. Each photo is a point in R4096\R^{4096}. How many numbers really describe it, and would a flat subspace of that dimension hold the photos well?

Three: two head angles and one lamp position. The photos lie on a 3-dimensional surface in R4096\R^{4096}, their intrinsic dimension. But the surface is curved, since turning the head changes pixel brightness nonlinearly, so no flat 3-dimensional subspace passes close to all of them and a linear method needs many more components. Closing that gap is the job of the nonlinear methods at the end of this lesson.

The direction of greatest variance

Center the data, x~i=xi−xˉ\tilde{\mathbf x}_i=\mathbf x_i-\bar{\mathbf x} with xˉ=1n∑ixi\bar{\mathbf x}=\frac1n\sum_i\mathbf x_i, stack the x~i⊤\tilde{\mathbf x}_i^\top as the rows of the centered data matrix X~∈Rn×d\tilde X\in\R^{n\times d}, and form the sample covariance matrix

S=1nX~⊤X~=1n∑i=1nx~ix~i⊤,S=\frac1n\tilde X^\top\tilde X=\frac1n\sum_{i=1}^n\tilde{\mathbf x}_i\tilde{\mathbf x}_i^\top,

which is symmetric and positive semidefinite. (Dividing by n−1n-1 instead rescales every eigenvalue by the same factor and changes no direction.) Projecting the points onto a unit vector u\mathbf u gives the numbers u⊤x~i\mathbf u^\top\tilde{\mathbf x}_i, whose mean is 0 and whose variance is 1n∑i(u⊤x~i)2=u⊤Su\frac1n\sum_i(\mathbf u^\top\tilde{\mathbf x}_i)^2=\mathbf u^\top S\mathbf u.

DerivationThe principal components are eigenvectors
  1. max⁡u∈Rd u⊤Susubject tou⊤u=1\max_{\mathbf u\in\R^d}\ \mathbf u^\top S\mathbf u\qquad\text{subject to}\qquad\mathbf u^\top\mathbf u=1

    Look for the unit direction with the largest projected variance, equivalently the maximizer of the Rayleigh quotient u⊤Su/u⊤u\mathbf u^\top S\mathbf u/\mathbf u^\top\mathbf u. The constraint matters: without it, stretching u\mathbf u would make the variance as large as you like.

  2. ∇u[u⊤Su−λ(u⊤u−1)]=2Su−2λu=0⟹Su=λu\nabla_{\mathbf u}\big[\mathbf u^\top S\mathbf u-\lambda(\mathbf u^\top\mathbf u-1)\big]=2S\mathbf u-2\lambda\mathbf u=\mathbf 0\quad\Longrightarrow\quad S\mathbf u=\lambda\mathbf u

    Add a Lagrange multiplier λ\lambda and set the gradient to zero, using ∇u(u⊤Su)=2Su\nabla_{\mathbf u}(\mathbf u^\top S\mathbf u)=2S\mathbf u for symmetric SS:

  3. u⊤Su=λ u⊤u=λ⟹max⁡=λ1  at  u=v1\mathbf u^\top S\mathbf u=\lambda\,\mathbf u^\top\mathbf u=\lambda\qquad\Longrightarrow\qquad\max=\lambda_1\ \text{ at }\ \mathbf u=\mathbf v_1

    Every stationary point is an eigenvector of SS, and the variance there equals its eigenvalue. The maximum is therefore the largest eigenvalue λ1\lambda_1, attained at its eigenvector v1\mathbf v_1, the first principal direction.

  4. v1⊤(2Su−2λu−μv1)=2λ1v1⊤u⏟0−2λv1⊤u⏟0−μ=0⟹μ=0\mathbf v_1^\top\big(2S\mathbf u-2\lambda\mathbf u-\mu\mathbf v_1\big)=2\lambda_1\underbrace{\mathbf v_1^\top\mathbf u}_{0}-2\lambda\underbrace{\mathbf v_1^\top\mathbf u}_{0}-\mu=0\quad\Longrightarrow\quad\mu=0

    For the second direction add the constraint v1⊤u=0\mathbf v_1^\top\mathbf u=0 with a multiplier μ\mu. Multiplying the new stationarity condition by v1⊤\mathbf v_1^\top, and using v1⊤Su=λ1v1⊤u=0\mathbf v_1^\top S\mathbf u=\lambda_1\mathbf v_1^\top\mathbf u=0, gives μ=0\mu=0. So again Su=λuS\mathbf u=\lambda\mathbf u, now orthogonal to v1\mathbf v_1: the answer is v2\mathbf v_2, with variance λ2\lambda_2, and induction gives the rest.

Check your understanding

You skip centering and take the top eigenvector of 1nX⊤X\frac1nX^\top X for data whose mean is (10, 10)(10,\,10) and whose spread is about 1 in every direction. What does that eigenvector find?

  1. The direction of greatest spread, as with centered data
  2. The direction of least spread
  3. Approximately the direction of the mean, (1,1)/2(1,1)/\sqrt2, whatever the shape of the cloud
  4. Nothing: without centering the matrix is singular
Show the answer

C. Approximately the direction of the mean, (1,1)/2(1,1)/\sqrt2, whatever the shape of the cloud

The uncentered matrix is 1nX⊤X=S+xˉxˉ⊤\frac1nX^\top X=S+\bar{\mathbf x}\bar{\mathbf x}^\top, and xˉxˉ⊤\bar{\mathbf x}\bar{\mathbf x}^\top has eigenvalue ∥xˉ∥2=200\norm{\bar{\mathbf x}}^2=200 along xˉ\bar{\mathbf x}, swamping the eigenvalues of SS (about 1). The top eigenvector reports where the cloud sits, not its shape: that is why PCA centers first.

The best k-dimensional compression

Now judge a kk-dimensional subspace differently: by how well it reconstructs the data, measured by the mean squared distance from each point to its projection. This is Pearson's 1901 criterion of the plane of closest fit, and it leads to the same answer as Hotelling's maximum variance.

DerivationReconstruction error = total variance − captured variance
  1. ∥x~∥2=∥VV⊤x~∥2+∥x~−VV⊤x~∥2,∥VV⊤x~∥2=∥V⊤x~∥2\norm{\tilde{\mathbf x}}^2=\norm{VV^\top\tilde{\mathbf x}}^2+\norm{\tilde{\mathbf x}-VV^\top\tilde{\mathbf x}}^2,\qquad\norm{VV^\top\tilde{\mathbf x}}^2=\norm{V^\top\tilde{\mathbf x}}^2

    For orthonormal VV, the residual x~−VV⊤x~\tilde{\mathbf x}-VV^\top\tilde{\mathbf x} is orthogonal to the projection VV⊤x~VV^\top\tilde{\mathbf x}, so Pythagoras splits the squared length. The projection's length equals that of its coordinates because VV has orthonormal columns:

  2. 1n∑i=1n∥x~i−VV⊤x~i∥2=tr⁡S−tr⁡(V⊤SV)\frac1n\sum_{i=1}^n\norm{\tilde{\mathbf x}_i-VV^\top\tilde{\mathbf x}_i}^2=\operatorname{tr}S-\operatorname{tr}\big(V^\top SV\big)

    Average over the data. The squared lengths average to the total variance tr⁡S=∑jλj\operatorname{tr}S=\sum_j\lambda_j, and the coordinates' squared lengths to the variance captured by the subspace, tr⁡(V⊤SV)\operatorname{tr}(V^\top SV):

  3. min⁡V⊤V=Ik 1n∑i=1n∥x~i−VV⊤x~i∥2=λk+1+⋯+λd\min_{V^\top V=I_k}\ \frac1n\sum_{i=1}^n\norm{\tilde{\mathbf x}_i-VV^\top\tilde{\mathbf x}_i}^2=\lambda_{k+1}+\dots+\lambda_d

    The total variance does not depend on VV, so minimizing reconstruction error and maximizing captured variance are the same problem. The top kk eigenvectors capture λ1+⋯+λk\lambda_1+\dots+\lambda_k, the largest possible value over all orthonormal VV (Ky Fan's theorem, proved in PCA in Depth). What is left is the sum of the discarded eigenvalues:

  4. ∇m 1n∑i=1n∥(I−VV⊤)(xi−m)∥2=−2n∑i=1n(I−VV⊤)(xi−m)=−2 (I−VV⊤)(xˉ−m)\nabla_{\mathbf m}\ \frac1n\sum_{i=1}^n\norm{(I-VV^\top)(\mathbf x_i-\mathbf m)}^2=-\frac2n\sum_{i=1}^n(I-VV^\top)(\mathbf x_i-\mathbf m)=-2\,(I-VV^\top)(\bar{\mathbf x}-\mathbf m)

    Centering at the mean is optimal too. For fixed VV the error is convex in the center m\mathbf m, and its gradient (I−VV⊤I-VV^\top is a symmetric, idempotent projection) vanishes at m=xˉ\mathbf m=\bar{\mathbf x}, or at any shift of it inside span⁡(V)\operatorname{span}(V):

EVRk=λ1+⋯+λkλ1+⋯+λd=1−mean squared reconstruction errortotal variance\mathrm{EVR}_k=\frac{\lambda_1+\dots+\lambda_k}{\lambda_1+\dots+\lambda_d}=1-\frac{\text{mean squared reconstruction error}}{\text{total variance}}
The explained-variance ratio of the first kk components. A scree plot draws λj\lambda_j, or its share, against jj.
Predict before you look

Two features have sample covariance matrix S=(5222)S=\begin{pmatrix}5&2\\2&2\end{pmatrix}. What percentage of the variance does the first principal component keep?

Show the answer

85.7 %

The trace is 7 and the determinant 5⋅2−2⋅2=65\cdot2-2\cdot2=6, so the eigenvalues solve λ2−7λ+6=0\lambda^2-7\lambda+6=0: λ1=6\lambda_1=6 and λ2=1\lambda_2=1. PC1 is (2,1)/5(2,1)/\sqrt5, since S(2,1)⊤=(12,6)⊤=6 (2,1)⊤S(2,1)^\top=(12,6)^\top=6\,(2,1)^\top. It keeps 6/7≈85.7%6/7\approx85.7\%, and projecting onto it leaves a mean squared reconstruction error of λ2=1\lambda_2=1. The total variance 5+25+2 equals the sum of the eigenvalues, as it must.

Rule for choosing kkHow it worksCaveat
Variance targetsmallest kk with EVRk≥90%\mathrm{EVR}_k\ge90\% (or 95%, 99%)arbitrary; on noisy high-dimensional data it can keep mostly noise
Scree elbow (Cattell, 1966)keep the components before the plot flattens into a "scree" of small, similar eigenvaluesthe elbow is often ambiguous
Kaiser's ruleon standardized data keep λj>1\lambda_j>1, the average eigenvaluecrude: with pure noise, sampling error alone pushes many eigenvalues above 1
Downstream validationcross-validate the model that uses the componentsneeds a task; refit PCA inside every fold
Principled rules (parallel analysis, random-matrix thresholds, probabilistic PCA) are in PCA in Depth.

Computing PCA with the SVD

In practice PCA is computed from the thin singular value decomposition of the centered data, X~=UΣV⊤\tilde X=U\Sigma V^\top. Here U∈Rn×rU\in\R^{n\times r} and V∈Rd×rV\in\R^{d\times r} have orthonormal columns, Σ=diag⁡(σ1,…,σr)\Sigma=\diag(\sigma_1,\dots,\sigma_r) with σ1≥⋯≥σr>0\sigma_1\ge\dots\ge\sigma_r>0, and r=rank⁡X~r=\rank\tilde X. Substituting into the covariance gives every piece of PCA at once:

S=1nX~⊤X~=1nVΣU⊤UΣV⊤=V Σ2n V⊤,λj=σj2n,Z=X~Vk=UkΣkS=\frac1n\tilde X^\top\tilde X=\frac1nV\Sigma U^\top U\Sigma V^\top=V\,\frac{\Sigma^2}{n}\,V^\top,\qquad\lambda_j=\frac{\sigma_j^2}{n},\qquad Z=\tilde XV_k=U_k\Sigma_k
The right singular vectors are the principal directions, the squared singular values divided by nn are the variances, and the scores of the first kk components are the first kk columns of UΣU\Sigma.

Why the SVD rather than an eigendecomposition of SS:

  • Accuracy. Forming X~⊤X~\tilde X^\top\tilde X squares the condition number, which doubles the number of digits lost in the small components.
  • Cost. A full SVD takes on the order of ndmin⁡(n,d)nd\min(n,d) operations; for the top kk components, Lanczos-type and randomized methods need a few passes at about ndkndk each (the randomized SVD is derived in Linear Algebra for ML: Eigenvectors & the SVD).
  • Wide data. When d≫nd\gg n (pixels, genes), SS is d×dd\times d but has rank at most n−1n-1, since centering removes a dimension; the SVD works on the small side automatically.
python
import numpy as np
from sklearn.decomposition import PCA
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

def pca_svd(X, k):
    mean = X.mean(axis=0)
    U, s, Vt = np.linalg.svd(X - mean, full_matrices=False)  # thin SVD of centered data
    variances = s**2 / X.shape[0]          # eigenvalues of S
    shares = variances / variances.sum()   # explained-variance ratios
    scores = U[:, :k] * s[:k]              # equals (X - mean) @ Vt[:k].T
    return mean, Vt[:k], scores, shares

# scikit-learn: standardize, then keep enough components for 95% of the variance
model = make_pipeline(StandardScaler(), PCA(n_components=0.95, svd_solver="full"))
Z_train = model.fit_transform(X_train)   # fit mean, scales and directions on training data
Z_test = model.transform(X_test)         # reuse them; never refit on test data

scikit-learn's explained_variance_ divides by n−1n-1; the ratios, directions and scores are unaffected. components_ stores the directions as rows, like Vt here.

Units, outliers and labels

PCA's answer depends on the units. Multiplying a feature by cc multiplies its variance by c2c^2, so a feature recorded in large numbers can take over PC1 just because its numbers are large. When features have different units, standardize them first: PCA then diagonalizes the correlation matrix. Keep raw units when they are commensurate and their spread is meaningful, as with pixel intensities, since standardizing inflates features that are mostly noise.

Outliers. PCA minimizes squared distances, so one distant point can rotate the components, as dragging a single point showed. Robust PCA (PCA in Depth) separates a low-rank part from sparse corruptions.

Labels. PCA never sees a label. It ranks directions by spread, whatever causes it: body size, batch effects, the measuring machine. When PCA feeds a classifier, the direction that predicts the label may have little variance and be discarded.

Curved data: neighbor embeddings and autoencoders

PCA finds flat subspaces. When data lie near a curved surface, like the face photos of the first step or a rolled-up sheet (the Swiss roll), a flat subspace either needs many dimensions or presses distant parts of the surface together. Nonlinear methods trade PCA's closed form for flexibility: kernel PCA runs PCA after an implicit feature map defined by a kernel, and spectral methods such as Isomap and Laplacian eigenmaps embed a nearest-neighbor graph with eigenvectors. As of the mid-2020s, the most used tools for 2-D pictures are neighbor embeddings.

t-SNE (van der Maaten & Hinton, 2008) turns distances into neighbor probabilities, using around each point a Gaussian whose width gives every point about the same effective number of neighbors, the perplexity (typically 5 to 50). It then places points in the plane so that neighbor probabilities computed there with a heavy-tailed Student-t kernel match the original ones, minimizing a KL divergence by gradient descent. UMAP (McInnes, Healy & Melville, 2018) lays out a weighted kk-nearest-neighbor graph by minimizing a cross-entropy between edge weights and map similarities. It is usually faster, scales better to more than two output dimensions, and can place new points approximately; most t-SNE implementations must be rerun.

Check your understanding

A t-SNE plot of single-cell measurements shows clump A, twice as large as clump B, far from clump C, while B sits right next to C. Which conclusion does the plot support?

  1. Cells in A vary more than cells in B
  2. The cells within each clump are similar to one another
  3. B and C are more similar to each other than either is to A
  4. The data contain exactly three cell types
Show the answer

B. The cells within each clump are similar to one another

t-SNE is built to keep neighbors together, so membership in a tight clump is the reliable signal. Sizes are distorted by its density adaptation, gaps depend on hyperparameters and initialization, and the number of clumps can change with the perplexity.

An autoencoder replaces PCA's encoder and decoder by neural networks f:Rd→Rkf:\R^d\to\R^k and g:Rk→Rdg:\R^k\to\R^d trained to minimize 1n∑i∥xi−g(f(xi))∥2\frac1n\sum_i\norm{\mathbf x_i-g(f(\mathbf x_i))}^2. With linear maps it cannot beat PCA: Baldi & Hornik (1989) showed that this error has a unique minimum, the projection onto the top-kk principal subspace, and that its other critical points are saddles; the weights themselves are an arbitrary invertible mixture of the principal directions. With nonlinear layers it can follow curved data: the deep autoencoders of Hinton & Salakhutdinov (2006) learned codes of images that worked much better than PCA with the same number of dimensions. Unlike t-SNE, it gives an explicit map for new points and an approximate inverse.

MethodTries to preserveNew points
PCA (linear)variance; large distancesproject
Isomap, LLE, Laplacian eigenmapsdistances along the data, or local geometrynot directly
t-SNElocal neighborhoodsrerun, in most implementations
UMAPlocal neighborhoods, some coarse global structureapproximately
Autoencoderwhatever the reconstruction loss rewardsrun the encoder
Random projection (linear)all pairwise distances, approximatelymultiply
No method preserves everything: a 2-D picture of rich data must choose what to distort.

Key takeaways

  • PCA's components are the eigenvectors of the sample covariance of the centered data. λj\lambda_j is the variance along component jj, and scores on different components are uncorrelated.
  • Maximizing captured variance and minimizing mean squared reconstruction error are the same problem, because the error equals tr⁡S−tr⁡(V⊤SV)\operatorname{tr}S-\operatorname{tr}(V^\top SV); its minimum is λk+1+⋯+λd\lambda_{k+1}+\dots+\lambda_d.
  • Compute PCA from the thin SVD of the centered data: the directions are the right singular vectors, the variances σj2/n\sigma_j^2/n and the scores UΣU\Sigma. Choose kk with a variance target, a scree plot or downstream validation, and fit everything on training data only.
  • Standardize features measured in different units. PCA is sensitive to outliers and blind to labels: the direction that matters can carry little variance.
  • For curved data and pictures, use nonlinear methods knowingly: t-SNE and UMAP preserve neighborhoods, not cluster sizes or gaps, and autoencoders learn nonlinear codes, while a linear autoencoder only recovers the principal subspace.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A centered data matrix X~\tilde X has n=100n=100 rows and largest singular value σ1=20\sigma_1=20. What is the variance of the data along the first principal component (dividing by nn)?

  1. 2020
  2. 0.20.2
  3. 44
  4. 400400
Show the answer

C. 44

With X~=UΣV⊤\tilde X=U\Sigma V^\top, the covariance is S=1nX~⊤X~=VΣ2nV⊤S=\frac1n\tilde X^\top\tilde X=V\frac{\Sigma^2}nV^\top, so λ1=σ12/n=400/100=4\lambda_1=\sigma_1^2/n=400/100=4.

Question 2

A dataset's covariance eigenvalues are 4, 2, 1, 0.5, 0.54,\ 2,\ 1,\ 0.5,\ 0.5. You keep the first two principal components. What is the mean squared reconstruction error?

  1. 22
  2. 66
  3. 0.250.25
  4. 11
Show the answer

A. 22

The error is the sum of the discarded eigenvalues, 1+0.5+0.5=21+0.5+0.5=2, and the kept share is 6/8=75%6/8=75\%. Error and captured variance always add up to the total variance, here 8.

Question 3

Before running PCA without standardization, you change one feature's unit from meters to centimeters, multiplying it by 100. What happens?

  1. Nothing: principal components do not depend on units
  2. That feature's variance grows by a factor of 10,000, and PC1 swings toward it
  3. Only the scores are multiplied by 100; the directions stay the same
  4. That feature's loading on PC1 shrinks by a factor of 100
Show the answer

B. That feature's variance grows by a factor of 10,000, and PC1 swings toward it

Scaling a feature by cc scales its variance by c2c^2 and its covariances by cc. PCA ranks directions by raw variance, so the rescaled feature soon dominates PC1. PCA is invariant to rotations and shifts of the data, not to rescaling individual features; standardizing removes the dependence on units.

Question 4

A linear autoencoder Rd→Rk→Rd\R^d\to\R^k\to\R^d is trained to the global minimum of its squared reconstruction error on centered data whose covariance eigenvalues are distinct. What has it learned?

  1. Exactly the top kk principal directions, as the columns of its decoder
  2. A better subspace than PCA's, because gradient descent explores more solutions
  3. A subspace that depends on the random initialization and has no relation to PCA
  4. A decoder whose columns span the same subspace as the top kk principal directions
Show the answer

D. A decoder whose columns span the same subspace as the top kk principal directions

The best rank-kk linear reconstruction is the projection onto the top-kk principal subspace, so the trained network must compute it. But replacing decoder DD and encoder EE by DADA and A−1EA^{-1}E, for any invertible k×kk\times k matrix AA, leaves the map unchanged: the decoder's columns are some basis of that subspace, not necessarily the principal directions.

Go deeper

Further reading

  • H. Hotelling, "Analysis of a complex of statistical variables into principal components," Journal of Educational Psychology 24(6), 417–441 and 24(7), 498–520 (1933).
  • I. T. Jolliffe & J. Cadima, "Principal component analysis: a review and recent developments," Philosophical Transactions of the Royal Society A 374, 20150202 (2016).
  • L. van der Maaten & G. Hinton, "Visualizing data using t-SNE," Journal of Machine Learning Research 9, 2579–2605 (2008).
  • T. Hastie, R. Tibshirani & J. Friedman, The Elements of Statistical Learning, 2nd ed. (Springer, 2009), chapter 14.