Level 3 In-Depth AI · Classical Machine Learning
t-SNE and UMAP
Nonlinear methods that draw high-dimensional data, such as embeddings, as a 2D map in which similar items end up near each other. Wonderful for exploring data, and easy to misread.
- Level
- ●●●●● Intermediate
- Reading
- 12 min
- To learn it well
- 45 minutes to read, an hour to practise
- Builds on
- 8 concepts →
- Quiz
- 5 questions ↓
Read first
PCA and Dimensionality ReductionThis leads to
—The full path from zero — 8 concepts before this one
- What Is AI?
- Vectors
- How Machines Learn
- Matrices and Matrix Multiplication
- Supervised, Unsupervised and Reinforcement Learning
- Eigenvectors and SVD
- Unsupervised Learning
- PCA and Dimensionality Reduction
- t-SNE and UMAP
Read them roughly in this order. See it on the concept map →
Why it matters
Modern AI turns everything into long vectors. A sentence becomes a 384- or 1,536-number embedding; an image passed through a Convolutional Neural Networks becomes 2,048 numbers; a single cell in a biology experiment is described by the activity of 20,000 genes. You can't look at a 1,536-dimensional space. But you badly want to: are there groups? Outliers? Did the model put similar things together? Are some labels wrong?
PCA and Dimensionality Reduction can squash the data to two dimensions, but it only rotates and drops axes. When the structure is curved or tangled, PCA piles different groups on top of each other. t-SNE and UMAP are nonlinear methods built for one job: draw a 2D (or 3D) map in which points that are neighbours in the original space stay neighbours on the map. They are standard tools for:
- inspecting embeddings from language and vision models;
- single-cell biology, where UMAP plots of cell types appear in thousands of papers;
- debugging datasets: spotting mislabelled examples, duplicates and unexpected clusters;
- presenting high-dimensional results in a picture.
They are also among the most misread figures in science. This chapter shows how they work so you know what their pictures can and cannot tell you.
The intuition
Imagine trying to draw a map of friendships in a school of a thousand pupils. You don't care about exact "distances" between people, only that friends are drawn close together. A good map puts each friend group in its own huddle. It doesn't matter much whether the chess club ends up to the left or the right of the football team, or how far apart they are, so long as each group stays together.
t-SNE and UMAP make maps like that. For each point they work out who its close neighbours are in the original high-dimensional space. Then they place the points in 2D and shuffle them around until each point's neighbours on the map match its neighbours in the original space as well as possible.
The cost of this focus on neighbours is that the large-scale layout is not faithful. Distances between islands, the sizes of islands and their positions are partly arbitrary.
Key idea t-SNE and UMAP place points in 2D so that each point's nearest neighbours stay nearby. Trust the local structure: which points cluster together. Distrust the global structure: cluster sizes, gaps between clusters and where they sit on the page.
How it works
t-SNE in three steps
t-SNE stands for t-distributed stochastic neighbour embedding.
Step 1: neighbour probabilities in the original space. For each point , turn distances to every other point into probabilities with a Gaussian (bell-curve) kernel. Close points get high probability, far points almost none:
Read as "the probability that would pick as its neighbour". The width ("sigma i") is set separately for every point so that each has about the same effective number of neighbours. That number is the perplexity, which you choose. It is defined as , where is the entropy of the point's neighbour probabilities. Dense regions get a narrow bell, sparse regions a wide one. The two directions are then averaged into one symmetric similarity .
Step 2: neighbour probabilities on the map. Place every point at some position in 2D (start from random or PCA positions). Compute similarities on the map the same way, but with a Student-t kernel instead of a Gaussian:
Step 3: make the two match. Move the map points by Gradient Descent to minimise the KL divergence (see Entropy, Cross-Entropy and KL Divergence) between the two sets of probabilities:
This loss punishes heavily when two points are close in the original space (large ) but far apart on the map (small ). It barely cares when far-apart points end up close. That asymmetry is exactly why t-SNE preserves local structure and not global structure.
Why a heavy-tailed kernel?
In high dimensions there is much more "room" at moderate distances than in 2D. A point in 50 dimensions can have dozens of neighbours all at roughly the same distance; in 2D you can't fit them all at that distance. This is called the crowding problem: squeeze everything into 2D with the same kernel and the clusters smear together in the middle.
The Student-t curve has a heavy tail: it decays slowly. To represent a small original similarity, the map has to push the two points much further apart than they were. Moderately dissimilar points get flung apart, and clusters separate cleanly. This one change, from the Gaussian of the earlier SNE method to Student-t, is the "t" in t-SNE.
A worked example by hand
Point has three neighbours at distances 1, 2 and 3.
With : the Gaussian weights are 0.607, 0.135 and 0.011. Divide by their sum (0.753) to get probabilities 0.806, 0.180 and 0.015. The entropy is bits, so the perplexity is : effectively, point has under two neighbours. The nearest one dominates.
With : weights are 0.882, 0.607 and 0.325, giving probabilities 0.487, 0.334, 0.179 and perplexity . All three neighbours now count.
t-SNE searches for the that hits the perplexity you asked for, separately for every point. On the map, the Student-t weights for distances 1, 2, 3 would be 0.5, 0.2 and 0.1, which normalise to 0.625, 0.25 and 0.125.
Perplexity: the knob that matters
Perplexity is roughly "how many neighbours each point should care about". Typical values are 5 to 50; scikit-learn's default is 30. It must be smaller than the number of points.
Small perplexities emphasise very local structure and can invent clumps in what is really one smooth cluster. Large perplexities preserve more global structure but blur fine detail and run slower. Always try a few.
UMAP
UMAP (uniform manifold approximation and projection) was published in 2018 and is now used at least as often as t-SNE. The recipe is similar in spirit:
- Build a nearest-neighbour graph in the original space: connect each point to its
n_neighborsclosest points (default 15), with edge weights that fall off with distance, scaled per point so each sees its local neighbourhood at a similar scale. - Lay the graph out in 2D, pulling connected points together and pushing a random sample of unconnected points apart, by stochastic gradient descent on a cross-entropy loss.
Its theoretical grounding comes from topology. It assumes the data lies on a manifold: a lower-dimensional surface, possibly curved, inside the high-dimensional space, like a crumpled sheet of paper in a room. In practice UMAP differs from t-SNE in ways that matter:
- Speed. UMAP is usually much faster on large datasets and scales to millions of points.
- Global structure. UMAP tends to keep somewhat more of the large-scale arrangement, though it is still not reliable for distances between clusters.
- Reusable. A fitted UMAP can
transformnew points onto an existing map. Standard t-SNE cannot. - Any number of output dimensions. UMAP works well for reducing to, say, 10 dimensions as input to clustering. t-SNE is really only for 2D or 3D pictures.
- Knobs.
n_neighborsplays the role of perplexity (local versus global).min_dist(default 0.1) controls how tightly points may pack: small values give tight clumps, large values an even spread.
Measuring how faithful a map is
Trustworthiness asks: of each point's nearest neighbours on the map, how many were genuinely near it in the original space? A score of 1 means no map neighbour is an impostor. In the code below, t-SNE scores 0.993 on the digits and PCA 0.830.
In code
t-SNE versus PCA on the digits, in scikit-learn. We check how well each 2D map keeps neighbours, and how well a simple classifier can tell digits apart using only the two map coordinates:
import time
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE, trustworthiness
from sklearn.model_selection import cross_val_score
from sklearn.neighbors import KNeighborsClassifier
X, y = load_digits(return_X_y=True) # 1,797 images, 64 pixels each
t = time.perf_counter()
emb_tsne = TSNE(n_components=2, perplexity=30, init="pca", random_state=0).fit_transform(X)
print(f"t-SNE took {time.perf_counter() - t:.1f} s")
emb_pca = PCA(n_components=2).fit_transform(X)
for name, E in [("PCA ", emb_pca), ("t-SNE", emb_tsne)]:
trust = trustworthiness(X, E, n_neighbors=10) # are 2D neighbours also true neighbours? (1 = perfect)
knn = cross_val_score(KNeighborsClassifier(5), E, y, cv=5).mean()
print(f"{name} trustworthiness {trust:.3f} 5-NN accuracy in 2D {knn:.3f}")
# t-SNE took 4.4 s (on a laptop CPU; your time will differ)
# PCA trustworthiness 0.830 5-NN accuracy in 2D 0.603
# t-SNE trustworthiness 0.993 5-NN accuracy in 2D 0.976
Plot emb_tsne with plt.scatter(*emb_tsne.T, c=y, s=3, cmap="tab10") to get the right-hand picture in the first figure. init="pca" gives more stable layouts than a random start. For data with hundreds of dimensions, reduce to about 50 with PCA first; it is faster and removes noise.
UMAP lives in the separate umap-learn package. It isn't run here, but the API follows scikit-learn's conventions:
import umap # pip install umap-learn
reducer = umap.UMAP(n_neighbors=15, min_dist=0.1, n_components=2, random_state=42)
embedding = reducer.fit_transform(X) # shape (n_samples, 2)
new_points_2d = reducer.transform(X_new) # place new data on the same map
Common pitfalls
Most of these come from the Distill article How to Use t-SNE Effectively, which is well worth ten minutes.
- Reading cluster sizes. t-SNE expands dense clusters and contracts sparse ones. Two islands of equal size on the map can be very different in spread in the original space.
- Reading distances between clusters. Gaps between islands carry little meaning, and they change with perplexity and random seed. "Cluster A is closer to B than to C" is not a safe conclusion from a t-SNE plot, and only somewhat safer from UMAP.
- Seeing clusters in noise. At low perplexity, t-SNE can draw convincing clumps in random data. Check that clusters survive different perplexities and seeds.
- Using one run. Results vary with the random seed. Run several and see what is stable.
- Treating the axes as meaningful. The x and y coordinates have no units or interpretation. Rotating or flipping a map changes nothing.
- Feeding the 2D coordinates to a model. Clustering on a t-SNE map is risky: the map has distorted densities. Cluster in the original space or on a moderate-dimensional UMAP or PCA output instead.
- Forgetting preprocessing. Scaling and the distance metric decide what "neighbour" means. For text embeddings, cosine distance is usually right (
metric="cosine").
Watch out A t-SNE or UMAP plot shows which points are neighbours. It does not faithfully show how big clusters are, how far apart they are, or whether a cluster really exists. Never draw conclusions from those features without checking them in the original space.
Where it leads
- Embedding exploration. Tools such as TensorBoard's Embedding Projector let you fly around t-SNE and UMAP maps of Word Embeddings and Sentence Embeddings.
- Clustering pipelines. A common recipe for grouping documents is: embed with a language model, reduce to 5–10 dimensions with UMAP, cluster with HDBSCAN (see k-Means Clustering), then label each cluster with an LLM.
- Autoencoders learn nonlinear low-dimensional codes that, unlike t-SNE, come with a decoder back to the original space. See Autoencoders.
- Anomaly spotting. Isolated points on a map are worth inspecting, though confirm with a proper method. See Anomaly Detection.
A bit of history
Geoffrey Hinton and Sam Roweis introduced stochastic neighbour embedding (SNE) in 2002. Laurens van der Maaten and Hinton fixed its crowding problem with the Student-t kernel and a symmetric cost, publishing t-SNE in 2008. Van der Maaten's 2014 Barnes–Hut approximation cut the cost from quadratic in the number of points to roughly , making t-SNE practical for tens of thousands of points; it is what scikit-learn uses by default. Leland McInnes, John Healy and James Melville published UMAP in 2018. It spread rapidly, especially in single-cell genomics, where it became the standard way to draw cell atlases. Earlier nonlinear methods, such as Isomap and locally linear embedding (both 2000), paved the way by showing that data often lies on curved, lower-dimensional manifolds.
Try it
- Recompute the hand example with . What is the perplexity? What happens to it as grows very large?
- Run the t-SNE code with perplexity 5, 30 and 200 and plot each. Which digits split into several islands at low perplexity?
- Harder: run t-SNE on 1,000 points of pure Gaussian noise in 10 dimensions (
np.random.randn(1000, 10)) with perplexity 2 and 30. Do you see "clusters"? What does that tell you?Hint for 1: with very large every neighbour gets nearly equal weight, so the perplexity approaches the number of neighbours, 3.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
How to Use t-SNE Effectively
Interactive demonstrations of how perplexity and randomness change t-SNE plots, and how to avoid misreading them.
StatQuest
Short, cheerful, very clear videos on statistics and nearly every ML algorithm.
Visualizing Data using t-SNE
The original t-SNE paper.
UMAP: Uniform Manifold Approximation and Projection for Dimension Reduction
The UMAP paper: a faster nonlinear embedding grounded in topology.
UMAP documentation
How to use the umap-learn library, how UMAP works, and how to tune n_neighbors and min_dist.
scikit-learn: Manifold Learning
t-SNE, Isomap, locally linear embedding and other nonlinear maps, with practical tips for t-SNE.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/ml/tsne-umap.md