A small image (8×8 pixels) of a handwritten digit is 64 numbers. P3.C3 showed that PCA can squash those 64 numbers to 2 and draw a picture, but the picture of the digits is smeared: the first two components hold only about of the variance of the raw pixels (about after scaling), and the ten digits overlap. Another method, t-SNE, usually keeps neighbouring images together much better, as the scikit-learn run near the end of this lesson measures. That is tempting to believe, and it is where the danger starts. This lesson shows how t-SNE and its modern cousin UMAP make their maps, and, more important, what in the map you can trust and what you cannot.
When straight lines are not enough
PCA (P3.C3) casts a shadow of the data on a flat sheet. That works when the data are spread along straight directions. It fails when the data lie along a curve.
Picture a sheet of paper rolled up like a carpet: a Swiss roll. Each point on the paper has two coordinates (how far along the sheet, and how far across), but in 3-D the sheet is curled. The data in this lesson are made up: 200 points on such a roll. Neighbours on the paper are close in 3-D. But the roll has layers, and a point on one layer is also close in 3-D to the point directly above it on the next layer, though they are far apart on the paper. PCA’s shadow flattens the layers on top of each other. Its first two components keep only about of the variance, and the third direction matters too.
What we want is not a shadow but an unrolling: a flat map in which points that were neighbours stay neighbours. That is the idea behind neighbour-preserving embeddings. They do not try to keep the straight-line distances between all pairs. They try to keep each point’s nearby points nearby, bending and stretching the rest as needed. t-SNE and UMAP are the two most used.
The picture: one data set, many maps
The widget shows stored t-SNE runs on made-up data in 10 dimensions (so you cannot look at the data directly). In the Three clusters preset there are three true clusters, drawn with different shapes. A has 60 points and is tight, B has 50 and is medium, C has 40 and is spread out. In the Pure noise preset there is nothing to find: 150 points drawn independently, with no structure at all. The widget counts a “group” by a stated rule: 5 or more points linked by short gaps (the exact rule is printed under the map).
Things to try:
- Three clusters, perplexity 30. Three groups appear, as they should. Now read the table. The true spreads of A, B and C are in the ratio (scaled to average 1), but in the map they are : the tight cluster looks the biggest and the spread-out one the smallest. The true distances between the cluster centres are for A–B and about for the other two pairs, but the map draws all three nearly equal (, , ).
- Slide to perplexity 2. The three clusters shatter into small pieces. Slide up to and the gaps change again: now A–B is drawn at , close to the truth, and the other two at . The sizes stay wrong. The setting, not the data, decided which gaps looked right.
- Pure noise. At perplexity 2 the map shows separate groups, although the data contain none. At perplexity 5 it shows 3 or 4, and from 10 up it is a single blob.
- Run A or run B. The runs differ only in the random start. At a good perplexity the picture is similar, but its position, rotation and details change. Compare them before trusting any detail.
The rest of the lesson explains why this happens. The last section turns the results into rules.
Step 1: probabilities of being neighbours
t-SNE (van der Maaten and Hinton, 2008, Journal of Machine Learning Research) starts in the original space. For every point it asks: if I picked a neighbour of at random, how likely is it to be ? Near points should get a high probability and far points almost none. It uses a bell curve (a Gaussian, P1.D3) centred on :
The denominator makes the probabilities for point add up to . The width belongs to point .
A small example. Four made-up points on a line: A at , B at , C at , D at . From A the squared distances are , and . Take . The weights are for B, for C and for D. They add up to , so
A with essentially knows only B. Make larger and A listens to more neighbours. That is the role of the next idea.
Perplexity: how many neighbours to listen to
How wide should the bell curve be? In a dense region a few units is plenty; in a sparse region the nearest point may be far. t-SNE does not pick directly. You set one number for all points, the perplexity, and the method searches each point’s until that point’s distribution has that perplexity.
The perplexity of a probability distribution is , where is its entropy in bits (P1.E2). It is the effective number of neighbours: a distribution that is spread evenly over points has perplexity exactly , and a distribution with one dominant point has a perplexity near . For A with different widths:
- : , perplexity .
- : , perplexity .
- : , perplexity .
- : , perplexity .
- Very large : all three about , perplexity close to .
So perplexity rises smoothly with from to the number of other points, and a binary search finds the that gives the target. For a target of the four points get values of , , and . Isolated points (A and D) get wide curves, points in a crowd get narrow ones. This is why t-SNE copes with data of varying density, and why it later draws dense and sparse clusters at similar sizes.
The perplexity must be smaller than the number of points. The scikit-learn documentation suggests values between and and uses by default; larger data sets usually need a larger value.
Symmetrizing
and differ, because the two points have different . t-SNE averages them into one number per pair:
which makes and makes all the over all pairs add up to . The also guarantees that every point, even an outlier whom nobody lists as a neighbour, has some total pull , so no point is left to wander free. For the four points, , and the largest value is that one; A and D, which are far apart, get .
Step 2: similarities in the map
Now place the points at random in 2-D, at positions . We want the map’s similarities to match the . The map uses a different bell curve, the Student-t distribution with one degree of freedom (the same shape as a Cauchy distribution):
A Gaussian falls off like , which is extremely fast. This curve falls off like , which is slow: it has a heavy tail. Why use it in the map?
The crowding problem. In 10 dimensions a point can have many neighbours at a moderate distance, and still have room for them all, because high-dimensional space has far more room than a flat page. In 2-D there is not enough room around a point to place all its moderate-distance neighbours at the right distances: they get pushed together, and the map collapses into one crowded lump. With a heavy tail, a moderate distance in the original space can be drawn as a larger distance in the map without paying much in similarity, so points have room and clusters can separate. This is why a heavy-tailed was added to the earlier method, SNE, which used Gaussians in both places.
Step 3: moving the points
We have two sets of numbers, from the data and from the map. t-SNE measures how far apart they are with the Kullback–Leibler divergence (P1.E4):
It uses the natural log, so the cost is in nats, and it is when . This divergence is lopsided, and the lopsidedness shapes the pictures: a pair that is close in the data (large ) but far in the map (small ) costs a lot, but a pair that is far in the data and close in the map costs little. So the map works hard to keep neighbours together and is relaxed about pulling non-neighbours apart. That is why local structure is reliable and global structure is not.
Then it minimizes with gradient descent (P1.F3) on the map positions . The gradient has a neat form:
Read it pair by pair. If the points should be closer, and the term acts like a spring that pulls toward . If they are too close, and it pushes them apart.
A hand-sized run. Put the four points in the map at on a line (a trial layout). Then , but the data say , so A and B should be closer. And against : C and D are drawn closer than the data suggest. The cost is . One gradient step with learning rate moves the points to , , and and lowers the cost to . The first cell below reproduces every probability, , , cost and step of this lesson’s small example.
Two practical tricks matter in real runs.
- Early exaggeration. For the first part of the run the are multiplied by a constant (scikit-learn’s default is ). This makes the attraction strong, so tight clusters form and can slide past each other before the details are worked out.
- Many iterations, and a random start. The cost is not convex, so a run can end in a different place depending on the starting layout, and stopping too early can leave misleading shapes. scikit-learn’s default start is a PCA layout, which makes runs repeatable; the widget uses random starts to show that the picture depends on them.
UMAP in brief
UMAP (McInnes, Healy and Melville, 2018) follows the same plan with different ingredients. The authors describe it as grounded in Riemannian geometry and algebraic topology; at the level of this lesson it works like this:
- Build a graph in the original space. Join each point to its nearest neighbours and give each edge a weight between and (a “fuzzy” edge): the closer the neighbour, the nearer to . The number of neighbours is the setting
n_neighbors(default ). - Lay the graph out in 2-D. Start from a rough layout and move the points so that the map’s own weights match the graph’s: connected points attract each other, and other pairs push each other apart. The setting
min_dist(default ) is how closely points may be packed in the map; small values give clumpier maps.
The two settings play roles like the perplexity. A small n_neighbors stresses fine local detail, and a large one stresses broader structure. The UMAP authors report that its maps are comparable to t-SNE’s, preserve more global structure and run faster; that is a claim from the paper. In this lesson, treat UMAP maps with the same caution as t-SNE maps, because they too depend on the settings, and distances between clusters in them also need checking. One practical difference is that the UMAP class of the umap-learn package has a transform method for new points, which the documentation says is slower than other transformers.
How to misread them
The widget has already shown most of these. The article “How to Use t-SNE Effectively” (Wattenberg, Viégas and Johnson, Distill, 2016) makes several of these points (perplexity, cluster sizes, distances between clusters, noise) and the advice to run until the picture is stable, with many more examples. It is worth reading.
- Cluster sizes mean nothing. t-SNE adapts to the local density, so a dense cluster is expanded and a sparse one shrunk. In the widget the tightest cluster is drawn the biggest. Do not say “cluster C is more varied than A” from the map.
- Distances between clusters may mean nothing. The gaps depend on the perplexity and the run. At perplexity 30 (run A) the widget draws three nearly equal gaps for clusters whose centres are and apart in the data, and at perplexity 100 it draws one of them right and the others wrong. Two clusters that are next to each other in the map are not necessarily more alike than two that are far apart.
- Noise looks like clusters. At low perplexity every point looks at only a few neighbours, and chance neighbours form clumps. The noise preset at perplexity 2 shows groups, from data with no groups.
- The picture depends on perplexity and the random start. A single map is one draw from a family. Look at several perplexities (for example 5, 30 and 50) and several seeds, and trust only what survives.
- A map is not a measurement. Each axis of a t-SNE map has no meaning, and rotating or flipping the picture changes nothing. The only thing to read is who is near whom, locally.
- The map is a one-off. The basic t-SNE method defines the position of the points it was given and nothing else: scikit-learn’s
TSNEhasfit_transformbut notransform, so there is no function that places a new point onto an existing map. To add points you have to run it again, which changes the whole picture, or use a method that learns a mapping (theUMAPclass ofumap-learnhas one). - Coordinates are not features. Treat the two coordinates as a drawing. Distances and sizes in them are distorted, so a distance-based method (P3.B1, P3.C1) fed those coordinates may do worse than on the original data, or give results that change with the seed. If you must cluster or classify, do it on the original or PCA features and use the map to look.
Using them well
- Scale first if the features have different units, as for any distance-based method (P3.A11). The distances in step 1 are computed from the raw numbers.
- Consider PCA to about 50 dimensions first when there are many features. The scikit-learn documentation recommends it for very high-dimensional data: it removes some noise and speeds up the distance computations. It is a speed and noise trade-off, not a rule.
- Try several perplexities and seeds, and run until the picture stops changing. Keep the perplexity below the number of points, and well below the size of the smallest group you hope to see.
- Mind the cost. The exact method compares all pairs, time, and cannot scale to millions of points. scikit-learn’s default is the Barnes–Hut approximation, (
method="exact"selects the slower exact version). The UMAP authors report that it runs faster. - Use the map to find questions, not to answer them. A group in the map is a hypothesis to test in the original data.
In scikit-learn, with real output
scikit-learn is not available in the in-browser runner, so this is a static block with real output from a local run (scikit-learn 1.8). It uses the digits data from P3.C3 (1797 images of pixels), scaled first. trustworthiness (from sklearn.manifold) scores a map from to : it is lower when points that are neighbours in the map were not neighbours in the original space. UMAP is not installed on the machine used for this lesson, so no UMAP code or output is shown.
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE, trustworthiness
from sklearn.preprocessing import StandardScaler
X, y = load_digits(return_X_y=True)
Xs = StandardScaler().fit_transform(X)
print("digits:", X.shape)
pca2 = PCA(n_components=2).fit_transform(Xs)
tsne = TSNE(perplexity=30, random_state=0)
emb = tsne.fit_transform(Xs)
print("t-SNE output:", emb.shape)
print("final KL:", round(tsne.kl_divergence_, 3))
print("has transform:", hasattr(tsne, "transform"))
for name, Z in [("PCA", pca2), ("t-SNE", emb)]:
tw = trustworthiness(Xs, Z, n_neighbors=10)
print("trustworthiness,", name, round(tw, 3))
for seed in (0, 1, 2):
e = TSNE(perplexity=30, init="random",
random_state=seed).fit_transform(Xs)
print("seed", seed, "first point:", e[0].round(1))
digits: (1797, 64)
t-SNE output: (1797, 2)
final KL: 0.837
has transform: False
trustworthiness, PCA 0.816
trustworthiness, t-SNE 0.986
seed 0 first point: [ 4.8 -54.2]
seed 1 first point: [-43.4 28.6]
seed 2 first point: [55.4 0.6]
What it shows: the t-SNE map keeps neighbours far better than the PCA map ( against ). TSNE has no transform. And the same data with three random starts put the first point in three different places: absolute positions mean nothing. (With the default PCA start, the three seeds would give the same map, which is repeatable but not more correct.) The final KL value depends on the perplexity and cannot be compared between maps made with different perplexities.
Depth: three ways to see it
Intuition
Think of a crowd photographed from a balcony, then asked to arrange itself in a flat field so that friends stand next to friends. t-SNE gives every person a list of who their friends are (step 1), and then a crowd-wide shuffle moves people so that friends end up close (steps 2 and 3). Because only closeness of friends counts, the final field shows friend groups clearly, but how far one group stands from another, or how big a group’s patch is, was never part of the rules. The analogy breaks because real friendship is not a bell curve of distance, and because here the “friends” are points in hundreds of dimensions that nobody can see.
Math
, with chosen so that . . . Cost with gradient , minimized by gradient descent with momentum from a small random start.
Code
import numpy as np
from sklearn.manifold import TSNE
Z = TSNE(n_components=2, perplexity=30, init="pca",
random_state=0).fit_transform(X_scaled) # (n, 2): no .transform for new rowsThe next section runs a small NumPy version, step by step.
Go deeper Why the heavy tail gives crowded points room
Suppose the map used a Gaussian too. In a high-dimensional space, a point’s moderately distant neighbours can be very numerous, but in 2-D the circumference of a circle (the room at distance ) grows only like , while in 10-D the room grows like . To give all of them the right similarity, they would have to be squeezed in near the point, and neighbours of different points would pile on each other. With the Student-t curve, a similarity that a Gaussian would give to a short distance can be had at a much larger one, since the curve decreases only like . Moderate-distance pairs can therefore be drawn farther apart at a small cost in , and the crowded centre opens up. It is one reason the cluster separation seen in t-SNE maps appears, and it is also why the distances between clusters are stretched in ways that cannot be read back.
Go deeper The two forces in the gradient
In the gradient, each pair contributes a force along the line between the two points. The attraction comes from and the repulsion from . Early exaggeration multiplies , so the pull wins at first and clusters tighten. Later, repulsion spreads the clusters out. UMAP’s layout step has the same two kinds of force, which is one reason the two methods give maps of a similar style.
Try it in NumPy
In the first cell, the four points of the lesson go through every step: the probabilities of point A for several widths, the search for at perplexity , the symmetrized , the map’s , the cost and one gradient step. In the second cell, a short NumPy t-SNE (about 30 lines) maps 200 made-up Swiss-roll points to 2-D, and we compare how many of each point’s 10 nearest neighbours survive in the PCA map and in the t-SNE map. It takes a few seconds to run.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Change the target perplexity from to and watch the values shrink: each point listens to almost only its nearest neighbour. A perplexity of or more is the most that four points allow, because each point has only three others.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
On the machine used for this lesson, the PCA map keeps of each point’s 10 nearest neighbours and the t-SNE map keeps . The t-SNE map is better, but still not perfect: it is a sensible rather than an exact unrolling. Change seed and perplexity and watch the number move.
Common mistakes
Exercises
- Point A has two neighbours, B and C, both at distance . What are and , for any , and what is the perplexity?
Show answer
The two weights are equal, so each probability is whatever is. A distribution spread evenly over two points has perplexity . - A distribution is . Find its perplexity.
Show answer
bits, so the perplexity is : between and effective neighbours. - With points, and . Find .
Show answer
. - Three points sit at , and on a line in the map. Find , and .
Show answer
The unnormalized values are for the two close pairs and for the far pair. The sum in the denominator runs over ordered pairs, so each pair counts twice: . So and . Counting each pair once, the three values add up to . - You run t-SNE on 5000 points and later receive 10 new points. A colleague suggests calling
transformon them. What is the problem, and what are two options?Show answer
scikit-learn’sTSNEhas notransform, because the method only fixes positions for the points it was given. Options: run t-SNE again on all 5010 points (the whole picture changes), or use a method that learns a mapping that can be applied to new points, such as thetransformmethod of UMAP inumap-learn, or a learned embedding such as an autoencoder (P8.2). - A map shows cluster P twice as wide as cluster Q. Name two reasons this does not mean P is twice as spread out.
Show answer
t-SNE adapts to local density, so dense groups are expanded and sparse ones shrunk, and the size also depends on the perplexity and on the run. Both reasons break the link between the drawn size and the real spread.
Check your understanding
What does a perplexity of tell t-SNE?
Perplexity is for a point’s neighbour distribution, which behaves like the effective number of neighbours, and the method sets each to match it. It is not an iteration count, it does not cut off the neighbours sharply in the method as defined (far points get small but nonzero weight; scikit-learn’s default Barnes–Hut version keeps about the perplexity nearest neighbours for speed), and it does not set the number of clusters.
Why does the map use a heavy-tailed Student-t similarity instead of a Gaussian?
There is not enough room in 2-D for all of a point’s moderate-distance neighbours at the right distances, and the heavy tail lets them be drawn farther away at little cost. The cost is still not convex, so the start still matters, and the map still cannot preserve all distances.
In a t-SNE map, cluster X looks three times wider than cluster Y. What can you conclude?
Drawn sizes are not a measurement: dense clusters are expanded and sparse ones shrunk, and the picture changes with perplexity. The widget draws the tightest cluster the largest. The map also says nothing reliable about point counts or the gaps between clusters.
You see six tight clumps in a map made at perplexity from data you believe has no structure. What is the best next step?
Low perplexity makes each point look at few neighbours, and chance neighbours form clumps even in pure noise, as the widget’s noise preset shows. Features that survive other settings deserve a closer look. Lowering the perplexity makes false clumps more likely, and PCA of the map coordinates only re-describes the picture.
You have a trained t-SNE map of images and receive one new image. With scikit-learn’s
TSNE, what happens?The class offers
fit_transformonly, because t-SNE optimizes the positions of the given points and learns no function from inputs to positions. Re-running changes the whole picture. No averaging or origin rule is part of the method.
Next: P3.C5 uses density and isolation to find anomalies. P3.C1 and P3.C2 group the same kind of unlabelled data, and P8.2 returns to learned, curved codes with autoencoders.