Back to Tutorials
Machine Learning
Intermediate

t-SNE and UMAP: Maps of High-Dimensional Data

Run t-SNE live on 500 handwritten digits, then feed it data with a known shape and see which parts of the map you can trust.

10 minInteractive: drag, click and try things as you read


Embeddings, images, customer records: most of the data AI works with describes each item with hundreds of numbers, and nobody can picture 384 dimensions. t-SNE and UMAP draw it as a flat map where similar items sit together, so you can see the groups and the odd ones out. These maps keep who sits near whom and give up almost everything else, so cluster sizes and the gaps between them can be made up by the method. Here you’ll run t-SNE on 500 handwritten digits, then feed it data whose true shape you know, and see what the map gets wrong.

Too many numbers to look at#

Each digit below is a tiny 8 × 8 pixel image: 64 numbers, one per pixel, from 0 (blank) to 16 (full ink). Two images count as similar when their 64 numbers are close. To see the whole collection at once you need to squash those 64 numbers down to two, an x and a y, while keeping similar images together.

The straightforward way is PCA: find the two directions in which the data spreads the most and project everything onto them, like a shadow on a wall. It’s honest and repeatable, and it keeps the broad layout. But a shadow can stack things that are really far apart on top of each other.

Predict first

You lay the 500 digits flat with PCA. For each image, look at the image drawn closest to it on the map. How often is it the same digit?

Try it
500 handwritten digits, 50 of each, from a public dataset that ships with scikit-learn. PCA and t-SNE run in your browser; the UMAP layouts were computed in advance with the umap-learn library. Each image is drawn as the digit it shows. Tap any digit to ring its 10 closest images, measured on all 64 pixels.

On the PCA map, only 64% of images sit closest to the same digit, and of each image’s 10 closest images, only 29% are still among its 10 closest on the map. Switch to t-SNE and watch: the points start in a tiny clump, bunch into groups, then spread into ten islands. Now about 99% of images sit next to the same digit and about 71% of their true neighbours stay neighbours. UMAP draws a similar picture, at 99% and 66%.

Nobody told either method which digit is which. The labels only colour the result. The islands appear because 2s really do resemble other 2s more than they resemble 7s.

How t-SNE decides where things go#

t-SNE stands for t-distributed stochastic neighbour embedding, from a 2008 paper by Laurens van der Maaten and Geoffrey Hinton. It works in three steps.

  1. Who are each point’s neighbours? In the original 64 dimensions, each point shares out 100% of its attention among the others: close points get a lot, far ones almost none, falling away like a bell curve. The bell’s width is set so that each point pays attention to roughly the same number of neighbours. That number is the perplexity.
  2. Who are its neighbours on the map? The same attention, computed from the map positions, but with a curve that has heavier tails: Student’s t, the “t” in t-SNE. This lets moderately distant points sit far apart on the map, which leaves room to spread the groups out.
  3. Move the points until the two agree. Step by step, with gradient descent, each point is pulled towards its true neighbours and pushed away from everything else. For the first 100 steps here the pull is exaggerated 12 times, which forms the clumps early. scikit-learn does this too, for its first 250 steps.

The mismatch t-SNE minimises punishes one mistake much more than the other. Putting true neighbours far apart costs a lot; putting distant points close together costs little. So the map is reliable about neighbourhoods and much less reliable about everything at a larger scale.

Perplexity: how many neighbours count#

Back in the figure, choose t-SNE and try each perplexity. At 2, each image cares about two neighbours, and the digits break into many small islands: the map still puts about 99% of images next to the same digit, but keeps under 60% of their 10 closest neighbours. At 30, scikit-learn’s default, you get ten clean islands. At 100, much the same. The original paper suggests values between 5 and 50, and scikit-learn’s documentation warns that different values can give significantly different results. So look at more than one.

UMAP’s equivalent setting is the number of neighbours, 15 by default. Try 5, 15 and 50 in the figure. The islands shift and change shape, but the digits stay apart.

What the map can’t tell you#

Real data never comes with an answer key, so make some that does. The next figure builds data in 20 dimensions with a shape fixed in advance, then draws it two ways: flat with PCA, which keeps sizes and distances roughly right for data like this, and with t-SNE.

Predict first

Two groups of 75 points: one tight, one 10 times as spread out. How big will they look on the t-SNE map?

