Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 3: Classical Machine LearningUnsupervised Learning

t-SNE and UMAP

P3.C445 min●●● AdvancedReviewed Dec 2, 2026

Why this matters for machine learning

t-SNE and UMAP turn data with hundreds of features into a 2-D map in which near points stay near, so you can look at the structure of a data set, if you know how not to over-read the picture.

  • Looking at a map of the learned representations of images, text or cells shows whether classes separate and where a model confuses them; the straight-line map of PCA is the first thing to compare with. (P3.C3: Principal Component Analysis)
  • The embeddings that neural networks learn for words and images are points in hundreds of dimensions, and they are usually inspected with exactly these maps. (P8.2: Autoencoders, coming soon)
  • A map can suggest groups to confirm with a clustering method, but the groups in the map need checking, not trusting. (P3.C1: k-means clustering)
  • The method minimizes a KL divergence by gradient descent, a direct use of two Part 1 ideas. (P1.E4: KL divergence)

Before this: Principal Component Analysis, Entropy, KL divergence, Gradient descent

After this lesson you can

  • Explain why PCA fails on data that lie along a curve, and what a neighbour-preserving map tries to do instead
  • Describe the three steps of t-SNE, the neighbour probabilities with a Gaussian whose width is set by the perplexity, the heavy-tailed Student-t similarities in the map, and the KL divergence that gradient descent reduces, and compute the probabilities for a few points by hand
  • Describe UMAP as a weighted neighbour graph laid out with attraction along edges and repulsion between other pairs, and name its two main settings
  • Read a t-SNE or UMAP picture without being fooled by cluster sizes, distances between clusters, noise that looks like clusters, or a single perplexity or seed

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 28%28\% of the variance of the raw pixels (about 22%22\% 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 75%75\% 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).

Perplexity slider: same data, different pictures

A: 60 points, tight B: 50, medium C: 40, spread out

Three groups, as in the data. Now compare the sizes and distances below with the true ones before trusting anything else about the picture.

Separate groups the eye would see: 3 (points closer than 4 typical nearest-neighbour gaps are linked; groups of 5 or more points are counted)
Cluster size (RMS spread)TrueMap
A0.421.2
B0.821.02
C1.750.79
Centre distanceTrueMap
A–B0.550.96
A–C1.230.96
B–C1.221.08

Each map is a stored t-SNE run of 150 made-up points in 10 dimensions. Move the slider to change the perplexity, and switch between run A and run B, which differ only in the random start. Sizes and distances are scaled so that the three values average 1; the true values come from the 10-dimensional data. The slider also works with the arrow keys.

Stored t-SNE maps (scikit-learn, random start) of 150 made-up points in 10 dimensions, for perplexities 2, 5, 10, 30, 50 and 100 and two random starts. In the cluster preset, shapes show the true cluster. The readouts compare the true sizes and distances with the drawn ones, and count the separate groups the eye would see.

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 0.42:0.82:1.750.42:0.82:1.75 (scaled to average 1), but in the map they are 1.20:1.02:0.791.20:1.02:0.79: the tight cluster looks the biggest and the spread-out one the smallest. The true distances between the cluster centres are 0.550.55 for A–B and about 1.231.23 for the other two pairs, but the map draws all three nearly equal (0.960.96, 0.960.96, 1.081.08).
  • Slide to perplexity 2. The three clusters shatter into 1111 small pieces. Slide up to 100100 and the gaps change again: now A–B is drawn at 0.580.58, close to the truth, and the other two at 1.211.21. The sizes stay wrong. The setting, not the data, decided which gaps looked right.
  • Pure noise. At perplexity 2 the map shows 1414 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 ii it asks: if I picked a neighbour of ii at random, how likely is it to be jj? Near points should get a high probability and far points almost none. It uses a bell curve (a Gaussian, P1.D3) centred on ii:

pj∣i=e−dij2/2σi2∑k≠ie−dik2/2σi2,dij=∥xi−xj∥.\begin{aligned}p_{j\mid i}&=\frac{e^{-d_{ij}^2/2\sigma_i^2}}{\sum_{k\neq i}e^{-d_{ik}^2/2\sigma_i^2}},\\ d_{ij}&=\lVert\mathbf{x}_i-\mathbf{x}_j\rVert.\end{aligned}

The denominator makes the probabilities for point ii add up to 11. The width σi\sigma_i belongs to point ii.

