◆ AI All-in-One

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
↗ Plan a path here

Read first

PCA and Dimensionality Reduction

This leads to

—
The full path from zero — 8 concepts before this one
  1. What Is AI?
  2. Vectors
  3. How Machines Learn
  4. Matrices and Matrix Multiplication
  5. Supervised, Unsupervised and Reinforcement Learning
  6. Eigenvectors and SVD
  7. Unsupervised Learning
  8. PCA and Dimensionality Reduction
  9. 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.

0 1 2 3 4 5 6 7 8 9 PCA to 2D linear: digits pile on top of each other 0 1 2 3 4 5 6 7 8 9 t-SNE to 2D nonlinear: each digit gets its own island 1,797 handwritten digits, 64 pixels each; colour and number = true digit (never shown to either method)
Fig. 1 The same 1,797 handwritten digits (64 pixels each) mapped to 2D by PCA and by t-SNE. Neither method saw the labels. PCA's straight-line projection piles most digits on top of each other. t-SNE gives each digit its own island, because it only tries to keep neighbours together.

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 xi\mathbf{x}_i, turn distances to every other point into probabilities with a Gaussian (bell-curve) kernel. Close points get high probability, far points almost none:

pj∣i=exp⁡ ⁣(−∥xi−xj∥2/2σi2)∑k≠iexp⁡ ⁣(−∥xi−xk∥2/2σi2)p_{j \mid i} = \frac{\exp\!\left(-\lVert \mathbf{x}_i - \mathbf{x}_j \rVert^2 / 2\sigma_i^2\right)}{\sum_{k \ne i} \exp\!\left(-\lVert \mathbf{x}_i - \mathbf{x}_k \rVert^2 / 2\sigma_i^2\right)}

Read pj∣ip_{j \mid i} as "the probability that ii would pick jj as its neighbour". The width σi\sigma_i ("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 2H2^{H}, where HH 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 pijp_{ij}.

Step 2: neighbour probabilities on the map. Place every point at some position yi\mathbf{y}_i 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:

qij=(1+∥yi−yj∥2)−1∑k≠l(1+∥yk−yl∥2)−1q_{ij} = \frac{\left(1 + \lVert \mathbf{y}_i - \mathbf{y}_j \rVert^2\right)^{-1}}{\sum_{k \ne l} \left(1 + \lVert \mathbf{y}_k - \mathbf{y}_l \rVert^2\right)^{-1}}

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:

KL(P ∥ Q)=∑i≠jpijlog⁡pijqij\text{KL}(P \,\Vert\, Q) = \sum_{i \ne j} p_{ij} \log \frac{p_{ij}}{q_{ij}}

This loss punishes heavily when two points are close in the original space (large pijp_{ij}) but far apart on the map (small qijq_{ij}). 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.

0 1 2 3 4 5 0 0.5 1 distance between two points similarity Gaussian used in the original space exp(−d²/2) at d = 3: 0.011 Student-t (heavy tail) used in the 2D map 1 / (1 + d²) at d = 3: 0.100 9× more similarity left in the tail heavy tails let moderately distant points sit far apart in 2D, giving clusters room to separate
Fig. 2 The Gaussian kernel used in the original space and the Student-t kernel used on the map. At distance 3, the Gaussian similarity has fallen to 0.011, but the Student-t similarity is still 0.100, about nine times more. To match a small similarity, the map must place points much further apart, which pulls clusters away from each other.

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 ii has three neighbours at distances 1, 2 and 3.

With σ=1\sigma = 1: the Gaussian weights exp⁡(−d2/2)\exp(-d^2/2) 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 H=−∑plog⁡2p=0.786H = -\sum p \log_2 p = 0.786 bits, so the perplexity is 20.786=1.722^{0.786} = 1.72: effectively, point ii has under two neighbours. The nearest one dominates.

With σ=2\sigma = 2: weights exp⁡(−d2/8)\exp(-d^2/8) are 0.882, 0.607 and 0.325, giving probabilities 0.487, 0.334, 0.179 and perplexity 21.478=2.792^{1.478} = 2.79. All three neighbours now count.

t-SNE searches for the σi\sigma_i 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.

the real data (first 2 of 10 dims) one wide, two tight; one far away t-SNE, perplexity 5 t-SNE, perplexity 30 t-SNE, perplexity 100 low perplexity shatters the wide cluster into fake fragments; cluster sizes and the gaps between clusters change with perplexity. In t-SNE plots, sizes and distances between clusters are not to be trusted.
Fig. 3 The same data, three blobs in 10 dimensions (one wide, two tight, one of the tight ones far from the others), mapped by t-SNE with three perplexities. With perplexity 5 the wide blob shatters into fake little clusters. At 30, all three blobs look about the same size and the far one isn't far. At 100 the large-scale layout is more faithful.

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:

  1. Build a nearest-neighbour graph in the original space: connect each point to its n_neighbors closest points (default 15), with edge weights that fall off with distance, scaled per point so each sees its local neighbourhood at a similar scale.
  2. 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 transform new 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_neighbors plays 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 kk 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 Nlog⁡NN \log N, 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

  1. Recompute the hand example with σ=0.5\sigma = 0.5. What is the perplexity? What happens to it as σ\sigma grows very large?
  2. Run the t-SNE code with perplexity 5, 30 and 200 and plot each. Which digits split into several islands at low perplexity?
  3. 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 σ\sigma every neighbour gets nearly equal weight, so the perplexity approaches the number of neighbours, 3.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. On a t-SNE map of embeddings, cluster A sits far from B and close to C. What can you safely conclude?

  2. At perplexity 5, a single wide blob splits into several small clusters on the t-SNE map. What is going on?

  3. You need to place new points onto an existing 2D map of millions of items. Which method fits best?

  4. Why does t-SNE use a heavy-tailed Student-t kernel on the map rather than a Gaussian?

  5. A t-SNE map has trustworthiness 0.993 and a PCA map has 0.830. What does that tell you?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Article

How to Use t-SNE Effectively

Wattenberg, Viégas & Johnson (Distill) · 2016 · Beginner · Free

Interactive demonstrations of how perplexity and randomness change t-SNE plots, and how to avoid misreading them.

Video

StatQuest

Josh Starmer · Beginner · Free

Short, cheerful, very clear videos on statistics and nearly every ML algorithm.

Docs

UMAP documentation

Leland McInnes · Intermediate · Free

How to use the umap-learn library, how UMAP works, and how to tune n_neighbors and min_dist.

Docs

scikit-learn: Manifold Learning

scikit-learn · Intermediate · Free

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