Skip to content
Classical machine learning Core 28 min read

PCA, t-SNE and UMAP

Dimensionality reduction finds a few coordinates that keep what matters about many. PCA keeps the directions of greatest variance with one linear projection; t-SNE and UMAP keep each point's neighbours with a nonlinear layout, at the price of distorting sizes and distances. Know which one preserves what, and you will stop misreading embedding plots.

10,000 ft

Real data have many measured dimensions but far fewer degrees of freedom: a face image has a million pixels but varies along pose, lighting, identity and expression. This manifold hypothesis is why learning works at all, and finding those few coordinates is a recurring task in AI. PCA is everywhere: preprocessing, whitening, compressing embeddings, finding the directions inside an LLM's activations that encode a concept (as in representation engineering and interpretability), and explaining why low-rank fine-tuning (LoRA) works. t-SNE and UMAP are how people look at embeddings, single-cell atlases and model activations. The modern descendants are learned: autoencoders and contrastive embeddings are nonlinear dimensionality reduction trained end to end, and t-SNE and UMAP turn out to be contrastive learning in disguise.

2,000 ft

Two different questions, two families of answer:

  1. Keep the global geometry (PCA). Centre the data, find the orthogonal directions along which it varies most (the top eigenvectors of the covariance matrix, equivalently the top right singular vectors of the data matrix), and project onto the first \(k\). This is also the best rank-\(k\) reconstruction in squared error. Linear, unique, fast, invertible up to the discarded part.
  2. Keep the neighbourhoods (t-SNE, UMAP). Turn distances into neighbour probabilities in the original space, then place points in 2-D so that similar probabilities computed with a heavy-tailed kernel match them. Neighbours stay together and clusters separate cleanly, but cluster sizes, gaps between clusters and global arrangement are not to be trusted.
  3. Between them sit random projections (preserve all distances approximately, with no learning at all) and manifold learners (Isomap, LLE, Laplacian eigenmaps).

Dimensionality reduction: what each family preserves
Dimensionality reduction: what each family preserves. High-dimensional data n points in D dims, Linear projections PCA: variance; random projection: all distances, roughly, Manifold learning Isomap: geodesics; LLE, Laplacian eigenmaps: local geometry, Neighbour embeddings t-SNE, UMAP: who is near whom, Learned encoders autoencoders, contrastive embeddings, global, exact, invertible-ish, global shaDimensionality reduction: what each family preserves. High-dimensional data n points in D dims, Linear projections PCA: variance; random projection: all distances, roughly, Manifold learning Isomap: geodesics; LLE, Laplacian eigenmaps: local geometry, Neighbour embeddings t-SNE, UMAP: who is near whom, Learned encoders autoencoders, contrastive embeddings, global, exact, invertible-ish, global sha

Ground level

Why reduce dimension at all

Three reasons, in increasing order of subtlety. Cost: fewer columns means faster models and smaller indexes. Noise: if the signal lives in a few directions and noise is spread over all of them, projecting onto the signal directions throws away mostly noise. Geometry: high-dimensional space behaves strangely. Draw 500 uniform random points in the unit cube and measure, from one of them, the ratio of the farthest to the nearest distance (the code in Build it does this):

dimension \(d\) 2 10 100 1000
farthest / nearest 67.1 3.32 1.36 1.11

In 1,000 dimensions every point is almost equally far from every other: distance concentration. "Nearest neighbour" loses its meaning unless the data actually live on a lower-dimensional structure, which, happily, real data usually do.

PCA: the two equivalent views

Let \(X \in \mathbb{R}^{n\times D}\) be centred (each column has mean zero) and \(C = \frac{1}{n-1}X^\top X\) its covariance matrix.

  • Maximum variance. Find the unit vector \(\mathbf{v}\) maximising the variance of the projections \(X\mathbf{v}\), which is \(\mathbf{v}^\top C\mathbf{v}\). The answer is the top eigenvector of \(C\), and the variance captured is its eigenvalue \(\lambda_1\). The next direction, orthogonal to the first, is the second eigenvector, and so on.
  • Minimum reconstruction error. Find the \(k\)-dimensional subspace whose orthogonal projection \(\hat X = XV_kV_k^\top\) minimises \(\lVert X - \hat X\rVert_F^2\). The answer is the same top-\(k\) eigenvectors, and the residual is \((n-1)\sum_{j>k}\lambda_j\).

Because the total variance \(\sum_j\lambda_j\) is fixed, maximising what you keep and minimising what you lose are the same problem. In practice you compute PCA with the SVD of the centred data, \(X = U S V^\top\): the right singular vectors \(V\) are the principal directions, \(\lambda_j = s_j^2/(n-1)\), and the scores (projected coordinates) are \(XV_k = U_kS_k\). The SVD is more numerically stable than forming \(X^\top X\). (The linear algebra is developed in eigenvectors, SVD and PCA; here we use it.)