A small example. Four made-up points on a line: A at 00, B at 11, C at 2.52.5, D at 66. From A the squared distances are 11, 6.256.25 and 3636. Take σ=1\sigma=1. The weights are e−0.5=0.6065e^{-0.5}=0.6065 for B, e−3.125=0.0439e^{-3.125}=0.0439 for C and e−18≈0.00000002e^{-18}\approx0.00000002 for D. They add up to 0.65050.6505, so

pB∣A=0.9325,pC∣A=0.0675,pD∣A≈0.\begin{aligned}p_{B\mid A}&=0.9325,\\ p_{C\mid A}&=0.0675,\\ p_{D\mid A}&\approx0.\end{aligned}

A with σ=1\sigma=1 essentially knows only B. Make σ\sigma 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 σi\sigma_i directly. You set one number for all points, the perplexity, and the method searches each point’s σi\sigma_i until that point’s distribution has that perplexity.

The perplexity of a probability distribution is 2H2^{H}, where H=−∑jpjlog⁡2pjH=-\sum_jp_j\log_2p_j is its entropy in bits (P1.E2). It is the effective number of neighbours: a distribution that is spread evenly over kk points has perplexity exactly kk, and a distribution with one dominant point has a perplexity near 11. For A with different widths:

  • σ=0.5\sigma=0.5: p=(1,0,0)p=(1,0,0), perplexity 1.001.00.
  • σ=1\sigma=1: p=(0.932,0.068,0)p=(0.932,0.068,0), perplexity 1.281.28.
  • σ=2\sigma=2: p=(0.653,0.339,0.008)p=(0.653,0.339,0.008), perplexity 1.981.98.
  • σ=5\sigma=5: p=(0.417,0.376,0.207)p=(0.417,0.376,0.207), perplexity 2.882.88.
  • Very large σ\sigma: all three about 13\tfrac13, perplexity close to 33.

So perplexity rises smoothly with σ\sigma from 11 to the number of other points, and a binary search finds the σ\sigma that gives the target. For a target of 22 the four points get σ\sigma values of 2.042.04, 1.441.44, 1.311.31 and 2.152.15. 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 55 and 5050 and uses 3030 by default; larger data sets usually need a larger value.

Symmetrizing

pj∣ip_{j\mid i} and pi∣jp_{i\mid j} differ, because the two points have different σ\sigma. t-SNE averages them into one number per pair:

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

which makes pij=pjip_{ij}=p_{ji} and makes all the pijp_{ij} over all pairs add up to 11. The 2N2N also guarantees that every point, even an outlier whom nobody lists as a neighbour, has some total pull ∑jpij≥12N\sum_jp_{ij}\ge\frac1{2N}, so no point is left to wander free. For the four points, pAB=(0.647+0.574)/8=0.153p_{AB}=(0.647+0.574)/8=0.153, and the largest value is that one; A and D, which are far apart, get pAD=0.008p_{AD}=0.008.

Step 2: similarities in the map

Now place the NN points at random in 2-D, at positions yi\mathbf{y}_i. We want the map’s similarities qijq_{ij} to match the pijp_{ij}. The map uses a different bell curve, the Student-t distribution with one degree of freedom (the same shape as a Cauchy distribution):

qij=wij∑k≠lwkl,wij=11+∥yi−yj∥2.\begin{aligned}q_{ij}&=\frac{w_{ij}}{\sum_{k\neq l}w_{kl}},\\ w_{ij}&=\frac{1}{1+\lVert\mathbf{y}_i-\mathbf{y}_j\rVert^2}.\end{aligned}

A Gaussian falls off like e−d2e^{-d^2}, which is extremely fast. This curve falls off like 1/d21/d^2, 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 qq was added to the earlier method, SNE, which used Gaussians in both places.

Step 3: moving the points

We have two sets of numbers, PP from the data and QQ from the map. t-SNE measures how far apart they are with the Kullback–Leibler divergence (P1.E4):

C=KL(P ∥ Q)=∑i≠jpijlog⁡pijqij.C=\mathrm{KL}(P\,\Vert\,Q)=\sum_{i\neq j}p_{ij}\log\frac{p_{ij}}{q_{ij}}.

