Simple Algorithm
Machine Learning · Convergence · 28 min

Manifold Learning: t-SNE & UMAP

Nonlinear embeddings, and how to read them without being fooled.

A t-SNE or UMAP picture can turn ten thousand cells or a million documents into a tidy map of islands. This lesson builds nonlinear embeddings from their objectives, from classical MDS and Isomap to t-SNE and UMAP, derives the t-SNE gradient as a balance of attraction and repulsion, and separates what is proved about these pictures from the ways they mislead.

What you’ll learn

  • State the manifold hypothesis, derive classical MDS by double centering, and explain how Isomap, LLE and Laplacian eigenmaps turn a neighborhood graph into an eigenvalue problem.
  • Define the t-SNE objective, explain perplexity calibration and the crowding problem, and derive the gradient as attraction minus repulsion.
  • Describe UMAP's graph and loss, and what later analyses showed it effectively optimizes.
  • State what is proved about cluster recovery, list the ways embeddings mislead, and measure an embedding's faithfulness.

The manifold hypothesis and spectral embeddings

The manifold hypothesis says that high-dimensional data concentrate near a manifold of much lower dimension m≪dm\ll d: images of one object under changing pose and light, sensor readings of a system with a few degrees of freedom. It can be made testable: Fefferman, Mitter & Narayanan (2016) give an algorithm that, from samples of a distribution in a possibly infinite-dimensional Hilbert space, decides whether the data lie close to some manifold of given dimension, volume and reach (which limits both its curvature and how closely it folds back on itself). In practice it is a working assumption, and the methods below differ in which property of the manifold they try to keep.

The oldest such method needs only distances. Classical multidimensional scaling (Torgerson, 1952) takes a matrix of pairwise distances and returns coordinates that reproduce them as well as possible.

DerivationClassical MDS: from distances to coordinates
  1. B=−12 HD(2)H,D(2)=(dij2)i,j=1nB=-\tfrac12\,HD^{(2)}H,\qquad D^{(2)}=\big(d_{ij}^2\big)_{i,j=1}^n

    For centered points with Gram matrix B=X~X~⊤B=\tilde X\tilde X^\top, squared distances are dij2=bii+bjj−2bijd_{ij}^2=b_{ii}+b_{jj}-2b_{ij}. The centering matrix H=I−1n11⊤H=I-\frac1n\mathbf 1\mathbf 1^\top annihilates the terms that are constant along a row or a column, and HX~=X~H\tilde X=\tilde X, so double centering recovers BB from the distances alone:

  2. Y=UmΛm1/2⟹YY⊤=UmΛmUm⊤≈BY=U_m\Lambda_m^{1/2}\quad\Longrightarrow\quad YY^\top=U_m\Lambda_mU_m^\top\approx B

    Take the top mm eigenpairs B≈UmΛmUm⊤B\approx U_m\Lambda_mU_m^\top and set Y=UmΛm1/2Y=U_m\Lambda_m^{1/2}. By Eckart–Young this is the best rank-mm fit to BB, and when the distances are Euclidean, YY equals the PCA scores up to rotation: classical MDS on Euclidean distances is PCA.

  3. D(2) is Euclidean  ⟺  −12HD(2)H⪰0D^{(2)}\text{ is Euclidean}\iff-\tfrac12HD^{(2)}H\succeq0

    Schoenberg (1935) characterized when this can be exact: a matrix of squared distances comes from points in some Euclidean space if and only if −12HD(2)H-\frac12HD^{(2)}H is positive semidefinite. Negative eigenvalues measure how far the distances are from Euclidean.

