t-SNE and UMAP for visualisation
Non-linear maps that keep neighbourhoods: how t-SNE works and how to read its pictures safely.
Animated explanation
The idea
PCA keeps large-scale variance but squashes curved structure. To see clusters in high-dimensional data (single-cell genomics, word embeddings, images), we want a 2-D map in which points that are neighbours in the original space remain neighbours.
t-SNE turns distances into probabilities of being neighbours in the original space, does the same in the 2-D map with a heavy-tailed kernel, and moves the map points until the two sets of probabilities match. Local structure is preserved beautifully. Global structure (distances between clusters, cluster sizes) is not, and the result changes with the perplexity and the random seed.
UMAP builds a fuzzy neighbour graph and optimises a similar objective faster, and tends to keep a little more global structure.
Reading t-SNE plots honestly
- Cluster sizes mean little: t-SNE expands dense clusters and contracts sparse ones.
- Distances between clusters mean little: far apart in the map is not "very different".
- Perplexity matters: try several values (5, 30, 50); real structure persists.
- Random noise can look clustered at low perplexity.
- It is for visualisation, not a feature extractor for downstream models (no stable transform for new points).
Practical recipe
Reduce to ~50 dimensions with PCA first (speed, noise), run t-SNE with perplexity 30, 1,000+ iterations, PCA initialisation, and several seeds. Barnes–Hut or FFT approximations make it . For millions of points or for a reusable transform, prefer UMAP.
The algorithm, step by step
- 1Compute pairwise affinities with a Gaussian whose width gives each point the chosen perplexity; symmetrise to .
- 2Initialise map points (small random or PCA).
- 3Repeat: compute Student-t affinities in the map; move points along with momentum.
- 4Use early exaggeration (multiply P by ~12) for the first iterations to form clusters.
The maths
High-dimensional affinities
Map affinities
Cost
Perplexity
Strengths and weaknesses
Strengths
- Reveals cluster structure in very high-dimensional data
- Captures non-linear manifolds
- Widely used; great for exploration
Weaknesses
- Distances and sizes between clusters are not meaningful
- Stochastic; sensitive to perplexity
- No out-of-sample transform; O(n²) without approximations
Reach for it when…
Check your understanding
Lambdian Lab
A tiny t-SNE
Implement exact t-SNE with a fixed Gaussian width (no perplexity search, to keep it short).
- joint_p(X, sigma): conditional Gaussian probabilities per row (zero diagonal), symmetrised and divided by 2n.
- joint_q(Y): Student-t affinities normalised over all pairs (zero diagonal).
- kl(P, Q): (skip zero p).
- gradient(P, Y): the t-SNE gradient.
- tsne(X, sigma, iters, lr, seed): gradient descent with momentum 0.8 from Y ~ N(0, 1e-4); return (Y, kl_history).