Search

Search papers and lessons

t-SNE

Level 3 · 15 min read

t-SNE places high-dimensional points on a 2D or 3D map so that points that were neighbours stay close, by matching two sets of neighbour probabilities with gradient descent.

On this page

  • Colour = topic mix
  • Probability
  • Linear algebra
  • Calculus
  • Discrete math
  • Representation learning
  • Inference
  • ReadReady to readNot yet

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 dAB2=1d_{AB}^2 = 1, dAC2=9d_{AC}^2 = 9 and dBC2=4d_{BC}^2 = 4. To keep the arithmetic easy, this example uses a fixed spread of 1 for every point.

  1. Turn distances into similarities. Each pair gets a similarity that is large when the points are close and falls off quickly with distance. Use exp⁡(−d2/2)\exp(-d^2/2), 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.
  2. 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 0.607+0.011=0.6180.607 + 0.011 = 0.618, so the probability that B is A's neighbour is 0.607/0.618=0.980.607 / 0.618 = 0.98, and the probability that C is A's neighbour is 0.011/0.618=0.020.011 / 0.618 = 0.02. The probabilities for each point add up to 1. Check: 0.98+0.02=10.98 + 0.02 = 1.
  3. 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 (0.98+0.82)/6=0.30(0.98 + 0.82) / 6 = 0.30. Doing this for every pair gives one joint probability pijp_{ij} per pair, and these add up to 1 over all ordered pairs.
  4. 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, 1/(1+d2)1/(1 + d^2), where dd is the distance on the map. Divide by the total to get qijq_{ij}. 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 1/(1+1)=0.51/(1+1) = 0.5.
  5. Move the map points to reduce the mismatch. Measure how badly the map's probabilities qijq_{ij} fit the data's pijp_{ij}, 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 pijp_{ij} is bigger than qijq_{ij}, 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.

00.511.522.533.5400.20.40.60.81distance dsimilarity
  • Gaussian kernel exp(-d^2/2), data side
  • heavy-tailed kernel 1/(1+d^2), map side
The map keeps moderately distant points somewhat similar, so clusters have room to separate.

The math

Definition: t-SNE

Given data points x1,…,xNx_1, \dots, x_N in a high-dimensional space, t-SNE chooses map points y1,…,yNy_1, \dots, y_N in a space of two or three dimensions so that the joint probabilities pijp_{ij} computed from the data and the joint probabilities qijq_{ij} 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 ii, the conditional probability that jj is its neighbour is

pj∣i=exp⁡(−∥xi−xj∥2/(2σi2))∑k≠iexp⁡(−∥xi−xk∥2/(2σi2))p_{j\mid i} = \frac{\exp\left(-\lVert x_i - x_j \rVert^2 / (2\sigma_i^2)\right)}{\sum_{k \neq i} \exp\left(-\lVert x_i - x_k \rVert^2 / (2\sigma_i^2)\right)}

Here ∥xi−xj∥\lVert x_i - x_j \rVert is the distance between two points, and σi\sigma_i 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 ii. With σi=1\sigma_i = 1 and the distances of the example, pB∣Ap_{B\mid A} comes out to 0.607/0.618=0.980.607 / 0.618 = 0.98.

Choosing each spread: perplexity

The spread σi\sigma_i is not picked by hand. The user chooses a target perplexity, a soft count of neighbours (see Perplexity), and the algorithm searches for the σi\sigma_i that gives this target. For a point with conditional distribution PiP_i,

Perp⁡(Pi)=2H(Pi),H(Pi)=−∑j≠ipj∣ilog⁡2pj∣i\operatorname{Perp}(P_i) = 2^{H(P_i)}, \qquad H(P_i) = -\sum_{j \neq i} p_{j\mid i} \log_2 p_{j\mid i}

where HH 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

pij=pj∣i+pi∣j2Np_{ij} = \frac{p_{j\mid i} + p_{i\mid j}}{2N}