Worked example

Four centred points: \((2, 2)\), \((-2, -2)\), \((1, -1)\), \((-1, 1)\). Sums: \(\sum x^2 = 10\), \(\sum xy = 6\), \(\sum y^2 = 10\), so

\[ C = \frac13\begin{pmatrix}10 & 6\\ 6 & 10\end{pmatrix}, \qquad \lambda_{1,2} = \frac{10 \pm 6}{3} = 5.33,\ 1.33, \qquad \mathbf{v}_1 = \tfrac{1}{\sqrt2}(1, 1),\ \ \mathbf{v}_2 = \tfrac{1}{\sqrt2}(1, -1). \]

PC1 explains \(5.33/6.67 = 80\%\) of the variance. The 1-D scores are \(\mathbf{x}^\top\mathbf{v}_1 = 2.83, -2.83, 0, 0\). The last two points are lost entirely: their squared norms (\(2 + 2 = 4\)) are the reconstruction error, and indeed \((n-1)\lambda_2 = 3 \times 1.33 = 4\), which is 20% of the total squared norm of 20.

Using PCA well

  • Standardise when units differ. PCA on raw features measured in rupees and in years finds "the rupee direction". On standardised features it is PCA of the correlation matrix. Neither is always right; decide whether scale carries meaning.
  • Choosing \(k\): keep enough components for 90–99% of variance, look for an elbow in the scree plot of \(\lambda_j\), or cross-validate the downstream task. Beware: when noise is spread over many dimensions, even a perfect signal subspace "explains" a modest fraction. In the Build-it example, three components recover the true subspace almost exactly (cosines of principal angles above 0.997), yet explain only 75% of variance, because 47 noise dimensions carry the rest.
  • Whitening: rescale each component by \(1/\sqrt{\lambda_j}\) so that the result has identity covariance. Useful before ICA or some clustering; it amplifies noise in small components.
  • PCA is not robust. One extreme outlier can rotate the first component towards itself, since variance is a sum of squares.
  • Variance is not relevance. The direction that separates your two classes may have tiny variance compared with an irrelevant nuisance. Supervised alternatives (linear discriminant analysis, partial least squares) use the labels.

Random projections and the Johnson–Lindenstrauss lemma

A surprising alternative to fitting anything: multiply by a random \(k \times D\) Gaussian matrix scaled by \(1/\sqrt{k}\). The Johnson–Lindenstrauss lemma says that for any \(n\) points, \(k = O(\log n/\varepsilon^2)\) dimensions suffice to preserve all pairwise distances within a factor \(1 \pm \varepsilon\) with high probability, independently of \(D\). Random projections are data-oblivious and nearly free, which is why they appear in sketching, locality-sensitive hashing and as cheap first steps before nearest-neighbour search.

Nonlinear manifolds

PCA can only find flat subspaces. A "Swiss roll" (a sheet of paper rolled up in 3-D) is intrinsically 2-D, but no plane unrolls it. Classic manifold learners (all 2000-ish) build a nearest-neighbour graph, which only trusts local Euclidean distances, and then embed the graph:

  • Kernel PCA (Schölkopf, Smola and Müller, 1998): PCA in a kernel feature space, using only the Gram matrix (kernels).
  • Isomap (Tenenbaum, de Silva and Langford, 2000): estimate geodesic distances as shortest paths in the graph, then embed them with classical multidimensional scaling.
  • LLE (Roweis and Saul, 2000): write each point as a weighted combination of its neighbours, then find low-dimensional points that satisfy the same weights.
  • Laplacian eigenmaps: use the bottom eigenvectors of the graph Laplacian, the same object as spectral clustering. UMAP uses this as its default initialisation.

These preserve manifold geometry well on clean data, but are fragile to noise and "short circuits" in the neighbour graph. For visualising messy real data, neighbour embeddings took over.

t-SNE: matching neighbour probabilities

Stochastic neighbour embedding (Hinton and Roweis, 2002) and its successor t-SNE (van der Maaten and Hinton, 2008) recast embedding as matching two probability distributions over pairs.