The spectral manifold methods feed better distances, or better similarities, into the same kind of eigenproblem, all built on a kk-nearest-neighbor graph that only trusts local Euclidean distances:

  • Isomap (Tenenbaum, de Silva & Langford, 2000) replaces each distance by the shortest-path length through the graph, an estimate of the geodesic distance along the manifold, and runs classical MDS. With dense sampling it recovers manifolds isometric to a convex region of Rm\R^m; holes in the parameter region bend the result, and one noisy edge that short-circuits two folds can wreck it. Hessian eigenmaps (Donoho & Grimes, 2003) drop the convexity requirement.
  • Locally linear embedding (Roweis & Saul, 2000) writes each point as an affine combination of its neighbors, min⁡∑i∥xi−∑jWijxj∥2\min\sum_i\norm{\mathbf x_i-\sum_jW_{ij}\mathbf x_j}^2 with ∑jWij=1\sum_jW_{ij}=1, weights invariant to rotating, rescaling and translating a neighborhood, then finds coordinates reconstructed by the same weights: the bottom eigenvectors of (I−W)⊤(I−W)(I-W)^\top(I-W), skipping the constant one.
  • Laplacian eigenmaps (Belkin & Niyogi, 2003) minimize ∑ijwij∥yi−yj∥2=2tr⁡(Y⊤LY)\sum_{ij}w_{ij}\norm{\mathbf y_i-\mathbf y_j}^2=2\operatorname{tr}(Y^\top LY) with heat-kernel weights wij=e−∥xi−xj∥2/tw_{ij}=e^{-\norm{\mathbf x_i-\mathbf x_j}^2/t} and L=D−WL=D-W, subject to Y⊤DY=IY^\top DY=I: the generalized eigenproblem Ly=λDyL\mathbf y=\lambda D\mathbf y, skipping the constant eigenvector. The graph Laplacian converges to the manifold's Laplace–Beltrami operator as the sample grows (Belkin & Niyogi, 2008); the same eigenvectors drive spectral clustering. Diffusion maps (Coifman & Lafon, 2006) scale them by powers of the eigenvalues of a random walk on the graph.

All three have a global optimum computable by linear algebra, but none preserves the scale of every neighborhood, and all are fragile to noise and to the choice of kk.

SNE and t-SNE: matching neighbor distributions

SNE (Hinton & Roweis, 2002) turns distances into neighbor probabilities. Point ii picks jj as its neighbor with probability pj∣i∝exp⁡(−∥xi−xj∥2/2σi2)p_{j\mid i}\propto\exp\big(-\norm{\mathbf x_i-\mathbf x_j}^2/2\sigma_i^2\big), and each bandwidth σi\sigma_i is found by binary search so that the perplexity 2H(Pi)2^{H(P_i)}, with HH the entropy in bits, equals a chosen value: an effective number of neighbors, typically 5 to 50. Map points yi\mathbf y_i define qj∣iq_{j\mid i} the same way, with one fixed bandwidth, and SNE minimizes ∑iDKL(Pi ∥ Qi)\sum_i\KL(P_i\,\|\,Q_i). The asymmetry of the KL divergence sets priorities: neighbors placed far apart (large pp, small qq) cost a lot, while non-neighbors placed close cost little.

t-SNE (van der Maaten & Hinton, 2008) makes two changes. It symmetrizes the input affinities, pij=(pj∣i+pi∣j)/2np_{ij}=(p_{j\mid i}+p_{i\mid j})/2n, and it gives the map a heavy-tailed Student-t kernel with one degree of freedom:

qij=wijZ,wij=(1+∥yi−yj∥2)−1,Z=∑k≠lwkl,C=DKL(P ∥ Q)=∑i≠jpijlog⁡pijqij.q_{ij}=\frac{w_{ij}}{Z},\qquad w_{ij}=\big(1+\norm{\mathbf y_i-\mathbf y_j}^2\big)^{-1},\qquad Z=\sum_{k\ne l}w_{kl},\qquad C=\KL(P\,\|\,Q)=\sum_{i\ne j}p_{ij}\log\frac{p_{ij}}{q_{ij}}.
Predict before you look

A point's conditional neighbor distribution puts probability 0.50.5 on one neighbor and 0.250.25 on each of two others. What is its perplexity?

Show the answer

2.83

H=−(0.5log⁡20.5+2×0.25log⁡20.25)=0.5+1=1.5H=-(0.5\log_20.5+2\times0.25\log_20.25)=0.5+1=1.5 bits, so the perplexity is 21.5≈2.832^{1.5}\approx2.83: between 2 and 3 effective neighbors, as the uneven weights suggest. A uniform distribution over kk neighbors has perplexity exactly kk, which is why perplexity reads as an effective neighborhood size.