The values pijp_{ij} are symmetric, pij=pjip_{ij} = p_{ji}, and they sum to 1 over all ordered pairs i≠ji \neq j. The factor 2N2N 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:

qij=(1+∥yi−yj∥2)−1∑k≠l(1+∥yk−yl∥2)−1q_{ij} = \frac{\left(1 + \lVert y_i - y_j \rVert^2\right)^{-1}}{\sum_{k \neq l} \left(1 + \lVert y_k - y_l \rVert^2\right)^{-1}}

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 qijq_{ij} 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:

C=∑i∑j≠ipijlog⁡pijqijC = \sum_{i} \sum_{j \neq i} p_{ij} \log \frac{p_{ij}}{q_{ij}}

Its gradient with respect to one map point has a simple form:

∂C∂yi=4∑j≠i(pij−qij) (yi−yj) (1+∥yi−yj∥2)−1\frac{\partial C}{\partial y_i} = 4 \sum_{j \neq i} (p_{ij} - q_{ij}) \, (y_i - y_j) \, \left(1 + \lVert y_i - y_j \rVert^2\right)^{-1}

Each term is a pull or a push along the line from yjy_j to yiy_i. The sign of pij−qijp_{ij} - q_{ij} decides the direction, and the factor (1+∥yi−yj∥2)−1(1 + \lVert y_i - y_j \rVert^2)^{-1} makes distant map points matter less. The update is

yi←yi−η ∂C∂yiy_i \leftarrow y_i - \eta \, \frac{\partial C}{\partial y_i}

with a learning rate η\eta (see Learning Rate). Practical versions also add a Momentum term and, for the first iterations, multiply every pijp_{ij} by a constant such as 4 so that clusters form early and then separate.

Worked examples

Example
Example 1: the map probabilities for three points

Three map points are at yA=(0,0)y_A = (0, 0), yB=(1,0)y_B = (1, 0) and yC=(0,2)y_C = (0, 2). Find qABq_{AB}, qACq_{AC} and qBCq_{BC}.

  1. Squared map distances: ∥yA−yB∥2=1\lVert y_A - y_B \rVert^2 = 1, ∥yA−yC∥2=4\lVert y_A - y_C \rVert^2 = 4, ∥yB−yC∥2=1+4=5\lVert y_B - y_C \rVert^2 = 1 + 4 = 5.
  2. Unnormalised similarities (1+d2)−1(1 + d^2)^{-1}: for AB it is 1/2=0.51/2 = 0.5, for AC it is 1/5=0.21/5 = 0.2, for BC it is 1/6=0.1671/6 = 0.167.
  3. Total over all ordered pairs. Each unordered pair counts twice, so the total is 2×(0.5+0.2+0.167)=2×0.867=1.7332 \times (0.5 + 0.2 + 0.167) = 2 \times 0.867 = 1.733.
  4. Divide each similarity by the total: qAB=0.5/1.733=0.288q_{AB} = 0.5 / 1.733 = 0.288, qAC=0.2/1.733=0.115q_{AC} = 0.2 / 1.733 = 0.115, qBC=0.167/1.733=0.096q_{BC} = 0.167 / 1.733 = 0.096.
  5. Check: the three unordered values add to 0.288+0.115+0.096=0.4990.288 + 0.115 + 0.096 = 0.499, 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.

Example
Example 2: one gradient step for a map point