t-SNE and UMAP share one recipe
t-SNE and UMAP share one recipe. High-D neighbour graph per-point bandwidth (perplexity, or k neighbours), Affinities P Gaussian on distances, symmetrised, Low-D layout Y initialised by PCA or spectral embedding, Low-D similarities Q heavy-tailed kernel 1/(1+d^2), Mismatch loss t-SNE: KL(P||Q); UMAP: fuzzy cross-entropy, Gradient step attract neighbours, repel everything else, repeatt-SNE and UMAP share one recipe. High-D neighbour graph per-point bandwidth (perplexity, or k neighbours), Affinities P Gaussian on distances, symmetrised, Low-D layout Y initialised by PCA or spectral embedding, Low-D similarities Q heavy-tailed kernel 1/(1+d^2), Mismatch loss t-SNE: KL(P||Q); UMAP: fuzzy cross-entropy, Gradient step attract neighbours, repel everything else, repeat
  1. High-dimensional affinities. For each point \(i\), define a distribution over the other points with a Gaussian centred on \(\mathbf{x}_i\): \(p_{j\mid i} \propto \exp(-\lVert\mathbf{x}_i - \mathbf{x}_j\rVert^2/2\sigma_i^2)\). Each \(\sigma_i\) is set by bisection so that the distribution has a chosen perplexity \(2^{H(P_i)}\), roughly "the effective number of neighbours". Perplexity 30 means entropy \(\log_2 30 = 4.91\) bits. Dense regions get small \(\sigma_i\), sparse ones large: the method adapts to local density, which is also why cluster sizes in the output say nothing about density in the input.
  2. Symmetrise: \(p_{ij} = (p_{j\mid i} + p_{i\mid j})/2n\), a joint distribution over pairs.
  3. Low-dimensional similarities with a Student-t kernel with one degree of freedom (a Cauchy kernel): \(q_{ij} = (1 + \lVert\mathbf{y}_i - \mathbf{y}_j\rVert^2)^{-1} / Z\), normalised over all pairs.
  4. Minimise \(\mathrm{KL}(P\,\Vert\,Q) = \sum_{ij}p_{ij}\log(p_{ij}/q_{ij})\) by gradient descent with momentum, starting from a small random or (better) PCA layout. For the first few hundred iterations, multiply \(P\) by about 12 (early exaggeration) so that clusters form before the fine structure settles.

The gradient has a physical reading: \(\partial C/\partial\mathbf{y}_i = 4\sum_j(p_{ij} - q_{ij})(1 + \lVert\mathbf{y}_i - \mathbf{y}_j\rVert^2)^{-1}(\mathbf{y}_i - \mathbf{y}_j)\), springs that pull together pairs whose \(p\) exceeds their \(q\) and push apart the rest. Exact t-SNE costs \(O(n^2)\) per iteration; the Barnes–Hut approximation (van der Maaten, 2014) brings it to \(O(n\log n)\) and FFT-based interpolation (FIt-SNE, openTSNE) to roughly \(O(n)\), so millions of points are routine.

Why the heavy tail: the crowding problem

In 10 dimensions, a ball of radius \(2r\) has \(2^{10} = 1024\) times the volume of a ball of radius \(r\); in 2-D only \(4\) times. A point can have many neighbours at a moderate distance in high-D, but there is no room for all of them at that distance in the plane. If the low-dimensional kernel had the same Gaussian shape as the high-dimensional one, moderately distant points would be crushed together in the middle. The Student-t kernel's polynomial tail means a moderate \(p_{ij}\) can be matched by a large low-dimensional distance, which gives clusters room and pushes them apart.

d = 3: Gaussian 0.011, Cauchy 0.10 012345distance between two points 10 Gaussian e^(−d²/2): SNE Student-t 1/(1+d²): t-SNE
Similarity as a function of distance. At distance 3 the Cauchy kernel is about nine times the Gaussian, so a moderate similarity is reproduced at a much larger distance in the plane. That extra room is what lets t-SNE separate clusters that SNE crushed together.

Reading a t-SNE plot without fooling yourself

The KL divergence \(\mathrm{KL}(P\Vert Q)\) is asymmetric: placing true neighbours far apart (large \(p\), small \(q\)) is heavily penalised, while placing non-neighbours close (small \(p\), larger \(q\)) is cheap. So t-SNE is faithful about who is near whom and loose about everything else. Wattenberg, Viégas and Johnson's interactive essay shows the consequences:

  • Cluster sizes mean nothing. Dense and sparse clusters come out similar in size, because bandwidths adapt to density.
  • Distances between clusters mean little. Two well-separated clusters may be placed near or far.
  • Random noise can look clustered at low perplexity, and shapes depend strongly on perplexity: always look at several values.
  • Different runs differ. Fix seeds, and prefer PCA initialisation, which makes runs reproducible and keeps more global structure (Kobak and Berens, 2019, recommend PCA initialisation, a learning rate that grows with \(n\), and multi-scale kernels).

UMAP: the same recipe, different ingredients