DerivationThe t-SNE gradient: attraction minus repulsion
  1. C=∑i≠jpijlog⁡pij−∑i≠jpijlog⁡wij+log⁡ZC=\sum_{i\ne j}p_{ij}\log p_{ij}-\sum_{i\ne j}p_{ij}\log w_{ij}+\log Z

    Since ∑pij=1\sum p_{ij}=1, the cost splits into a constant, an attraction term and the log of the normalizer:

  2. ∂C∂yi=4∑jpij wij(yi−yj)−4∑jqij wij(yi−yj)=4∑j(pij−qij) wij (yi−yj)\frac{\partial C}{\partial\mathbf y_i}=4\sum_{j}p_{ij}\,w_{ij}(\mathbf y_i-\mathbf y_j)-4\sum_jq_{ij}\,w_{ij}(\mathbf y_i-\mathbf y_j)=4\sum_j\big(p_{ij}-q_{ij}\big)\,w_{ij}\,(\mathbf y_i-\mathbf y_j)

    Differentiate with ∂wij/∂yi=−2wij2(yi−yj)\partial w_{ij}/\partial\mathbf y_i=-2w_{ij}^2(\mathbf y_i-\mathbf y_j); each pair appears twice in the sums, and ∂log⁡Z/∂yi\partial\log Z/\partial\mathbf y_i brings in qij=wij/Zq_{ij}=w_{ij}/Z:

  3. wij=(1+∥yi−yj∥2)−1≈∥yi−yj∥−2(∥yi−yj∥≫1)w_{ij}=\big(1+\norm{\mathbf y_i-\mathbf y_j}^2\big)^{-1}\approx\norm{\mathbf y_i-\mathbf y_j}^{-2}\qquad(\norm{\mathbf y_i-\mathbf y_j}\gg1)

    The first sum pulls each point toward its input neighbors, the second pushes every point away from every other, normalized by ZZ. Exact evaluation costs O(n2)\order{n^2} per iteration; Barnes–Hut trees reduce it to O(nlog⁡n)\order{n\log n} (van der Maaten, 2014), and FFT-accelerated interpolation on a grid is faster still (Linderman et al., 2019). For distant pairs the kernel decays like an inverse square law:

The crowding problem. In high dimension a point can have many neighbors at about the same distance that are also far from each other; in the plane, at most six points can sit at distance 1 from a center while staying at least 1 apart from one another. A Gaussian map kernel must then squeeze moderately distant points into a crowded ring. The Student-t tail lets them sit much farther away at little cost, which separates clusters cleanly, and is also why the gaps between clusters in a t-SNE map are exaggerated and not to scale.

Optimization. The cost is nonconvex. Implementations start from a small random or, better, PCA initialization and use momentum and early exaggeration: for the first iterations every pijp_{ij} is multiplied by α>1\alpha>1 (4 in the original paper; 12, for the first 250 iterations, in scikit-learn), which strengthens attraction while clusters form.

UMAP, and what neighbor embeddings really optimize

UMAP (McInnes, Healy & Melville, 2018) starts from a kk-nearest-neighbor graph. For each point it sets ρi\rho_i, the distance to its nearest neighbor, and a scale σi\sigma_i solving ∑j=1kexp⁡(−max⁡(0,dij−ρi)/σi)=log⁡2k\sum_{j=1}^k\exp\big(-\max(0,d_{ij}-\rho_i)/\sigma_i\big)=\log_2k, so that every point connects to its nearest neighbor with weight 1 and to the rest with locally normalized weights AijA_{ij}. A fuzzy union symmetrizes them, B=A+A⊤−A∘A⊤B=A+A^\top-A\circ A^\top: the probability that at least one of the two directed edges exists. Map similarities are vij=(1+a∥yi−yj∥2b)−1v_{ij}=\big(1+a\norm{\mathbf y_i-\mathbf y_j}^{2b}\big)^{-1}, with a,ba,b fitted to a min_dist parameter, and the layout minimizes a cross-entropy between μij=Bij\mu_{ij}=B_{ij} and vijv_{ij}:

CUMAP=∑i<j[μijlog⁡μijvij+(1−μij)log⁡1−μij1−vij]\mathcal C_{\text{UMAP}}=\sum_{i<j}\Big[\mu_{ij}\log\frac{\mu_{ij}}{v_{ij}}+(1-\mu_{ij})\log\frac{1-\mu_{ij}}{1-v_{ij}}\Big]
The first term attracts graph neighbors and the second repels everyone else. Optimization is stochastic: edges are sampled in proportion to μij\mu_{ij} and pulled together, and a few random points per edge are pushed away (negative sampling), so an epoch costs about O(nk)\order{nk}. The default initialization is a spectral layout, the Laplacian eigenmap of the graph.