Take the same three map points as in Example 1. Suppose the data gave these symmetric joint probabilities: pAB=0.20p_{AB} = 0.20, pAC=0.10p_{AC} = 0.10 and pBC=0.20p_{BC} = 0.20. They add to 0.50.5 over unordered pairs, so they add to 1 over ordered pairs, as they should. Find the gradient for yAy_A and take one step with η=0.1\eta = 0.1.

  1. Write the gradient for yAy_A as a sum over j=Bj = B and j=Cj = C, with the factor 4 in front.
  2. For j=Bj = B: pAB−qAB=0.20−0.288=−0.088p_{AB} - q_{AB} = 0.20 - 0.288 = -0.088. The difference yA−yB=(0,0)−(1,0)=(−1,0)y_A - y_B = (0, 0) - (1, 0) = (-1, 0). The kernel is 0.50.5. The term is −0.088×(−1,0)×0.5=(0.044,0)-0.088 \times (-1, 0) \times 0.5 = (0.044, 0).
  3. For j=Cj = C: pAC−qAC=0.10−0.115=−0.015p_{AC} - q_{AC} = 0.10 - 0.115 = -0.015. The difference yA−yC=(0,−2)y_A - y_C = (0, -2). The kernel is 0.20.2. The term is −0.015×(0,−2)×0.2=(0,0.006)-0.015 \times (0, -2) \times 0.2 = (0, 0.006).
  4. Add the two terms: (0.044,0.006)(0.044, 0.006). Multiply by 4: the gradient is (0.176,0.024)(0.176, 0.024).
  5. Take the step: yA←(0,0)−0.1×(0.176,0.024)=(−0.018,−0.002)y_A \leftarrow (0, 0) - 0.1 \times (0.176, 0.024) = (-0.018, -0.002).
  6. Check the direction. A and B should be closer, since pABp_{AB} is smaller than qABq_{AB} here, so the step should push A away from B. A moved from 0 to −0.018-0.018 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 −0.002-0.002, 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.

Example
Example 3: what perplexity means for a real dataset

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 pj∣i=1/30p_{j\mid i} = 1/30. Find the perplexity check and the joint probability for one pair of such neighbours.

  1. Entropy of the even spread: H=−∑j(1/30)log⁡2(1/30)=log⁡230=4.91H = -\sum_{j} (1/30) \log_2 (1/30) = \log_2 30 = 4.91 bits, since the sum has 30 identical terms that add to 1.
  2. Perplexity: 2H=24.91=302^{H} = 2^{4.91} = 30. The chosen perplexity has been hit, and the spread σi\sigma_i that produces an even split over 30 neighbours is the one the search would find.
  3. Suppose A and B are neighbours in this sense, so pB∣A=1/30p_{B\mid A} = 1/30 and pA∣B=1/30p_{A\mid B} = 1/30. Then pAB=(1/30+1/30)/(2×5000)=(2/30)/10000=0.0000067p_{AB} = (1/30 + 1/30) / (2 \times 5000) = (2/30) / 10000 = 0.0000067.
  4. Check the scale: there are 5,000 points, so each point has about 30 neighbours, and there are about 5,000×30=150,0005{,}000 \times 30 = 150{,}000 ordered neighbour pairs, each with a joint probability near 1/(150,000)1/(150{,}000), which is 0.00000670.0000067. The numbers agree.
  5. 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 pABp_{AB} for a pair of neighbours? Answer: each neighbour has 1/101/10, so pAB=(1/10+1/10)/10000=0.00002p_{AB} = (1/10 + 1/10) / 10000 = 0.00002. 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 2H2^{H} 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 pijp_{ij}, from Gaussian similarities whose spreads are set by a chosen perplexity.
  • The map gets its own probabilities qijq_{ij}, 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 qijq_{ij} match the data probabilities pijp_{ij}. The cost is the KL divergence C=∑i∑j≠ipijlog⁡(pij/qij)C = \sum_i \sum_{j \neq i} p_{ij} \log (p_{ij} / q_{ij}). The cost is large when a pair with a big pijp_{ij} has a small qijq_{ij}, 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 1/(1+32)=1/10=0.11/(1 + 3^2) = 1/10 = 0.1. The Gaussian kernel gives exp⁡(−9/2)=0.0111\exp(-9/2) = 0.0111. 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 log⁡210=3.32\log_2 10 = 3.32 bits, so its perplexity is 23.32=102^{3.32} = 10. Even spreading means the point's neighbourhood is as broad as 10 equally likely neighbours, so the spread σi\sigma_i 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.

Sources