It uses the natural log, so the cost is in nats, and it is 00 when Q=PQ=P. This divergence is lopsided, and the lopsidedness shapes the pictures: a pair that is close in the data (large pijp_{ij}) but far in the map (small qijq_{ij}) 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 CC with gradient descent (P1.F3) on the map positions yi\mathbf{y}_i. The gradient has a neat form:

∂C∂yi=4∑j(pij−qij) wij (yi−yj).\frac{\partial C}{\partial\mathbf{y}_i}=4\sum_{j}\big(p_{ij}-q_{ij}\big)\,w_{ij}\,\big(\mathbf{y}_i-\mathbf{y}_j\big).

Read it pair by pair. If pij>qijp_{ij}>q_{ij} the points should be closer, and the term acts like a spring that pulls yi\mathbf{y}_i toward yj\mathbf{y}_j. If pij<qijp_{ij}<q_{ij} they are too close, and it pushes them apart.

A hand-sized run. Put the four points in the map at 0,1,2,30,1,2,3 on a line (a trial layout). Then qAB=0.125q_{AB}=0.125, but the data say pAB=0.153p_{AB}=0.153, so A and B should be closer. And qCD=0.125q_{CD}=0.125 against pCD=0.099p_{CD}=0.099: C and D are drawn closer than the data suggest. The cost is C=0.0544C=0.0544. One gradient step with learning rate 11 moves the points to 0.0700.070, 0.9420.942, 1.8751.875 and 3.1143.114 and lowers the cost to 0.02910.0291. The first cell below reproduces every probability, σ\sigma, qq, 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 pijp_{ij} are multiplied by a constant (scikit-learn’s default is 1212). 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:

  1. Build a graph in the original space. Join each point to its nearest neighbours and give each edge a weight between 00 and 11 (a “fuzzy” edge): the closer the neighbour, the nearer to 11. The number of neighbours is the setting n_neighbors (default 1515).
  2. 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 0.10.1) 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.

  1. 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.
  2. 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 0.550.55 and 1.231.23 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.
  3. 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 1414 groups, from data with no groups.
  4. 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.
  5. 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.
  6. 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 TSNE has fit_transform but no transform, 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 (the UMAP class of umap-learn has one).
  7. 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, O(n2)O(n^2) time, and cannot scale to millions of points. scikit-learn’s default is the Barnes–Hut approximation, O(nlog⁡n)O(n\log n) (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 8×88\times8 pixels), scaled first. trustworthiness (from sklearn.manifold) scores a map from 00 to 11: 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 (0.9860.986 against 0.8160.816). 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

pj∣i=e−∥xi−xj∥2/2σi2∑k≠ie−∥xi−xk∥2/2σi2p_{j\mid i}=\dfrac{e^{-\lVert\mathbf{x}_i-\mathbf{x}_j\rVert^2/2\sigma_i^2}}{\sum_{k\ne i}e^{-\lVert\mathbf{x}_i-\mathbf{x}_k\rVert^2/2\sigma_i^2}}, with σi\sigma_i chosen so that 2H(Pi)=perplexity2^{H(P_i)}=\text{perplexity}. pij=pj∣i+pi∣j2Np_{ij}=\dfrac{p_{j\mid i}+p_{i\mid j}}{2N}. qij=(1+∥yi−yj∥2)−1∑k≠l(1+∥yk−yl∥2)−1q_{ij}=\dfrac{(1+\lVert\mathbf{y}_i-\mathbf{y}_j\rVert^2)^{-1}}{\sum_{k\ne l}(1+\lVert\mathbf{y}_k-\mathbf{y}_l\rVert^2)^{-1}}. Cost C=∑i≠jpijlog⁡pijqijC=\sum_{i\ne j}p_{ij}\log\frac{p_{ij}}{q_{ij}} with gradient 4∑j(pij−qij) wij (yi−yj)4\sum_j(p_{ij}-q_{ij})\,w_{ij}\,(\mathbf{y}_i-\mathbf{y}_j), 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 rows

The 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 rr) grows only like rr, while in 10-D the room grows like r9r^9. 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 qq that a Gaussian would give to a short distance can be had at a much larger one, since the curve decreases only like 1/d21/d^2. Moderate-distance pairs can therefore be drawn farther apart at a small cost in qq, 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 pijp_{ij} and the repulsion from qijq_{ij}. Early exaggeration multiplies pijp_{ij}, 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 σi\sigma_i at perplexity 22, the symmetrized pijp_{ij}, the map’s qijq_{ij}, 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.