Three analyses changed how UMAP is understood:

  • Its true loss. Damrich & Hamprecht (2021) derived in closed form the loss that the sampling scheme actually minimizes. It differs from the stated cross-entropy, and the layout ends up reproducing little more than the shared kk-nearest-neighbor graph rather than the fine weights μij\mu_{ij}; the balance of attraction and repulsion created by negative sampling is what makes it work.
  • The attraction–repulsion spectrum. Böhm, Berens & Kobak (2022) showed that raising t-SNE's exaggeration moves its output toward UMAP, then toward the force-directed layout ForceAtlas2, with Laplacian eigenmaps at the extreme. More attraction shows continuous manifolds better; more repulsion separates discrete clusters and keeps more true neighbors. UMAP behaves like t-SNE with extra attraction.
  • Initialization. Kobak & Linderman (2021) showed that UMAP's reputation for better global structure comes largely from its spectral initialization: t-SNE started from PCA keeps comparable global structure, and either method started at random loses it.
Check your understanding

You keep t-SNE's exaggeration at α=4\alpha=4 for the whole run instead of switching it off after the early phase. What change should you expect?

  1. None: exaggeration only matters during the first iterations
  2. More attraction: continuous structures look more connected and compact, as in UMAP, while fewer of each point's true nearest neighbors are kept
  3. More repulsion: clusters fragment into smaller islands and nearest-neighbor recall rises
  4. The map converges to the PCA projection
Show the answer

B. More attraction: continuous structures look more connected and compact, as in UMAP, while fewer of each point's true nearest neighbors are kept

Exaggeration multiplies the attractive term relative to the repulsive one. Along the attraction–repulsion spectrum, more attraction moves t-SNE toward UMAP-like and then Laplacian-eigenmap-like layouts: better continuity, worse fine-grained neighbor preservation.

python
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE, trustworthiness
import umap  # the umap-learn package

X50 = PCA(n_components=50).fit_transform(X)   # denoise and speed up first
Y_tsne = TSNE(perplexity=30, init="pca", random_state=0).fit_transform(X50)
Y_umap = umap.UMAP(n_neighbors=15, min_dist=0.1, random_state=0).fit_transform(X50)

# trustworthiness is 1 when every neighbor in the map is also a neighbor in X50
for name, Y in [("t-SNE", Y_tsne), ("UMAP", Y_umap)]:
    print(name, trustworthiness(X50, Y, n_neighbors=10))

Run each method with several seeds and neighborhood sizes, and score the maps instead of judging them by eye: trustworthiness (Venna & Kaski, 2001) penalizes false neighbors in the map, and the fraction of true kk nearest neighbors kept (kNN recall) penalizes lost ones.

What is proved, and how embeddings mislead

A sketch of the mechanism, following Linderman & Steinerberger: while all map points are close together, every wij≈1w_{ij}\approx1 and the exaggerated attraction dominates the repulsion, so one gradient step is approximately y←(I−c αh LP) y\mathbf y\leftarrow(I-c\,\alpha h\,L_P)\,\mathbf y for each map coordinate, where LPL_P is the graph Laplacian of the affinities and cc a constant. Repeating it is power iteration: it damps every component of y\mathbf y except those along the Laplacian's bottom eigenvectors, which are the cluster indicators when no affinity crosses between clusters, and close to them when the clusters are well separated. So t-SNE's early phase acts like a spectral clustering method (see Spectral Clustering), and the number of separate blobs it produces is a lower bound on the number of clusters. Arora, Hu & Kothari (2018) proved related guarantees under a deterministic well-separation condition that holds, for example, for mixtures of well-separated log-concave distributions, and partial recovery when it fails. Beyond well-separated clusters, little is proved.

How much a 2-D map can be trusted is contested. Chari & Pachter (2023) argued that embeddings of single-cell data distort high-dimensional structure so much that they are counterproductive, noting that their own autoencoder could arrange cells into an elephant while preserving distance correlations about as well as t-SNE and UMAP. Lause, Berens & Kobak (2024) replied that distance-based scores unsurprisingly favor PCA, and that on neighborhood and class measures (kNN accuracy and recall, silhouette) t-SNE and UMAP clearly beat both PCA and the elephant, although they too keep fewer than 40% of true nearest neighbors. Both sides agree that the maps distort distances and should not be used for quantitative analysis; they differ on their value for exploration.

Key takeaways

  • Classical MDS recovers coordinates from distances by double centering, B=−12HD(2)HB=-\frac12HD^{(2)}H, and equals PCA on Euclidean distances; Isomap, LLE and Laplacian eigenmaps feed graph-based distances or weights into eigenproblems with global optima.
  • t-SNE matches Gaussian neighbor probabilities, with bandwidths set by the perplexity, to Student-t similarities by minimizing DKL(P ∥ Q)\KL(P\,\|\,Q). Its gradient 4∑j(pij−qij)wij(yi−yj)4\sum_j(p_{ij}-q_{ij})w_{ij}(\mathbf y_i-\mathbf y_j) is attraction between input neighbors minus normalized repulsion among all points.
  • UMAP builds a fuzzy kk-nearest-neighbor graph and optimizes a cross-entropy by edge and negative sampling. In effect it is t-SNE with more attraction, and much of its global-structure advantage comes from spectral initialization.
  • Early exaggeration provably contracts well-separated clusters, acting like spectral clustering. Beyond that, sizes, gaps and global layout are not faithful: score maps with trustworthiness and kNN recall, and validate conclusions in the original space.