UMAP (McInnes, Healy and Melville, 2018) is motivated by topology (fuzzy simplicial sets on a Riemannian manifold), but its computation is a close cousin of t-SNE:

  1. Build a \(k\)-nearest-neighbour graph (default \(k = 15\)). For each point, \(\rho_i\) is the distance to its nearest neighbour and \(\sigma_i\) is chosen so that \(\sum_j \exp(-(d_{ij} - \rho_i)/\sigma_i) = \log_2 k\). Edge weights \(w_{j\mid i} = \exp(-(d_{ij} - \rho_i)/\sigma_i)\) guarantee every point is connected to its nearest neighbour with weight 1.
  2. Symmetrise by the fuzzy union \(w_{ij} = w_{j\mid i} + w_{i\mid j} - w_{j\mid i}w_{i\mid j}\) (probability that at least one directed edge exists).
  3. In the low-dimensional space, use \(v_{ij} = (1 + a\lVert\mathbf{y}_i - \mathbf{y}_j\rVert^{2b})^{-1}\), with \(a, b\) fitted from the min_dist parameter (how tightly points may pack); \(a = b = 1\) is t-SNE's kernel.
  4. Minimise the fuzzy cross-entropy \(\sum_{ij} w_{ij}\log\frac{w_{ij}}{v_{ij}} + (1 - w_{ij})\log\frac{1 - w_{ij}}{1 - v_{ij}}\) by stochastic gradient descent: sample an edge and pull its ends together; sample a few random points and push them away (negative sampling).

The second term is the important difference: UMAP has an explicit repulsion for non-edges and no global normalisation \(Z\), which makes it fast (no all-pairs sum) and lets it embed new points. UMAP was widely reported to preserve global structure better than t-SNE; Kobak and Linderman (2021) showed that this advantage came almost entirely from initialisation (UMAP's default spectral start against t-SNE's then-default random start). With the same informative initialisation the two preserve global structure about equally well. Damrich et al. (2022) later showed both are instances of contrastive learning with different negative-sampling schemes, which places them on a spectrum with the contrastive objectives used to train embedding models.

Do not compute on the picture

t-SNE and UMAP coordinates are for looking, not for measuring. Chari and Pachter (2023) show that reducing hundreds or thousands of dimensions to two "inevitably induces significant distortion", and argue that quantitative analyses (distances, cluster sizes, trajectories) should be done in the original or PCA space. If you cluster, cluster in a moderate-dimensional space (say 10–50 PCA components, or a UMAP with 10+ dimensions) and use the 2-D plot only to display the result.

Dimensionality reduction in modern AI

  • Low-rank structure everywhere. Fine-tuning updates of large models are approximately low-rank: Aghajanyan, Zettlemoyer and Gupta (2020) tuned RoBERTa to 90% of full performance on MRPC by optimising only 200 parameters randomly projected into the full space, an observation that motivated LoRA (Hu et al., 2021).
  • Directions in activation space. Representation engineering (Zou et al., 2023) applies PCA to differences in an LLM's activations between contrasting prompts to find "reading vectors" for concepts such as honesty; Arditi et al. (2024) find that refusal in many chat models is mediated by a single direction (computed as a difference of means) whose removal disables refusals. See interpretability.
  • Truncatable embeddings. Matryoshka representation learning (Kusupati et al., 2022) trains embeddings so that every prefix of the vector is itself a good embedding, reporting "up to 14× smaller embedding size for ImageNet-1K classification at the same level of accuracy". It is PCA-like ordering of information, learned. Many embedding APIs expose this as a dimensions parameter (see vector search).
  • Looking at models. UMAP or t-SNE of token embeddings, sentence embeddings or SAE features is the standard first plot in embedding and interpretability work, with all the caveats above.

History

  • 1901: Pearson, "On lines and planes of closest fit": PCA as the best-fitting line, the reconstruction view.
  • 1933: Hotelling names principal components and gives the variance view.
  • 1936: Eckart and Young prove that truncated SVD gives the best low-rank approximation.
  • 1984: Johnson and Lindenstrauss prove their lemma, as a step in a result about Lipschitz extensions.
  • 1998–2000: kernel PCA; Isomap and LLE appear back to back in the same issue of Science.
  • 2002–2008: SNE (Hinton and Roweis), then t-SNE (van der Maaten and Hinton) with the Student-t kernel; Barnes–Hut t-SNE in 2014.
  • 2018: UMAP; it rapidly becomes the default in single-cell biology and embedding visualisation.
  • 2019–2023: Kobak and Berens, Kobak and Linderman, Damrich et al. and Chari and Pachter clarify what these methods do and do not preserve.

First principles

Why eigenvectors? Maximise \(\mathbf{v}^\top C\mathbf{v}\) subject to \(\mathbf{v}^\top\mathbf{v} = 1\). The Lagrangian \(\mathbf{v}^\top C\mathbf{v} - \lambda(\mathbf{v}^\top\mathbf{v} - 1)\) has gradient \(2C\mathbf{v} - 2\lambda\mathbf{v}\), which vanishes exactly when \(C\mathbf{v} = \lambda\mathbf{v}\); the objective there equals \(\lambda\), so the maximiser is the eigenvector with the largest eigenvalue. Symmetry of \(C\) guarantees real eigenvalues and orthogonal eigenvectors, which is why the components are uncorrelated.

