TL;DR
Data with dozens or thousands of features cannot be drawn directly. t-SNE (t-distributed stochastic neighbor embedding) places each point on a two-dimensional or three-dimensional map so that points that were close together in the original space land close together on the map. It does this by building a probability for every pair of points in the data, building a second probability for every pair on the map, and moving the map points by gradient descent until the two sets of probabilities agree as well as possible.
Builds on: Dimensionality Reduction, Kullback–Leibler Divergence, Student's t-Distribution, Gradient Descent · Leads to: UMAP
Where it's used
Looking at cell types in biology. Single-cell experiments measure thousands of gene activity levels for each cell. Researchers run t-SNE on those measurements and colour the map by suspected cell type, so that groups of cells with similar activity show up as separate islands on the plot.
Inspecting what a neural network has learned. A network turns each image or sentence into a long vector. Feeding those vectors through t-SNE gives a picture in which examples of the same class tend to form clumps. Engineers use the picture to find classes the model confuses, such as two digits that always sit in the same region.
Checking a dataset before modelling. A quick map can reveal duplicate samples, outliers and clusters that a model would otherwise have to discover by itself. The original 2008 paper showed maps of handwritten digits from the MNIST collection, where each digit class formed its own group.
How it works
Take three data points that lie on a line: A at 0, B at 1 and C at 3. Use the squared distance between points to measure how far apart they are. The squared distances are , and . To keep the arithmetic easy, this example uses a fixed spread of 1 for every point.
- Turn distances into similarities. Each pair gets a similarity that is large when the points are close and falls off quickly with distance. Use , which is 0.607 for the pair A and B, 0.135 for the pair B and C, and 0.011 for the pair A and C. Close pairs score high, far pairs score near zero. Check: A and B are the closest pair, and they have the largest similarity, 0.607.
- Turn similarities into neighbour probabilities. From the point of view of A, divide each of its similarities by their total. The total of A's similarities is , so the probability that B is A's neighbour is , and the probability that C is A's neighbour is . The probabilities for each point add up to 1. Check: .
- Make the pairs symmetric. A's view of B (0.98) and B's view of A (about 0.82) disagree, so average the two and divide by the number of points times two. For this pair the result is . Doing this for every pair gives one joint probability per pair, and these add up to 1 over all ordered pairs.
- Place the points on a map and compute the map's own probabilities. Start with any positions for A, B and C on a plane, for example A at (0, 0), B at (1, 0) and C at (0, 2). Give each map pair a similarity that uses a heavy-tailed kernel, , where is the distance on the map. Divide by the total to get . Map points that are far apart now keep some similarity, which is the key change from the first step. Check: the pair A and B, at map distance 1, has kernel .
- Move the map points to reduce the mismatch. Measure how badly the map's probabilities fit the data's , using the KL divergence. Compute the gradient of that mismatch with respect to each map point, and move each point a small step the opposite way. A pair that should be closer than the map shows is pulled together, and a pair that is too close is pushed apart. Repeat steps 4 and 5 until the map stops changing. Check: if is bigger than , the gradient pulls the two map points together.
Figure: the two kernels that do the work. The Gaussian kernel (used in the data, step 1) falls to almost zero by distance 3. The heavy-tailed kernel (used on the map, step 4) still has a noticeable value out there.
- Gaussian kernel exp(-d^2/2), data side
- heavy-tailed kernel 1/(1+d^2), map side
The math
Given data points in a high-dimensional space, t-SNE chooses map points in a space of two or three dimensions so that the joint probabilities computed from the data and the joint probabilities computed from the map are as close as possible, measured by the KL divergence between them.
Step 1 in symbols: similarities in the data
For each point , the conditional probability that is its neighbour is
Here is the distance between two points, and is a spread chosen separately for each point. The numerator is a Gaussian shape in the distance, and the denominator makes the values add up to 1 for each point . With and the distances of the example, comes out to .
Choosing each spread: perplexity
The spread is not picked by hand. The user chooses a target perplexity, a soft count of neighbours (see Perplexity), and the algorithm searches for the that gives this target. For a point with conditional distribution ,
where is the Entropy of the distribution in bits. A point with a small spread has a peaked distribution and a low perplexity, and a point with a large spread has a flat one and a high perplexity. Typical choices are between 5 and 50.
Step 3 in symbols: symmetric joint probabilities
The values are symmetric, , and they sum to 1 over all ordered pairs . The factor is what makes the sum come out to 1.
Step 4 in symbols: the map
The map probabilities use a Student-t kernel with one degree of freedom, which is the heavy-tailed kernel from the walkthrough:
The top line is the unnormalised similarity of the map pair, and the bottom sums that quantity over all ordered pairs of map points, so the add up to 1.
Step 5 in symbols: the cost and its gradient
The cost is the KL divergence between the two sets of probabilities:
Its gradient with respect to one map point has a simple form:
Each term is a pull or a push along the line from to . The sign of decides the direction, and the factor makes distant map points matter less. The update is
with a learning rate (see Learning Rate). Practical versions also add a Momentum term and, for the first iterations, multiply every by a constant such as 4 so that clusters form early and then separate.
Worked examples
Three map points are at , and . Find , and .
- Squared map distances: , , .
- Unnormalised similarities : for AB it is , for AC it is , for BC it is .
- Total over all ordered pairs. Each unordered pair counts twice, so the total is .
- Divide each similarity by the total: , , .
- Check: the three unordered values add to , which is 0.5 up to rounding, because the ordered values add to 1.
Interpretation: the closest pair on the map, A and B, gets the largest share of the probability, and the far pair, A and C, gets less. The map distances are the only input here, so the numbers say nothing about the original data.
Take the same three map points as in Example 1. Suppose the data gave these symmetric joint probabilities: , and . They add to over unordered pairs, so they add to 1 over ordered pairs, as they should. Find the gradient for and take one step with .
- Write the gradient for as a sum over and , with the factor 4 in front.
- For : . The difference . The kernel is . The term is .
- For : . The difference . The kernel is . The term is .
- Add the two terms: . Multiply by 4: the gradient is .
- Take the step: .
- Check the direction. A and B should be closer, since is smaller than here, so the step should push A away from B. A moved from 0 to on the x axis, which is away from B at x equals 1. The same reasoning says A should move away from C, which is at height 2, and A moved slightly down, to , which is also away.
Interpretation: the step moves A a small distance away from the points that the map places too close to it. Repeating this for all points, many times, is the whole optimisation.
Suppose a sample of 5,000 handwritten digits is fed to t-SNE with perplexity 30. Each point's conditional distribution is spread evenly over 30 neighbours, so each neighbour has . Find the perplexity check and the joint probability for one pair of such neighbours.
- Entropy of the even spread: bits, since the sum has 30 identical terms that add to 1.
- Perplexity: . The chosen perplexity has been hit, and the spread that produces an even split over 30 neighbours is the one the search would find.
- Suppose A and B are neighbours in this sense, so and . Then .
- Check the scale: there are 5,000 points, so each point has about 30 neighbours, and there are about ordered neighbour pairs, each with a joint probability near , which is . The numbers agree.
- Try it: suppose the perplexity is changed to 10 with the same 5,000 points, and again each point spreads its probability evenly over its neighbours. What is for a pair of neighbours? Answer: each neighbour has , so . Smaller perplexity means fewer neighbours share each point's probability, so each neighbouring pair gets a larger joint probability.
Common mistakes and tradeoffs
It is tempting to think that distances on the map are faithful everywhere. In fact the map keeps neighbourhoods but distorts large distances. Clusters can be drawn at very different sizes, and the gap between two clusters means little about how different they really are, because the heavy-tailed kernel and the layout process reshape them, and because a few points are shifted to make room for others. Compare neighbours inside a cluster, and treat the gaps as a rough hint.
It is tempting to think that t-SNE is a clustering method. In fact it does not assign labels. The clumps you see are a picture of the neighbour structure, and you still need a clustering method such as k-means or a human reading of the plot to name groups.
It is tempting to think that perplexity is the number of neighbours. In fact it is a soft count: the entropy-based value tells how many neighbours a point effectively spreads its probability over. Changing it changes the picture, sometimes a lot, so try several values, such as 5, 30 and 50, before trusting a map.
It is tempting to think that one run gives the answer. In fact the cost function is not convex, and the map depends on the random starting positions and the step sizes. Two runs on the same data can differ, so compare runs and do not read a single map as proof.
It is tempting to use t-SNE output as features for a downstream model. In fact the map is tuned for display. Its coordinates have no stable meaning from one run to the next, and t-SNE has no simple way to place a new point on an existing map. For features, use Dimensionality Reduction methods such as Principal Component Analysis instead.
The cost grows quickly with the number of points if computed exactly, so for very large datasets, approximations such as Barnes–Hut are used, and they still make it slower than linear methods. UMAP is a common alternative that is usually faster and often keeps more of the global layout, though the two methods answer slightly different questions.
History
In 2002, Geoffrey Hinton and Sam Roweis introduced stochastic neighbor embedding, which used Gaussian kernels on both the data and the map. It worked well on local structure, but points that should have stayed apart tended to crowd into the middle of the map.
In 2008, Laurens van der Maaten and Geoffrey Hinton published t-SNE in the Journal of Machine Learning Research. The change that made it work was the heavy-tailed kernel on the map. Distant points keep more similarity there, which gives clusters room to spread out. The paper showed clear maps of handwritten digits and other data, and the method spread quickly through biology and machine learning because it made high-dimensional data easy to look at.
Recap
- The data gets pairwise neighbour probabilities , from Gaussian similarities whose spreads are set by a chosen perplexity.
- The map gets its own probabilities , from a heavy-tailed kernel, so that moderately distant points keep some similarity.
- The cost is the KL divergence between the two sets, and its gradient pulls neighbours together and pushes unrelated pairs apart.
- Gradient descent moves the map points until the two sets of probabilities agree as well as they can.
- Read the result as a picture of local neighbourhoods, not of exact distances, and compare several runs.
Read next: UMAP, which uses a related but different construction to build a low-dimensional map, and Perplexity for the soft neighbour count that sets each point's spread.
Check yourself
QuestionWhat does t-SNE try to make small, and what is the cost measure?Show answer
It tries to make the map probabilities match the data probabilities . The cost is the KL divergence . The cost is large when a pair with a big has a small , that is, when points that are neighbours in the data are far apart on the map. The reverse mistake costs less, so the layout keeps neighbours together first.
QuestionA map pair is at distance 3. What is its unnormalised t-SNE similarity, and what would the Gaussian kernel exp(-d^2/2) with the same distance give?Show answer
The t-SNE similarity is . The Gaussian kernel gives . The heavy-tailed similarity is about nine times larger at this distance, which is why distant map points keep some similarity under t-SNE.
QuestionWhy does t-SNE use a heavy-tailed kernel on the map but a Gaussian kernel on the data?Show answer
In the data, the Gaussian kernel is fine: it makes only close neighbours count, which is what we want. On the map, a Gaussian would give moderately distant points almost no similarity. Then the map has too little room, and points from different clusters are squeezed into the middle. This is the crowding problem. The heavy tail lets the map push unrelated points far enough apart that clusters separate.
QuestionA point's conditional probabilities are spread evenly over 10 neighbours. What is its perplexity, and what does that tell you about the point's spread?Show answer
Its entropy is bits, so its perplexity is . Even spreading means the point's neighbourhood is as broad as 10 equally likely neighbours, so the spread that the search finds is one that gives a flat distribution over about 10 neighbours.
QuestionYou run t-SNE twice on the same data and get two maps that look different. Does that mean the method is broken, and what should you do?Show answer
Not necessarily. The cost is not convex and the result depends on the random start and the step sizes, so different runs can settle differently. Check whether the same groups of points stay together in both runs, try a few perplexity values, and avoid reading gaps or sizes as exact facts. If the groups hold across runs and settings, the structure is probably real.