Check yourself

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

Question 1

Classical MDS is applied to the Euclidean distances between the rows of a data matrix and keeps mm dimensions. What does it return?

  1. The original coordinates exactly
  2. The top-mm PCA scores, up to rotation and sign
  3. Isomap's embedding, since both use eigenvectors
  4. Coordinates that preserve only nearest-neighbor distances
Show the answer

B. The top-mm PCA scores, up to rotation and sign

Double centering turns squared Euclidean distances into the Gram matrix X~X~⊤\tilde X\tilde X^\top of the centered data, and its top eigenvectors scaled by λ\sqrt{\lambda} are exactly the PCA scores UmΣmU_m\Sigma_m. The distances determine the points only up to a rigid motion, so a rotation or reflection is unavoidable.

Question 2

Why does t-SNE use a Gaussian kernel in the input space but a heavy-tailed Student-t kernel in the map?

  1. So that moderately distant points can be placed far apart in two dimensions, relieving the crowding problem
  2. Because input distances follow a Gaussian distribution and map distances a Student-t distribution
  3. To preserve global distances between clusters faithfully
  4. Only because the Student-t kernel is cheaper to evaluate
Show the answer

A. So that moderately distant points can be placed far apart in two dimensions, relieving the crowding problem

Two dimensions have too little room for all the moderately distant neighbors a point can have in high dimension. The t-kernel's polynomial tail charges little for pushing such points farther away, which keeps true neighbors together and separates clusters, at the price of gaps that are not to scale.

Question 3

You rerun t-SNE on the same data with the perplexity raised from 5 to 50. What changes?

  1. The embedding gains more output dimensions
  2. The optimizer runs ten times as many iterations
  3. Every cluster is drawn with the same size
  4. Each point's Gaussian widens until it has about 50 effective neighbors, so the map reflects coarser structure and small spurious clumps tend to merge
Show the answer

D. Each point's Gaussian widens until it has about 50 effective neighbors, so the map reflects coarser structure and small spurious clumps tend to merge

Perplexity 2H(Pi)2^{H(P_i)} fixes each point's effective number of neighbors, and the bandwidth σi\sigma_i is tuned to match it. A larger perplexity makes the affinities reflect larger neighborhoods, which reveals coarser structure and suppresses clumps that small neighborhoods carve out of noise.

Question 4

A UMAP plot keeps three groups in the same arrangement as their true geometry, while a t-SNE plot of the same data with random initialization scrambles them. According to Kobak & Linderman (2021), what explains most of the difference?

  1. UMAP's topological foundations, which preserve global distances
  2. t-SNE's Student-t kernel, which cannot represent global structure
  3. The initialization: UMAP starts from a spectral layout, and t-SNE started from PCA keeps comparable global structure
  4. The number of iterations, which is larger for UMAP
Show the answer

C. The initialization: UMAP starts from a spectral layout, and t-SNE started from PCA keeps comparable global structure

Both methods mostly optimize local neighborhoods, and their losses barely constrain the relative placement of distant groups, which is inherited from the starting layout. Informative initializations (PCA for t-SNE, spectral for UMAP) carry global structure into the final map; random ones do not.

Further reading

  • J. B. Tenenbaum, V. de Silva & J. C. Langford, "A global geometric framework for nonlinear dimensionality reduction," Science 290(5500), 2319–2323 (2000).
  • M. Belkin & P. Niyogi, "Laplacian eigenmaps for dimensionality reduction and data representation," Neural Computation 15(6), 1373–1396 (2003).
  • L. van der Maaten & G. Hinton, "Visualizing data using t-SNE," Journal of Machine Learning Research 9, 2579–2605 (2008).
  • L. McInnes, J. Healy & J. Melville, "UMAP: Uniform manifold approximation and projection for dimension reduction," arXiv:1802.03426 (2018).
  • G. C. Linderman & S. Steinerberger, "Clustering with t-SNE, provably," SIAM Journal on Mathematics of Data Science 1(2), 313–332 (2019).