When is variance the right thing to keep? If data are Gaussian, the covariance is a complete description, and projecting onto top eigenvectors keeps the most information in a precise sense: probabilistic PCA (a linear-Gaussian latent variable model, \(\mathbf{x} = W\mathbf{z} + \boldsymbol\mu + \boldsymbol\varepsilon\)) has PCA as its maximum-likelihood solution. For non-Gaussian structure (clusters, curved manifolds, independent sources), variance can point the wrong way, and you need ICA, manifold learners or neighbour embeddings.

Why can no 2-D map be faithful? Ten points that are mutually equidistant in 9 dimensions (a regular simplex) cannot be placed in the plane with equal pairwise distances: at most three points can be mutually equidistant in 2-D. Every map to 2-D must sacrifice something; the only choice is what. PCA sacrifices the small-variance directions and keeps global geometry; t-SNE and UMAP sacrifice global geometry and keep neighbourhoods.

Why the KL direction matters. \(\mathrm{KL}(P\Vert Q)\) weights each pair's mismatch by \(p_{ij}\), so pairs that are neighbours in high-D dominate. Reverse it, \(\mathrm{KL}(Q\Vert P)\), and the loss would care most about pairs close in the map, preserving gaps between clusters instead. The asymmetry, explored on the information theory page, decides which errors the method tolerates.

The maths

PCA via SVD. Shapes: \(X \in \mathbb{R}^{n\times D}\) centred, \(X = USV^\top\) with \(U \in \mathbb{R}^{n\times r}\), \(S = \operatorname{diag}(s_1 \ge \dots \ge s_r > 0)\), \(V \in \mathbb{R}^{D\times r}\), \(r = \operatorname{rank}X\). Then \(C = \frac{1}{n-1}X^\top X = V\frac{S^2}{n-1}V^\top\), so the columns of \(V\) are eigenvectors of \(C\) with \(\lambda_j = s_j^2/(n-1)\). Scores \(T_k = XV_k = U_kS_k \in \mathbb{R}^{n\times k}\); reconstruction \(\hat X = T_kV_k^\top\).

Derivation: PCA minimises reconstruction error (Eckart–Young for projections)

For an orthonormal \(V_k \in \mathbb{R}^{D\times k}\), the projection \(P = V_kV_k^\top\) is symmetric and idempotent, so

\[ \lVert X - XP\rVert_F^2 = \operatorname{tr}\big((X - XP)^\top(X - XP)\big) = \operatorname{tr}(X^\top X) - \operatorname{tr}(PX^\top XP) = \operatorname{tr}(X^\top X) - \operatorname{tr}(V_k^\top X^\top XV_k). \]

Minimising the error is maximising \(\operatorname{tr}(V_k^\top CV_k) = \sum_{j=1}^k\mathbf{v}_j^\top C\mathbf{v}_j\), the variance captured. By the Ky Fan maximum principle this is at most \(\lambda_1 + \dots + \lambda_k\), with equality when \(V_k\) spans the top \(k\) eigenvectors. The minimum error is \((n-1)\sum_{j>k}\lambda_j = \sum_{j>k}s_j^2\). Eckart and Young proved the stronger statement that the truncated SVD \(U_kS_kV_k^\top\) is the best rank-\(k\) approximation among all rank-\(k\) matrices, not just projections.

Derivation: the t-SNE gradient

Write \(w_{ij} = (1 + d_{ij}^2)^{-1}\) with \(d_{ij} = \lVert\mathbf{y}_i - \mathbf{y}_j\rVert\), \(Z = \sum_{k\ne l}w_{kl}\) and \(q_{ij} = w_{ij}/Z\). Since \(\sum p_{ij} = 1\),

\[ C = \sum_{ij}p_{ij}\log p_{ij} - \sum_{ij}p_{ij}\log w_{ij} + \log Z . \]

Differentiate with respect to \(\mathbf{y}_i\). Each unordered pair \(\{i,j\}\) appears twice in the sums. \(\partial w_{ij}/\partial\mathbf{y}_i = -2w_{ij}^2(\mathbf{y}_i - \mathbf{y}_j)\), so \(\partial\log w_{ij}/\partial\mathbf{y}_i = -2w_{ij}(\mathbf{y}_i - \mathbf{y}_j)\). Then

\[ \frac{\partial}{\partial\mathbf{y}_i}\Big(-\sum_{kl}p_{kl}\log w_{kl}\Big) = 4\sum_j p_{ij}w_{ij}(\mathbf{y}_i - \mathbf{y}_j), \qquad \frac{\partial\log Z}{\partial\mathbf{y}_i} = \frac{1}{Z}\cdot 2\sum_j\big(-2w_{ij}^2(\mathbf{y}_i - \mathbf{y}_j)\big) = -4\sum_j q_{ij}w_{ij}(\mathbf{y}_i - \mathbf{y}_j). \]

