t-SNE and UMAP: flattening high-dimensional data into a 2D picture
A sentence embedding is a point with hundreds of numbers. To see it, you have to move it onto a flat 2D picture, but some shapes get tangled when you squash them along straight lines (PCA). Unfold two linked rings with t-SNE one step at a time, and see how far you can trust the picture.
Short answer. t-SNE flattens high-dimensional points into 2D while keeping who is whose neighbor. In the original space it writes down, for each point, the chance that every other point is its neighbor. Then it moves points in 2D, bit by bit, until those chances look alike. UMAP is a similar method that keeps a neighbor graph, and it is usually faster. Both are for looking. The distance between clusters and the size of a cluster cannot be trusted, and the picture changes with the settings and the seed.
The data is 48 points in 3D. Ring A (24 green circles) has radius 1 and lies flat. Ring B (24 blue squares) has radius 0.8, stands up, and passes through ring A, like two links of a chain. The points are made up and shaken a little with a fixed seed. The faint lines join neighboring points along each ring. Both pictures zoom so the points fill the box, with the same scale across and up. Changing the perplexity or the seed starts t-SNE over. This is a scaled-down toy. With so few points it computes every pair exactly (learning rate 20, momentum 0.8), and it leaves out tricks that real tools use, such as approximations for big data and "early exaggeration", which makes P bigger during the first steps.
Try this. ① At the start the points sit in a tiny cloud near the origin and KL is 1.52. Press "100 steps": KL drops to 0.23 and the two rings unfold into two separate rings. Press it twice more (300 steps) for 0.19. ② The PCA picture on the left keeps 85% of the variance, but ring B is squashed into a bar, like a ring seen from the side, and cuts across ring A. ③ Set perplexity to 3 and run 300 steps: KL is 0.44 and the rings come out crumpled instead of smoothly round. Set it to 25: KL is 0.08 and the two rings are drawn on top of each other. Different perplexity means a different P, so do not compare KL values across perplexities. ④ At perplexity 10, press "New seed" once (seed 2) and run 300 steps: KL is 0.22 and the picture differs from seed 1. Same data, same settings.
Definitions
The text below explains with pictures and experiments. These are the textbook definitions. The high-dimensional points are x₁, …, xn, their places in 2D are y₁, …, yn, and ‖·‖ is the distance between two points (the Euclidean norm).
- affinity p(j | i), pij
- p(j | i) is a conditional probability: the value of a Gaussian kernel (width σi) centered at point i, divided so that it sums to 1 over the points j ≠ i. We set p(i | i) = 0. t-SNE uses pij, which pairs these up to make them symmetric.
- affinity in 2D, qij
- Between the 2D places y, take , the shape of a Student's t-distribution with 1 degree of freedom (the Cauchy distribution), and divide so that it sums to 1 over all pairs of different points. Its tail is heavier than the Gaussian kernel's, which eases the crowding problem.
- Kullback-Leibler (KL) divergence
- A number that measures how different two probability distributions P and Q are. It is 0 or more, and 0 only when P = Q. Swapping P and Q changes it (it is not symmetric). This is the cost that t-SNE makes smaller.
- perplexity
- Take the entropy H of point i's affinities p(· | i), measured in bits, and raise 2 to that power. Read it as "the number of neighbors the point really looks at". t-SNE fixes one perplexity and, for each point, finds σi by binary search so that the point's perplexity matches it.
- t-SNE (t-distributed stochastic neighbor embedding)
- A nonlinear dimensionality reduction method. It moves the 2D places yi by gradient descent so that KL(P ‖ Q) between the high-dimensional affinities pij and the 2D affinities qij gets smaller. The gradient in the original paper is below. The cost is not convex, so the result depends on the starting places (the seed).
- UMAP (uniform manifold approximation and projection)
- A nonlinear dimensionality reduction method. It builds a k-nearest neighbor graph that links each point to a few of its nearest neighbors (nneighbors). Then it places the points so that the graph built from the 2D places differs as little as possible from it, measured by cross-entropy. min_dist is a hyperparameter that sets how close points may sit to each other in 2D.
1. What it does: flattening high-dimensional points into 2D
An embedding writes a sentence or an image as a point with hundreds of numbers. Similar things land close together. But eyes only see 2D (a flat page). So we move the points onto a plane and try to keep something from the original. Each method keeps a different thing.
PCA squashes along straight lines. It picks the two directions where the points spread out the most and drops a shadow onto that plane. It is fast, always gives the same answer, and can move new points the same way. But a curved shape overlaps itself the moment you squash it. In the lab, ring B turns into a bar, like a ring seen from the side, and cuts across ring A. PCA kept 85% of the variance, yet "who is whose neighbor" is broken.
t-SNE keeps neighbors. It does not pick directions. For each point it writes down who its close neighbors were, as chances, and then moves points in 2D so the same neighbors end up close. It barely cares about distances between far-apart points.
1. In the original space, find a neighbor chance p_ij for every pair (section 2)
2. Drop the points into 2D at random (a tiny cloud near the origin)
3. In 2D, find a neighbor chance q_ij for every pair
4. Move the points a little so that the gap between p and q (KL) shrinks (section 3)
5. Repeat 3 and 4 many times
2. How the formula is built: from distance to neighbor chance
Follow it by hand with four points. Say the distances from A to B, C and D are 1, 2 and 4. Seen from A, we turn "who is my neighbor?" into chances.
- Distance:
d(i, j) = ‖xᵢ − xⱼ‖. From A to B, C, D: 1, 2, 4. A distance grows as points get farther apart, so on its own it is not a "chance of being a neighbor". - Closer means bigger:
exp(−d² ÷ 2σ²). With σ = 1: B 0.607, C 0.135, D 0.00034. It is 1 at distance 0 and drops fast toward 0, the bell shape of the normal distribution. σ is the width of the bell: a wide bell counts far points as neighbors too. Why: to give most of the weight to a few close points and almost none to far ones, you need a curve that drops fast. - Make it add up to 1:
p(j | i) = exp(−d(i, j)² ÷ 2σᵢ²) ÷ Σₖ exp(−d(i, k)² ÷ 2σᵢ²). Divide by the sum 0.742 and you get B 0.817, C 0.182, D 0.00045. It reads "if A picked one neighbor, it would be B 82% of the time". Why: once they are chances, you can compare them with the 2D chances on the same scale and measure the gap with KL. σ is set separately for each point (section 4). - A heavier tail in 2D:
q(i, j) ∝ 1 ÷ (1 + ‖yᵢ − yⱼ‖²). ∝ means "this is the shape before dividing". It is the shape of the heavy-tailed t-distribution with one degree of freedom. At distance 4 the bell gives 0.00034 and this gives 0.059, 175 times more. The value 0.135 that the bell gave at distance 2, this curve gives at distance 2.53. Why (the crowding problem): in many dimensions there is room for a great many points at a medium distance from one point, but a flat plane has no such room. With the same bell, you would have to cram all of them close in, and the middle gets crowded. With a heavier tail, a medium-distance point can sit farther away and still get the same chance, so gaps open up between clusters.
| Point | Distance d | exp(−d² ÷ 2) | ÷ sum = p(j | A) | 1 ÷ (1 + d²) |
|---|---|---|---|---|
| B | 1 | 0.607 | 0.817 | 0.5 |
| C | 2 | 0.135 | 0.182 | 0.2 |
| D | 4 | 0.00034 | 0.00045 | 0.059 |
| Sum | 0.742 | 1 |
Real t-SNE does two more things. It pairs up p: p_ij = (p(j | i) + p(i | j)) ÷ 2n (n is the number of points). And it divides q over all pairs at once, not one point at a time: q_ij = (1 + ‖yᵢ − yⱼ‖²)⁻¹ ÷ Σ_(k≠l) (1 + ‖y_k − y_l‖²)⁻¹. The two curves in the picture are both drawn to start at 1 so you can compare their shapes.
Try this. Press "Next" three times and the table above turns into a picture one column at a time. At step ③ the line below says perplexity 1.61, which means "A looks at about 1.6 neighbors" (section 4). At step ④ the orange dotted line shows the distance that gives the same value 0.135 stretching from 2 to 2.53.
3. How the points move: gradient descent on KL
The gap between p and q is measured with the KL divergence: KL(P‖Q) = Σ p_ij · log(p_ij ÷ q_ij). It is 0 or more, and 0 only when the two lists are the same. It is the number in the lab's status line.
KL is lopsided. If p is big and q is small (close neighbors placed far apart), it grows a lot. If p is small and q is big (far points placed close), it grows only a little. So t-SNE puts its effort into keeping close neighbors and keeps large distances less well. The warnings in section 6 come from this.
Points move by gradient descent. The gradient from the original paper is ∂KL/∂yᵢ = 4 Σⱼ (p_ij − q_ij)(yᵢ − yⱼ)(1 + ‖yᵢ − yⱼ‖²)⁻¹. When p is bigger than q, the two points pull together. When it is smaller, they push apart. The lab's "1 step" moves once against this gradient. The cost is not convex, so where it stops depends on where it starts (the seed).
4. Perplexity: how many neighbors to look at
The σ from section 2 is different for each point. A point in a dense area needs a small σ and a point in a sparse area needs a big one, so every point looks at about the same number of neighbors. Nobody can set σ by hand for each point, so you pick one number, "about how many neighbors", and a binary search finds the σ that fits it for each point. That number is the perplexity.
perplexity = 2^H H = −Σⱼ p(j | i) · log₂ p(j | i) (entropy, in bits)
H: the entropy of point i's neighbor chances, in bits.p(j | i): the chance that point i would pick j if it picked one neighbor (section 2).Σⱼ: add over every neighbor j.
If you split the chance evenly among k neighbors, the perplexity is exactly k. Point A in section 2 gives most of its weight to B, so its perplexity is 1.61. A small value looks only at the very closest points, which gives small pieces and crumples. A large value looks wide and shows the big shape, but clusters can blend. The perplexity must be smaller than the number of points (the lab uses 3, 10 and 25 with 48 points).
5. UMAP in one line
UMAP builds a graph that links each point to a few close neighbors, then lays the points out in 2D so the links in that graph are kept. It is usually faster than t-SNE and handles big data better. It measures the gap between the two graphs with cross-entropy instead of KL. The knobs are the number of neighbors n_neighbors (a role like perplexity) and min_dist, which sets how tightly points may pack in 2D. It is still a picture made to keep neighbors, so the warnings in section 6 apply to UMAP pictures too.
6. How to misread the picture
- Cluster size means nothing. Because σ is fitted per point, dense clusters get stretched and sparse ones get shrunk. In the lab, ring B is smaller than ring A (radius 0.8 vs 1), but in the t-SNE picture they come out about the same size.
- Distances between clusters cannot be trusted either. KL barely cares where far points go. The two rings in the lab are close enough to pass through each other, yet at perplexity 10 they are drawn apart. Far apart does not mean very different, and close does not mean similar.
- The picture changes with the settings and the seed. Perplexity, number of steps and starting positions all give different pictures. Too few steps gives a half-unfolded picture. Do not decide from one picture. Draw it with a few settings and only trust what shows up in all of them.
- You can see clumps in data that has none. With a small perplexity, points that are just scattered can sometimes look like small clumps (the Distill article).
- It is for looking. Be careful feeding it into a model. The 2D coordinates have bent distances and density, and they change when you run it again. If you see clusters in the picture, check them again in the original embeddings with something like k-means.
7. Properties to know
| Property | In plain words | In the lab |
|---|---|---|
| Keeps close neighbors | Placing close neighbors far apart makes KL grow a lot | At perplexity 10 the faint lines stay as rings |
| Keeps large distances less well | Placing far points close makes KL grow only a little | The linked rings are drawn apart |
| No single answer | The cost is not convex, so it stops in different places depending on the start | After 300 steps, seed 1 gives KL 0.19 and seed 2 gives 0.22 |
| Works on every pair of points | n points make n × (n − 1) pairs. Big data uses approximations such as Barnes-Hut | 48 points, 2,256 pairs |
| New points mean running it again | It does not learn a formula, it places each point | PCA moves any point with its two axes |
When to use which
| Method | Good | Bad | Use it when |
|---|---|---|---|
| PCA | Fast and always the same answer. Moves new points the same way. The kept-variance ratio tells you how much you lost | Only squashes along straight lines. Curved shapes overlap | A first look. Cutting down very high dimensions before t-SNE. Shrinking the inputs of a model |
| t-SNE | Close neighbors and small clusters show up clearly | Slow. Cluster size and distance between clusters cannot be trusted. Each setting and seed gives a different picture. Cannot add new points | Checking by eye whether embeddings group similar things, or whether labels are mixed |
| UMAP | Usually faster than t-SNE and fits big data. Can place new points on a fitted picture (transform in umap-learn) | The same warnings as t-SNE. The picture changes with n_neighbors and min_dist | When the data is big and t-SNE is slow. When you keep adding new data to the same picture |
Where it is used
- Looking at embeddings. See whether similar sentences group together and whether different topics mix (embeddings).
- Doubting labels. A point sitting in the middle of another cluster may have a wrong label or be an unclear example. Open the original data and check.
- Looking inside a neural network. Flatten the values of a middle layer and see whether kinds of data pull apart as training goes on.
Common questions
If two clusters are far apart in a t-SNE picture, are they very different?
You cannot say that. t-SNE works hard to keep close neighbors close and cares much less about large distances. Check the distance between clusters and the size of each cluster in the original space.
What perplexity should I use?
There is no right answer. It sets roughly how many neighbors each point looks at, and it must be smaller than the number of points. Draw the picture with a few values and only trust shapes that show up in all of them.
Can I feed t-SNE or UMAP 2D coordinates into a model?
Be careful. The coordinates are made for looking, so distances and density are bent, and they change when you run it again. Plain t-SNE also has no way to place new points on the same picture. If you need fewer inputs, think of PCA or the original embeddings first.
Words
| What this page says | What books call it |
|---|---|
| flattening high-dimensional points into 2D | dimensionality reduction, visualization |
| squashing along straight lines | linear projection, principal component analysis (PCA) |
| neighbor chance | similarity, affinity p_ij, q_ij |
| bell shape | Gaussian kernel |
| distribution with a heavier tail | Student's t-distribution; with one degree of freedom, the Cauchy distribution |
| points crowding on a plane | crowding problem |
| gap between two lists of chances | Kullback-Leibler (KL) divergence |
| about how many neighbors | perplexity |
| random number that sets the start | random seed, initialization |
| making P bigger in the first steps | early exaggeration |
| neighbor graph | k-nearest neighbor graph |
| curved shape | manifold, nonlinear structure |
Sources
- Laurens van der Maaten, Geoffrey Hinton, Visualizing Data using t-SNE, JMLR, 2008. Neighbor chances p and q, pairing up, perplexity and the binary search, the crowding problem and the t-distribution, the gradient, early exaggeration.
- Leland McInnes, John Healy, James Melville, UMAP: Uniform Manifold Approximation and Projection for Dimension Reduction, arXiv:1802.03426. The neighbor graph, cross-entropy, n_neighbors and min_dist.
- Martin Wattenberg, Fernanda Viégas, Ian Johnson, How to Use t-SNE Effectively, Distill. Cluster sizes and distances between clusters, pictures that change with perplexity and steps, clumps that appear in scattered points.
- scikit-learn documentation: TSNE (perplexity smaller than the number of points, the Barnes-Hut approximation, reducing very high dimensions first).