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 features is a cloud of points in , 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 by a shorter , , that keeps what matters. It buys visualization ( or ), compression ( numbers instead of ), denoising (if the signal lives in a few directions and the noise in all , 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 . 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 , 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, with , stack the as the rows of the centered data matrix , and form the sample covariance matrix
which is symmetric and positive semidefinite. (Dividing by instead rescales every eigenvalue by the same factor and changes no direction.) Projecting the points onto a unit vector gives the numbers , whose mean is 0 and whose variance is .
Look for the unit direction with the largest projected variance, equivalently the maximizer of the Rayleigh quotient . The constraint matters: without it, stretching would make the variance as large as you like.
Add a Lagrange multiplier and set the gradient to zero, using for symmetric :
Every stationary point is an eigenvector of , and the variance there equals its eigenvalue. The maximum is therefore the largest eigenvalue , attained at its eigenvector , the first principal direction.
For the second direction add the constraint with a multiplier . Multiplying the new stationarity condition by , and using , gives . So again , now orthogonal to : the answer is , with variance , and induction gives the rest.
You skip centering and take the top eigenvector of for data whose mean is and whose spread is about 1 in every direction. What does that eigenvector find?
- The direction of greatest spread, as with centered data
- The direction of least spread
- Approximately the direction of the mean, , whatever the shape of the cloud
- Nothing: without centering the matrix is singular
Show the answer
C. Approximately the direction of the mean, , whatever the shape of the cloud
The uncentered matrix is , and has eigenvalue along , swamping the eigenvalues of (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 -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.
For orthonormal , the residual is orthogonal to the projection , so Pythagoras splits the squared length. The projection's length equals that of its coordinates because has orthonormal columns:
Average over the data. The squared lengths average to the total variance , and the coordinates' squared lengths to the variance captured by the subspace, :
The total variance does not depend on , so minimizing reconstruction error and maximizing captured variance are the same problem. The top eigenvectors capture , the largest possible value over all orthonormal (Ky Fan's theorem, proved in PCA in Depth). What is left is the sum of the discarded eigenvalues:
Centering at the mean is optimal too. For fixed the error is convex in the center , and its gradient ( is a symmetric, idempotent projection) vanishes at , or at any shift of it inside :
Two features have sample covariance matrix . What percentage of the variance does the first principal component keep?
Show the answer
85.7 %
The trace is 7 and the determinant , so the eigenvalues solve : and . PC1 is , since . It keeps , and projecting onto it leaves a mean squared reconstruction error of . The total variance equals the sum of the eigenvalues, as it must.
| Rule for choosing | How it works | Caveat |
|---|---|---|
| Variance target | smallest with (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 eigenvalues | the elbow is often ambiguous |
| Kaiser's rule | on standardized data keep , the average eigenvalue | crude: with pure noise, sampling error alone pushes many eigenvalues above 1 |
| Downstream validation | cross-validate the model that uses the components | needs a task; refit PCA inside every fold |
Computing PCA with the SVD
In practice PCA is computed from the thin singular value decomposition of the centered data, . Here and have orthonormal columns, with , and . Substituting into the covariance gives every piece of PCA at once:
Why the SVD rather than an eigendecomposition of :
- Accuracy. Forming squares the condition number, which doubles the number of digits lost in the small components.
- Cost. A full SVD takes on the order of operations; for the top components, Lanczos-type and randomized methods need a few passes at about each (the randomized SVD is derived in Linear Algebra for ML: Eigenvectors & the SVD).
- Wide data. When (pixels, genes), is but has rank at most , since centering removes a dimension; the SVD works on the small side automatically.
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 datascikit-learn's explained_variance_ divides by ; 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 multiplies its variance by , 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 -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.
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?
- Cells in A vary more than cells in B
- The cells within each clump are similar to one another
- B and C are more similar to each other than either is to A
- 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 and trained to minimize . With linear maps it cannot beat PCA: Baldi & Hornik (1989) showed that this error has a unique minimum, the projection onto the top- 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.
| Method | Tries to preserve | New points |
|---|---|---|
| PCA (linear) | variance; large distances | project |
| Isomap, LLE, Laplacian eigenmaps | distances along the data, or local geometry | not directly |
| t-SNE | local neighborhoods | rerun, in most implementations |
| UMAP | local neighborhoods, some coarse global structure | approximately |
| Autoencoder | whatever the reconstruction loss rewards | run the encoder |
| Random projection (linear) | all pairwise distances, approximately | multiply |
Key takeaways
- PCA's components are the eigenvectors of the sample covariance of the centered data. is the variance along component , and scores on different components are uncorrelated.
- Maximizing captured variance and minimizing mean squared reconstruction error are the same problem, because the error equals ; its minimum is .
- Compute PCA from the thin SVD of the centered data: the directions are the right singular vectors, the variances and the scores . Choose 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.
A centered data matrix has rows and largest singular value . What is the variance of the data along the first principal component (dividing by )?
Show the answer
C.
With , the covariance is , so .
A dataset's covariance eigenvalues are . You keep the first two principal components. What is the mean squared reconstruction error?
Show the answer
A.
The error is the sum of the discarded eigenvalues, , and the kept share is . Error and captured variance always add up to the total variance, here 8.
Before running PCA without standardization, you change one feature's unit from meters to centimeters, multiplying it by 100. What happens?
- Nothing: principal components do not depend on units
- That feature's variance grows by a factor of 10,000, and PC1 swings toward it
- Only the scores are multiplied by 100; the directions stay the same
- 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 scales its variance by and its covariances by . 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.
A linear autoencoder is trained to the global minimum of its squared reconstruction error on centered data whose covariance eigenvalues are distinct. What has it learned?
- Exactly the top principal directions, as the columns of its decoder
- A better subspace than PCA's, because gradient descent explores more solutions
- A subspace that depends on the random initialization and has no relation to PCA
- A decoder whose columns span the same subspace as the top principal directions
Show the answer
D. A decoder whose columns span the same subspace as the top principal directions
The best rank- linear reconstruction is the projection onto the top- principal subspace, so the trained network must compute it. But replacing decoder and encoder by and , for any invertible matrix , leaves the map unchanged: the decoder's columns are some basis of that subspace, not necessarily the principal directions.
Go deeper
- PCA in Depth · Variance, reconstruction, the SVD and probabilistic PCA.
- Manifold Learning: t-SNE & UMAP · Nonlinear embeddings, and how to read them without being fooled.
- Random Projections & Johnson–Lindenstrauss · Why random directions preserve distances.
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.