Adding, \(\dfrac{\partial C}{\partial\mathbf{y}_i} = 4\sum_j(p_{ij} - q_{ij})\,w_{ij}\,(\mathbf{y}_i - \mathbf{y}_j)\). The \(p\) term is attraction along edges of the neighbour graph; the \(q\) term is repulsion between all pairs, and its normalisation \(Z\) is what Barnes–Hut and FFT methods approximate, and what UMAP replaces with negative sampling.

Perplexity calibration. For point \(i\) and precision \(\beta_i = 1/2\sigma_i^2\), \(H(P_i) = -\sum_j p_{j\mid i}\log_2 p_{j\mid i}\) decreases monotonically as \(\beta_i\) grows (narrower kernel, fewer effective neighbours), so bisection on \(\beta_i\) until \(2^{H} = \text{perplexity}\) always converges.

Johnson–Lindenstrauss, the core step. For a fixed unit vector \(\mathbf{u}\) and \(R \in \mathbb{R}^{k\times D}\) with i.i.d. \(\mathcal{N}(0, 1/k)\) entries, \(\lVert R\mathbf{u}\rVert^2\) is \(\frac1k\chi^2_k\): mean 1, and concentrated so that \(P(|\lVert R\mathbf{u}\rVert^2 - 1| > \varepsilon) \le 2e^{-k(\varepsilon^2 - \varepsilon^3)/4}\). A union bound over the \(\binom{n}{2}\) difference vectors gives \(k \ge 4\ln n/(\varepsilon^2/2 - \varepsilon^3/3)\) (the Dasgupta–Gupta form). For \(n = 10^6\) and \(\varepsilon = 0.1\) that is about 12,000 dimensions, whatever \(D\) is.