Try it: t-SNE steps on four points

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Change the target perplexity from 22 to 1.21.2 and watch the σ\sigma values shrink: each point listens to almost only its nearest neighbour. A perplexity of 33 or more is the most that four points allow, because each point has only three others.

Try it: PCA or t-SNE on a Swiss roll

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 0.6020.602 of each point’s 10 nearest neighbours and the t-SNE map keeps 0.8180.818. 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

  1. Point A has two neighbours, B and C, both at distance 22. What are pB∣Ap_{B\mid A} and pC∣Ap_{C\mid A}, for any σ\sigma, and what is the perplexity?
    Show answerThe two weights are equal, so each probability is 0.50.5 whatever σ\sigma is. A distribution spread evenly over two points has perplexity 22.
  2. A distribution is (0.5, 0.25, 0.25)(0.5,\,0.25,\,0.25). Find its perplexity.
    Show answerH=0.5⋅1+0.25⋅2+0.25⋅2=1.5H=0.5\cdot1+0.25\cdot2+0.25\cdot2=1.5 bits, so the perplexity is 21.5=2.832^{1.5}=2.83: between 22 and 33 effective neighbours.
  3. With N=4N=4 points, pB∣A=0.647p_{B\mid A}=0.647 and pA∣B=0.574p_{A\mid B}=0.574. Find pABp_{AB}.
    Show answerpAB=(0.647+0.574)/(2⋅4)=1.221/8=0.153p_{AB}=(0.647+0.574)/(2\cdot4)=1.221/8=0.153.
  4. Three points sit at 00, 11 and 22 on a line in the map. Find q01q_{01}, q12q_{12} and q02q_{02}.
    Show answerThe unnormalized values are (1+1)−1=0.5(1+1)^{-1}=0.5 for the two close pairs and (1+4)−1=0.2(1+4)^{-1}=0.2 for the far pair. The sum in the denominator runs over ordered pairs, so each pair counts twice: 2(0.5+0.5+0.2)=2.42(0.5+0.5+0.2)=2.4. So q01=q12=0.5/2.4=0.208q_{01}=q_{12}=0.5/2.4=0.208 and q02=0.2/2.4=0.083q_{02}=0.2/2.4=0.083. Counting each pair once, the three values add up to 0.50.5.
  5. You run t-SNE on 5000 points and later receive 10 new points. A colleague suggests calling transform on them. What is the problem, and what are two options?
    Show answerscikit-learn’s TSNE has no transform, 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 the transform method of UMAP in umap-learn, or a learned embedding such as an autoencoder (P8.2).
  6. 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 answert-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

  1. What does a perplexity of 3030 tell t-SNE?

  2. Why does the map use a heavy-tailed Student-t similarity instead of a Gaussian?

  3. In a t-SNE map, cluster X looks three times wider than cluster Y. What can you conclude?

  4. You see six tight clumps in a map made at perplexity 22 from data you believe has no structure. What is the best next step?

  5. You have a trained t-SNE map of 20002000 images and receive one new image. With scikit-learn’s TSNE, what happens?

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.

Key takeaways

  • PCA draws a straight-line shadow of the data, which squashes data that lie along a curve. t-SNE and UMAP instead try to keep each point's neighbours as neighbours in a 2-D map, bending the data as needed.
  • t-SNE turns distances into probabilities: each point spreads a Gaussian over its neighbours, with a width chosen so the effective number of neighbours equals the perplexity. In the map, Student-t similarities have a heavy tail, which gives moderately far points room (the crowding problem). Gradient descent reduces KL(P‖Q).
  • UMAP builds a weighted graph of each point's nearest neighbours (a chosen number of neighbours each) and lays it out in 2-D, pulling connected points together and pushing other points apart; a minimum-distance setting controls how tightly points may pack.
  • The picture is not a measurement. Cluster sizes and the gaps between clusters can mean nothing, random noise can form clusters at low perplexity, and the shapes change with perplexity and the random start. Run several settings before believing a feature.
  • scikit-learn's TSNE has no transform for new points, and the coordinates are for looking, not for feeding to distance-based methods without care. Scale the features first, consider PCA to about 50 dimensions first, and expect exact t-SNE to cost O(n²) and Barnes–Hut O(n log n).
Found a mistake? Tell us