Try it
Made-up data in 20 dimensions, generated in your browser: two groups of 75 points, or three groups of 50, or 150 points with no groups at all. Both maps are computed live. The status line measures sizes and gaps in the original 20 dimensions and on each map.

Sizes: in 20 dimensions the orange group is 10 times as spread out as the blue one. The flat projection shows 12.5 times. On the t-SNE map, at every perplexity from 2 to 50, the two come out nearly the same size: never even twice as wide.

Gaps: three groups in a line, with green 4 times as far from orange as blue is. At perplexity 2 to 30, t-SNE draws the three about equally far apart. At 50, a third of all the points, the gap comes back. That’s typical: with enough neighbours in view the map can show the bigger picture, but you only know which setting is right here because you built the data.

No groups: 150 points from a single round cloud. At perplexity 2, t-SNE breaks them into little clumps that look like structure. There is none.

These three are lessons from Martin Wattenberg, Fernanda Viégas and Ian Johnson’s 2016 article “How to Use t-SNE Effectively”, which says plainly that cluster sizes in a t-SNE plot mean nothing, and that distances between well-separated clusters may mean nothing either. UMAP has the same habits: run on data built the same way, it also drew the tight and wide groups at about the same size and lost the 4-times gap, at 5, 15 and 50 neighbours.

t-SNE or UMAP?#

UMAP (uniform manifold approximation and projection) came out in 2018, from Leland McInnes, John Healy and James Melville. It follows the same plan as t-SNE: work out each point’s neighbours, then arrange a map that keeps them close. The maths differs. It’s usually faster on large datasets, it can place new points on an existing map, and it has a second setting, min_dist (0.1 by default), for how tightly points may pack.

UMAP is often said to keep more of the big picture. Dmitry Kobak and George Linderman tested that in 2021 and found the difference came mostly from the starting layout: UMAP starts from a sensible layout, while many t-SNE tools started from random positions. Given the same start, they found UMAP kept the global structure no better than t-SNE. scikit-learn’s t-SNE has started from a PCA layout by default since version 1.2, and so does the one in this page.

How to read these maps safely#

  • Trust neighbourhoods, not distances. Points drawn close together are probably similar. Points drawn far apart might be fairly close in the original data.
  • Ignore cluster sizes and the gaps between clusters. As you saw, the method makes them up.
  • Try several settings. A group that appears at several perplexities, or several neighbour counts, is more likely to be real.
  • Colour by something you already know. Labels, dates, sources. The map then shows whether your embedding separates them, and a lone point in the wrong group is worth a look: maybe it’s mislabelled.
  • Measure in the original space. To find clusters, run k-means or similar on the original numbers, not on the map’s x and y. Use the map to ask questions and the numbers to answer them.

In code#

Both methods on the full digits dataset, with scikit-learn and umap-learn (pip install scikit-learn umap-learn). Trustworthiness is a standard score from 0 to 1 for how well a map avoids putting faraway points next to each other:

from sklearn.datasets import load_digits
from sklearn.manifold import TSNE, trustworthiness
import umap

X, y = load_digits(return_X_y=True)           # 1,797 images, 64 pixels each
tsne_map = TSNE(perplexity=30, random_state=0).fit_transform(X)
umap_map = umap.UMAP(n_neighbors=15, min_dist=0.1, random_state=0, n_jobs=1).fit_transform(X)

for name, flat in [("t-SNE", tsne_map), ("UMAP", umap_map)]:
    score = trustworthiness(X, flat, n_neighbors=10)
    print(f"{name}: {flat.shape}, trustworthiness {score:.3f}")
# t-SNE: (1797, 2), trustworthiness 0.993
# UMAP: (1797, 2), trustworthiness 0.989

To draw either map, plt.scatter(flat[:, 0], flat[:, 1], c=y, s=4) with matplotlib. For tens of thousands of points, reach for UMAP or the openTSNE library, both built to stay fast at that size.

What to remember

  • t-SNE and UMAP flatten many numbers into a 2-D map by keeping each point’s nearest neighbours close.
  • Neighbourhoods on the map are meaningful; cluster sizes, gaps between clusters and clumps at low perplexity may not be.
  • Try several settings, colour by what you know, and confirm anything important in the original data.

Keep going

Sign in to save your place and keep a learning streak. Free, with Google.