Dimensionality reduction: PCA, t-SNE and UMAP
Finding the few directions that matter
High-dimensional data is mostly empty space; dimensionality reduction finds the low-dimensional structure hiding inside it. PCA is the single most-used algorithm in data science and the cleanest application of the eigenvectors and SVD you learned in 1.3 Eigen-things, SVD and low rank. t-SNE and UMAP are how you will actually look at embeddings from word vectors (6.3 Word embeddings) to LLM activations (8.11 Interpretability: what is happening inside), and knowing what their pictures do and do not mean saves you from a whole genre of wrong conclusions.
You'll be able to
- Derive PCA as variance maximization and as reconstruction minimization, and compute it via eigen-decomposition or SVD
- Choose the number of components with explained variance and apply PCA correctly (centering, scaling, whitening)
- Explain how t-SNE and UMAP work and interpret their plots without over-reading them
- Connect PCA to autoencoders, low-rank structure and embedding geometry
Key ideas
- PCA finds orthogonal directions of maximal variance: they are the eigenvectors of the covariance S = XᵀX/n, and each eigenvalue is the variance captured.
- Equivalently PCA minimizes reconstruction error; by Eckart–Young it is the truncated SVD X ≈ U_kΣ_kV_kᵀ, with λⱼ = σⱼ²/n.
- Center always, standardize when units differ, choose k by cumulative explained variance (≈90–95%), fit inside the training pipeline.
Show 4 more key ideas
- Variance ≠ relevance: PCA is unsupervised and can discard a low-variance direction that predicts the label.
- t-SNE matches neighbour probabilities with a heavy-tailed Student-t kernel by minimizing KL(P‖Q); perplexity sets the neighbourhood size.
- On t-SNE/UMAP plots, cluster sizes and inter-cluster distances are not meaningful; run several settings and never measure on the plot.
- UMAP is faster, keeps more global structure and can transform new points; a linear autoencoder recovers the PCA subspace.
Suggested path through this lesson
Why reduce dimensions
Three reasons: compression and speed (fewer features for downstream kNN or clustering), denoising (small-variance directions are often noise), and visualization (we can only see 2–3 dimensions). The methods split into linear projections that preserve global geometry (PCA) and nonlinear embeddings that preserve neighbourhoods (t-SNE, UMAP).
PCA as variance maximization
Center the data so each feature has mean zero and stack it as . The covariance matrix is (symmetric, positive semi-definite). We want the unit direction along which the projected data has the largest variance:
The Lagrangian has gradient , so : the optimal direction is an eigenvector of the covariance, and the variance it captures is . The first principal component is the eigenvector with the largest eigenvalue; the second is the top eigenvector orthogonal to the first, and so on. The explained variance ratio of component is .
Worked example. Two features with covariance . Eigenvalues solve , giving , , with eigenvectors and . The data is elongated along the diagonal; PC1 explains of the variance, and projecting onto it keeps most of the structure with one number per point.
PCA as reconstruction, and via SVD
The same components solve a different problem: find the -dimensional subspace whose orthogonal projection best reconstructs the data, minimizing . This is the Eckart–Young theorem from 1.3 Eigen-things, SVD and low rank: the best rank- approximation of comes from its SVD, . The principal directions are the columns of , the projected coordinates ("scores") are , and the eigenvalues are . Libraries compute PCA through the SVD because forming squares the condition number. Whitening additionally rescales each component to unit variance, , which decorrelates and equalizes features.
Intuition. PCA rotates your coordinate system to align with the data's own axes of spread, then drops the axes with the least spread. Nothing about the labels is involved — PCA is unsupervised.
Using PCA well
Center always; standardize when features have different units, otherwise the largest-unit feature becomes PC1. Choose by cumulative explained variance (90–95%) or a scree-plot elbow. PCA before kNN or k-means often helps (less noise, faster distances); PCA as preprocessing for a supervised model can hurt, because variance is not the same as predictive relevance — a low-variance direction may carry the label. PCA is linear and sensitive to outliers; kernel PCA and robust PCA address those. Fit PCA on the training fold only inside a pipeline (3.13 Feature engineering, data quality and data-centric ML).
t-SNE: preserving neighbourhoods
t-SNE builds a map in 2-D where nearby points stay nearby. In the input space it converts distances to conditional probabilities,
where each is set so the distribution has a user-chosen perplexity (effective number of neighbours, typically 5–50). In the map it uses a heavy-tailed Student- kernel, , and moves the points by gradient descent to minimize (1.9 Information theory: entropy, cross-entropy and KL divergence). The heavy tails fix the crowding problem: moderately distant points can be pushed far apart in 2-D without a large penalty. Consequences you must respect (Wattenberg et al., 2016): cluster sizes mean nothing, distances between clusters mean little, random noise can look clustered at low perplexity, and the result depends on the seed. Run several perplexities, and never cluster or measure on a t-SNE plot. t-SNE has no transform for new points.
UMAP
UMAP builds a weighted -nearest-neighbour graph with locally adaptive distances (so every point is connected to its neighbours), then optimizes a low-dimensional layout whose own neighbour graph matches it, minimizing a cross-entropy between edge weights. It is much faster than t-SNE, scales to millions of points, keeps somewhat more global structure, and provides transform for new data. Its knobs are n_neighbors (local vs global focus) and min_dist (how tightly points pack). The same caveats about reading distances apply.
| PCA | t-SNE | UMAP | |
|---|---|---|---|
| preserves | global variance (linear) | local neighbourhoods | local + some global |
| deterministic | yes | no (seed) | mostly |
| new points | project | no | transform |
| use for | preprocessing, compression | 2-D looks | 2-D looks, preprocessing |
Autoencoders and low rank
A linear autoencoder with hidden units trained with squared error learns the same subspace as PCA with components (4.10 Autoencoders, embeddings and representation learning); add nonlinearities and you get nonlinear PCA. Low-rank structure is everywhere later: LoRA fine-tunes an LLM by learning a rank- update (8.2 Fine-tuning and PEFT), attention heads are low-rank bilinear maps (7.2 Scaled dot-product and multi-head attention, fully derived), and Matryoshka embeddings are trained so their first coordinates behave like a PCA truncation (9.2 Embeddings deep dive).
Where this shows up later
- Eigenvectors, SVD and Eckart–Young — 1.3 Eigen-things, SVD and low rank; clustering in reduced spaces — 3.11 Clustering: k-means, GMMs/EM, DBSCAN and hierarchical; pipeline hygiene — 3.13 Feature engineering, data quality and data-centric ML.
- Autoencoders as nonlinear PCA — 4.10 Autoencoders, embeddings and representation learning; visualizing word and sentence embeddings — 6.3 Word embeddings, 9.2 Embeddings deep dive; PCA/probing on model activations in interpretability — 8.11 Interpretability: what is happening inside; low-rank adaptation — 8.2 Fine-tuning and PEFT.
Common pitfalls (4)
- Forgetting to center (and usually standardize) before PCA — the first component then just points at the mean or the largest-unit feature.
- Fitting PCA on train+test data before splitting: a subtle leakage.
- Clustering on a t-SNE embedding or reading 'cluster A is far from cluster B' off the plot.
- Choosing k by eyeballing a scree plot with no elbow; report cumulative explained variance instead.
Recap: all 7 key points
- PCA finds orthogonal directions of maximal variance: they are the eigenvectors of the covariance S = XᵀX/n, and each eigenvalue is the variance captured.
- Equivalently PCA minimizes reconstruction error; by Eckart–Young it is the truncated SVD X ≈ U_kΣ_kV_kᵀ, with λⱼ = σⱼ²/n.
- Center always, standardize when units differ, choose k by cumulative explained variance (≈90–95%), fit inside the training pipeline.
- Variance ≠ relevance: PCA is unsupervised and can discard a low-variance direction that predicts the label.
- t-SNE matches neighbour probabilities with a heavy-tailed Student-t kernel by minimizing KL(P‖Q); perplexity sets the neighbourhood size.
- On t-SNE/UMAP plots, cluster sizes and inter-cluster distances are not meaningful; run several settings and never measure on the plot.
- UMAP is faster, keeps more global structure and can transform new points; a linear autoencoder recovers the PCA subspace.
Watch
PCA via SVD on a small example, loading scores and scree plots.
Read
Try it live
Interactive demo
runs in your browserExercises
- PCA from scratch
Center a dataset (e.g. the 64-pixel digits), compute the covariance matrix, its eigen-decomposition, and the projection onto the top 2 components. Then redo it with
np.linalg.svdand with scikit-learn's PCA. Expected: identical components up to sign; the top 2 components explain roughly 20–30% of the variance for digits. - How many components?
Plot cumulative explained variance for the digits data and find k for 90% and 95%. Train a kNN classifier on raw pixels and on the PCA-reduced data at those k; compare accuracy and prediction time. Expected: similar accuracy at a fraction of the dimensions and much faster kNN.
- Misreading t-SNE, on purpose
Run t-SNE on 500 points of pure Gaussian noise at perplexities 2, 5, 30 and 100, and on the digits data. Expected: at low perplexity the noise forms spurious 'clusters'; for digits the cluster sizes change wildly with perplexity while membership stays stable — the lesson of the Distill article.
Quiz
Flashcards
These cards are now in your spaced-repetition queue. Review all due cards →