In practice

  • PCA first, almost always. Before t-SNE/UMAP, before k-means on high-dimensional data, before a nearest-neighbour index, reduce to 30–100 principal components: it denoises and speeds everything up. Randomised SVD (scikit-learn's svd_solver="randomized") handles millions of rows.
  • t-SNE settings: perplexity 30 is a sensible default (try 5–50, and larger for large \(n\)); PCA initialisation; learning rate scaled with \(n\) (openTSNE and recent scikit-learn do this automatically); enough iterations that the KL has flattened.
  • UMAP settings: n_neighbors trades local (5–15) against global (50–200) structure; min_dist controls how tightly points pack (0.0 for clustering input, 0.1–0.5 for display); spectral initialisation (the default). Set random_state for reproducibility (it disables some parallelism).
  • Show more than one plot. Vary perplexity or n_neighbors and seeds; patterns that survive are real. Colour by known metadata to check that the picture means what you think.
  • Never draw conclusions from cluster sizes, inter-cluster distances or apparent "trajectories" in a 2-D embedding without checking in the original space.

Common misconceptions

“The first principal component is the most important feature”

It is the direction of greatest variance, which may be a nuisance factor (lighting, batch effects, document length). Importance is defined by your task.

“UMAP preserves global structure; t-SNE does not”

Mostly an artefact of default initialisation, as Kobak and Linderman showed. Both preserve local structure well and global structure only as much as their initialisation and settings allow.

“PCA needs Gaussian data”

PCA is a well-defined linear-algebra operation on any data. Gaussianity is what makes variance a complete summary; without it, PCA still gives the best linear reconstruction, but may miss structure that is not about variance.

Build it

First, distance concentration and PCA by SVD on 1,000 points in 50-D that secretly live near a 3-D subspace:

import numpy as np
rng = np.random.default_rng(0)

# 1) Distances concentrate in high dimension: nearest and farthest neighbours look alike
for d in (2, 10, 100, 1000):
    P = rng.uniform(size=(500, d))
    dist = np.sqrt(((P[1:] - P[0])**2).sum(1))
    print(f"d={d:>4}: farthest/nearest distance ratio from one point = {dist.max()/dist.min():6.2f}")

# 2) PCA by SVD: 1,000 points in 50-D that really live near a 3-D subspace
n, D, k = 1000, 50, 3
Z = rng.normal(size=(n, k)) * np.array([5.0, 3.0, 1.5])     # latent factors with different scales
A = np.linalg.qr(rng.normal(size=(D, k)))[0]                 # random orthonormal embedding, D x k
X = Z @ A.T + 0.5 * rng.normal(size=(n, D))                  # plus isotropic noise
Xc = X - X.mean(0)                                           # centring is not optional
U, S, Vt = np.linalg.svd(Xc, full_matrices=False)
var = S**2 / (n - 1)                                         # eigenvalues of the covariance matrix
print("top 6 eigenvalues:", var[:6].round(2))
print("explained variance ratio, cumulative:", (np.cumsum(var) / var.sum())[:6].round(3))
proj = Xc @ Vt[:3].T                                         # n x 3 scores
recon = proj @ Vt[:3]
print(f"relative reconstruction error with 3 components: {np.linalg.norm(Xc - recon) / np.linalg.norm(Xc):.3f}")
print("principal subspace vs true subspace, cosines of angles:", np.linalg.svd(Vt[:3] @ A)[1].round(4))
d=   2: farthest/nearest distance ratio from one point =  67.13
d=  10: farthest/nearest distance ratio from one point =   3.32
d= 100: farthest/nearest distance ratio from one point =   1.36
d=1000: farthest/nearest distance ratio from one point =   1.11
top 6 eigenvalues: [25.02  8.5   2.5   0.36  0.35  0.35]
explained variance ratio, cumulative: [0.524 0.702 0.754 0.762 0.769 0.776]
relative reconstruction error with 3 components: 0.496
principal subspace vs true subspace, cosines of angles: [0.9997 0.9992 0.9971]

The true variances are \(25\), \(9\) and \(2.25\) plus noise variance \(0.25\) in every direction, and the top three eigenvalues match (25.0, 8.5, 2.5) within sampling error. The noise eigenvalues sit near \(0.36\), not \(0.25\): with \(D/n = 0.05\), sample eigenvalues of pure noise spread up to about \(0.25(1 + \sqrt{0.05})^2 = 0.37\) (the Marchenko–Pastur edge), so the gap between 2.5 and 0.36 is how you know where signal ends. Three components recover the true subspace (principal-angle cosines above 0.997) while "explaining" only 75% of variance.

Second, exact t-SNE from scratch (perplexity bisection, symmetrised affinities, Student-t similarities, early exaggeration, momentum), compared with PCA on six clusters in 50-D:

import numpy as np
rng = np.random.default_rng(0)

def sq_dists(X):
    s = (X**2).sum(1); return np.maximum(s[:, None] + s[None, :] - 2 * X @ X.T, 0)

def affinities(X, perplexity=30.0):
    """p_{j|i} with a per-point bandwidth found by bisection so that 2^H(P_i) = perplexity."""
    D = sq_dists(X); n = len(X); P = np.zeros((n, n))
    for i in range(n):
        lo, hi, beta = 0.0, np.inf, 1.0                     # beta = 1 / (2 sigma_i^2)
        d = np.delete(D[i], i)
        for _ in range(60):
            p = np.exp(-(d - d.min()) * beta); p /= p.sum()
            H = -(p * np.log2(p + 1e-12)).sum()
            if H > np.log2(perplexity): lo = beta; beta = beta * 2 if hi == np.inf else (beta + hi) / 2
            else: hi = beta; beta = (lo + beta) / 2
        P[i, np.arange(n) != i] = p
    return (P + P.T) / (2 * n)                               # symmetrise: p_ij sums to 1

def tsne(X, dims=2, iters=750, lr=200.0):
    P = affinities(X); n = len(X)
    Y = 1e-4 * rng.normal(size=(n, dims)); vel = np.zeros_like(Y)
    for t in range(iters):
        exag = 12.0 if t < 250 else 1.0                       # early exaggeration
        W = 1 / (1 + sq_dists(Y)); np.fill_diagonal(W, 0)     # Student-t (Cauchy) kernel
        Q = W / W.sum()
        G = 4 * ((exag * P - Q) * W)                          # gradient: 4 sum_j (p-q) w (y_i - y_j)
        grad = G.sum(1)[:, None] * Y - G @ Y
        vel = (0.5 if t < 250 else 0.8) * vel - lr * grad; Y += vel
        if t in (250, 749):
            print(f"iter {t}: KL(P||Q) = {(P * np.log((P + 1e-12) / (Q + 1e-12))).sum():.3f}")
    return Y

def knn_kept(X, Y, k=10):                                    # share of each point's k-NN preserved
    a = np.argsort(sq_dists(X), 1)[:, 1:k+1]; b = np.argsort(sq_dists(Y), 1)[:, 1:k+1]
    return np.mean([len(set(a[i]) & set(b[i])) / k for i in range(len(X))])

# 6 clusters in 50-D, each a 5-D blob; the clusters sit at random corners far apart
centres = rng.normal(size=(6, 50)) * 3
X = np.vstack([c + rng.normal(size=(60, 5)) @ rng.normal(size=(5, 50)) * 0.4 for c in centres])
Xc = X - X.mean(0)
Y_pca = Xc @ np.linalg.svd(Xc, full_matrices=False)[2][:2].T
Y_tsne = tsne(X)
print(f"10-NN preserved: PCA-2D {knn_kept(X, Y_pca):.3f}   t-SNE-2D {knn_kept(X, Y_tsne):.3f}")
iter 250: KL(P||Q) = 1.471
iter 749: KL(P||Q) = 0.266
10-NN preserved: PCA-2D 0.409   t-SNE-2D 0.624

PCA's best plane keeps only 41% of each point's ten nearest neighbours, because six clusters in general position cannot all be separated by one linear projection to 2-D. t-SNE keeps 62%: it is optimising for exactly this. KL falls from 1.47 at the end of early exaggeration to 0.27.

Things to try

  • Plot Y_tsne coloured by cluster at perplexity 5, 30 and 100. Then make one cluster ten times more spread out than the others and observe that t-SNE draws it about the same size.
  • Run t-SNE on 360 points of pure Gaussian noise at perplexity 2. Do you see "clusters"?
  • Initialise t-SNE from Y_pca scaled to standard deviation 1e-4 instead of random noise and compare the arrangement of clusters across seeds.
  • Project the 50-D data with a random Gaussian matrix to \(k = 5, 20, 50\) dimensions and measure the worst relative distortion of pairwise distances, against the Johnson–Lindenstrauss prediction.
  • Implement kernel PCA with an RBF kernel (centre the Gram matrix with \(H K H\), \(H = I - \frac1n\mathbf{1}\mathbf{1}^\top\)) and unroll two concentric circles.

Check yourself

A covariance matrix has eigenvalues 9, 4, 1, 1, 1. How much variance do two components explain, and what is the best 2-D reconstruction error per sample in squared units?

Total variance 16; two components keep \(13/16 = 81.25\%\). The expected squared reconstruction error per sample is the sum of discarded eigenvalues, \(1 + 1 + 1 = 3\) (with the \(1/(n-1)\) convention, total error \(3(n-1)\)).

Why must you centre the data before PCA, and what happens if you forget?

Without centring, \(X^\top X\) is the second-moment matrix, not the covariance. The first "component" then points largely towards the mean of the data, which describes location rather than variation, and the remaining components are distorted to be orthogonal to it.

What does perplexity control in t-SNE, and why can t-SNE not tell you that one cluster is denser than another?

Perplexity sets each point's Gaussian bandwidth so that its neighbour distribution has entropy \(\log_2(\text{perplexity})\), about that many effective neighbours. Because each point's bandwidth adapts to its local density, dense and sparse clusters both end up with the same effective neighbour counts, and so similar spreads in the map.

Why does t-SNE use a Student-t kernel in the low-dimensional space but a Gaussian in the high-dimensional one?

The crowding problem: there is much less room at moderate distances in 2-D than in high-D. A heavy-tailed low-dimensional kernel lets moderately similar pairs sit far apart in the map while keeping close neighbours close, which separates clusters. In high-D a Gaussian with an adaptive bandwidth is used to define who the neighbours are.

UMAP's loss has a term (1 − w) log((1 − w)/(1 − v)). What does it do, and how is it computed efficiently?

It penalises pairs that are not neighbours in high-D (\(w \approx 0\)) but are close in the map (\(v\) near 1): explicit repulsion. Summing it over all \(O(n^2)\) pairs would be expensive, so UMAP samples a few random "negative" points per positive edge, as in word2vec's negative sampling.

Hard: you see a clear trajectory from cluster A to cluster C passing through B in a UMAP plot of cell states, and conclude that cells develop A → B → C. What could be wrong, and how would you check?

The ordering and the gaps between clusters are not reliably preserved; a chain can be an artefact of n_neighbors, initialisation or a few bridging points, and the true high-dimensional distances might put A closer to C than to B. Check in a faithful space: compute distances or a nearest-neighbour graph in PCA space, vary UMAP's parameters and seeds, and use methods designed for trajectories (pseudotime on the kNN graph) with an independent biological validation.

Hard: LoRA constrains a weight update to rank r. Using the Eckart–Young theorem, what is the best possible error of any rank-r approximation to a full fine-tuning update ΔW, and why might it be small?

\(\min_{\operatorname{rank}(M)\le r}\lVert\Delta W - M\rVert_F^2 = \sum_{j>r}s_j^2\), the sum of squared singular values of \(\Delta W\) beyond the \(r\)-th. If fine-tuning updates have rapidly decaying spectra (the intrinsic-dimension finding of Aghajanyan et al. suggests low effective dimension), that tail is small and a small \(r\) loses little. LoRA learns its low-rank factors directly rather than truncating an SVD, but the theorem sets the bound.

Go deeper

Papers

Videos and lectures

Articles and blog posts

  • How to Use t-SNE Effectively — Wattenberg, Viégas and Johnson, Distill, 2016. Interactive; the single most useful thing to read before showing anyone a t-SNE plot.
  • Understanding UMAP — Google PAIR. Interactive comparison of UMAP and t-SNE and the effect of each parameter.
  • How UMAP Works — McInnes. The author's own intuitive walk-through.

Code

  • openTSNE and umap-learn — Fast, well-documented reference implementations with good defaults.

Where this leads