t-SNE: stochastic neighbor embedding
Build t-SNE from neighborhood probabilities, perplexity, KL divergence and a heavy-tailed kernel, then study optimization and how to interpret its plots.
After this lesson you can
- Calibrate per-point bandwidths by binary search to a target perplexity.
- Derive the t-SNE gradient and interpret it as attraction and repulsion.
- Explain crowding and why a heavy-tailed kernel mitigates it.
- Implement exact t-SNE with early exaggeration, momentum and PCA initialization.
- Interpret group sizes, distances and global structure in t-SNE plots critically.
Before you start
Motivation: drawing what does not fit in a drawing
You have points in with ranging from 64 (the digits in this module) to thousands (expression of thousands of genes in each cell, language-model embeddings, layer activations, features of thousands of malware samples you want to see grouped by family), and you want to look at them. PCA gives the best linear projection in terms of variance, but the interesting structure is often neighborhoods: what resembles what. Two digit “3”s may be far apart along the direction of greatest variance while still being neighbors relative to any “8”.
t-SNE (van der Maaten and Hinton, 2008, building on Hinton and Roweis’s 2002 Stochastic Neighbor Embedding) is the most widely used tool for this purpose, for example to visualize cell populations (Kobak and Berens, 2019), and one of the most frequently misinterpreted. It also appears in interpretability (activation maps) and token or sentence embedding maps, with the same interpretive traps. Before the theory, consider a measurement. The cell compares PCA and t-SNE on the first 250 digits of load_digits with two numbers: trustworthiness (the quality measure from the Isomap lesson) with 10 neighbors, which falls when the drawing introduces neighbors that were not neighbors in the data, and purity, the fraction of the 5 closest points in the drawing with the same class (neither method uses the class).
import numpy as np
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE, trustworthiness
digits = load_digits()
X, y = digits.data[:250].astype(float), digits.target[:250]
def purity(Y, y, k=5):
"""Fracción de los k vecinos más próximos en Y que comparten la clase."""
D = ((Y[:, None, :] - Y[None, :, :]) ** 2).sum(-1)
np.fill_diagonal(D, np.inf)
return (y[np.argsort(D, axis=1)[:, :k]] == y[:, None]).mean()
Y_pca = PCA(2).fit_transform(X)
Y_tsne = TSNE(2, perplexity=30, init="pca", random_state=0).fit_transform(X)
for nombre, Y in [("PCA", Y_pca), ("t-SNE", Y_tsne)]:
print(f"{nombre:6s} confiabilidad(10) = {trustworthiness(X, Y, n_neighbors=10):.3f} pureza de los 5 vecinos = {purity(Y, y):.3f}")The difference in local neighborhoods is large: in the PCA projection, 64% of a digit’s 5 nearest neighbors share its class (trustworthiness 0.846), and in t-SNE 98% do (0.994). The price is that t-SNE discards information PCA preserves: the scales and relative positions of groups. That is half the lesson. The other half builds it: neighborhood probabilities calibrated by perplexity, a KL objective, a heavy-tailed kernel for the crowding problem, a gradient read as forces, and the optimization tricks that make it work. With these in hand, correct interpretation of a t-SNE plot can be derived rather than memorized.
SNE: neighborhood probabilities and perplexity
Hinton and Roweis’s (2002) idea is to convert data geometry into probabilities and seek a drawing with the same probabilities.
Each row is a distribution over the other points: a Gaussian centered at whose bandwidth determines how many points “count.” Here is the first practical problem. One shared does not work: in a dense region points are all close and the Gaussian covers them all; in a sparse region the same Gaussian reaches no neighbors and nearly all probability falls on one. We need a per point, and a criterion to set it.
That this adjustment can always be made uniquely is a simple result that justifies the algorithm.
Proof
With and expectation under , entropy in nats is . Since and (derivative of an exponential family),
while is nonconstant. The limits are those of the uniform distribution () and the one concentrated on nearest points (). The intermediate value theorem gives existence and monotonicity gives uniqueness.
∎Hence it is solved by binary search: start from any , double or halve the interval depending on whether perplexity is above or below target, and stop when error is below a tolerance. Each step costs per point, and about 10 to 30 steps suffice. Try the figure: choose a point from the sparse group and one from the dense group, and change perplexity. Then disable calibration and set a shared : perplexity soars for some points and plummets for others.
Typical values are 5 to 50 (van der Maaten and Hinton, 2008), and Kobak and Berens (2019) propose combining 30 with another of order to preserve more global structure (multiscale perplexity, mixing two kernels). A value of 30 means “look at about 30 effective neighbors,” not “30 neighbors”: the Gaussian weights rather than cuts off. A language model with perplexity 30 is uncertain among about 30 words; here, a point is uncertain among about 30 neighbors.
Before seeing the lab implementation, write it yourself: it is the heart of calibration and fits in a dozen lines.
binary_search_sigma(d2, perplexity, tol=1e-5, max_iter=100), which receives a point’s squared distances d2 to all other points (excluding itself) and returns for which has the requested perplexity . Use entropy monotonicity in (binary search, doubling while there is no upper bound). Tests check achieved perplexity on several rows, distance rescaling and monotonicity in target perplexity.import numpy as np
def binary_search_sigma(d2, perplexity, tol=1e-5, max_iter=100):
"""sigma con perplejidad 2^H(p) = perplexity, p_j ∝ exp(-d2_j / (2 sigma^2))."""
d2 = np.asarray(d2, float)
# tu código: beta = 1/(2 sigma^2), cotas lo y hi, entropía H en nats, comparar con log(perplexity)
return 1.0Lab: probabilities from scratch
The cell implements exactly the above: squared distances, binary search for (a solution to the exercise), conditional probabilities, and the symmetrization covered in the next section. Check that all 250 rows reach the requested perplexity and see how much the vary.
import numpy as np
def sq_dists(X):
s = (X ** 2).sum(1)
D = s[:, None] + s[None, :] - 2 * X @ X.T
np.fill_diagonal(D, 0.0)
return np.maximum(D, 0.0)
def row_probs(d2, sigma):
"""p_{j|i} para las distancias al cuadrado d2 (sin el propio punto)."""
w = np.exp(-(d2 - d2.min()) / (2 * sigma ** 2)) # restar el mínimo no cambia p y evita el desbordamiento
return w / w.sum()
def binary_search_sigma(d2, perplexity, tol=1e-5, max_iter=100):
"""sigma tal que la perplejidad de p_{j|i} sea `perplexity`; d2: distancias al cuadrado a los demás puntos."""
d2 = np.asarray(d2, float) - np.min(d2)
objetivo = np.log(perplexity) # entropía objetivo en nats
lo, hi, beta = 0.0, np.inf, 1.0 / np.mean(d2 + 1e-12)
for _ in range(max_iter):
w = np.exp(-beta * d2)
s = w.sum()
p = w / s
H = np.log(s) + beta * (p * d2).sum() # H = log Z + beta E[d]
if abs(H - objetivo) < tol:
break
if H > objetivo: # demasiado difusa: más precisión
lo = beta
beta = beta * 2 if np.isinf(hi) else (beta + hi) / 2
else:
hi = beta
beta = (beta + lo) / 2
return np.sqrt(1.0 / (2.0 * beta))
def joint_probabilities(X, perplexity):
"""P simétrica con suma 1: p_ij = (p_{j|i} + p_{i|j}) / 2n."""
n = len(X)
D = sq_dists(X)
P = np.zeros((n, n))
sigmas = np.zeros(n)
for i in range(n):
d = np.delete(D[i], i)
sigmas[i] = binary_search_sigma(d, perplexity)
P[i, np.arange(n) != i] = row_probs(d, sigmas[i])
P = (P + P.T) / (2 * n)
return np.maximum(P, 1e-12) * (1 - np.eye(n)), sigmas
P, sigmas = joint_probabilities(X, 30)
DX = sq_dists(X)
perps = []
for i in range(len(X)):
p = row_probs(np.delete(DX[i], i), sigmas[i])
perps.append(2 ** (-(p * np.log2(p)).sum()))
print(f"perplejidad de las {len(X)} filas: de {min(perps):.4f} a {max(perps):.4f} (objetivo 30)")
print(f"sigma_i: mínimo {sigmas.min():.2f}, mediana {np.median(sigmas):.2f}, máximo {sigmas.max():.2f}")
print(f"suma de P = {P.sum():.6f}; simétrica: {np.allclose(P, P.T)}")The range from 8.96 to 15.86: each point adapts to its surrounding density (almost a factor of 2 between densest and sparsest for these digits; in the figure above, with a much more heterogeneous cloud, the factor exceeds 10), and perplexity lands exactly at 30.
Symmetrization and the KL objective
SNE minimizes a sum of divergences, one per row, and its gradient is more complicated than that of a single joint distribution over pairs. The naive solution, defining as a Gaussian normalized over all pairs, has a serious flaw for outliers: if is far from everything, all its are tiny and the position of barely affects cost. t-SNE avoids this by symmetrizing the already calibrated conditionals and works with one joint distribution:
Notice the change. Since , symmetrization gives : every point, outlier or not, contributes at least to the total, so there is always force on it. And sums to 1, making it one distribution over ordered pairs (or pairs), not separate distributions.
What KL penalizes and what it lets through
The divergence is asymmetric, and its asymmetry determines which errors cost dearly. A pair’s term is . If is large (neighbors) and the drawing separates them (small ), the logarithm is huge and multiplied by a large . If is nearly zero (not neighbors) and the drawing brings them together, the term is almost zero: weight cancels it, and the cost is only indirect, because sums to 1 and mass taken by that pair is subtracted from others. The cell measures this with 100 pairs: 10 strong neighbors and 90 weak pairs.
import numpy as np
def kl(p, q):
return float((p * np.log(p / q)).sum())
# afinidades de 100 pares: 10 vecinos fuertes (0.06 cada uno) y 90 pares débiles (0.4 repartido)
p = np.concatenate([np.full(10, 0.06), np.full(90, 0.4 / 90)])
q_sep = p.copy()
q_sep[0] = 0.003 # error A: un par de vecinos (p = 0.06) queda separado
q_sep /= q_sep.sum()
q_cer = p.copy()
q_cer[10] = 0.06 # error B: un par débil (p = 0.0044) queda tan cerca como un vecino
q_cer /= q_cer.sum()
print(f"KL(P||Q) con error A (separar vecinos): {kl(p, q_sep):.3f}")
print(f"KL(P||Q) con error B (acercar lejanos): {kl(p, q_cer):.3f}")
print(f"KL(Q||P) con error A (separar vecinos): {kl(q_sep, p):.3f}")
print(f"KL(Q||P) con error B (acercar lejanos): {kl(q_cer, p):.3f}")With , separating two neighbors costs 0.121, almost three times the 0.042 cost of bringing two distant points together; with reverse divergence the order reverses (0.049 versus 0.094). Venna and coauthors (2010) formulated this in information-retrieval terms: minimizing favors recall (true neighbors appear close) at the expense of precision (non-neighbors may appear close). This is the first reason t-SNE is excellent for viewing local clusters and mediocre as a global measure: small “false neighborhoods” remain, and no force keeps distances between distant groups proportional, because between them and cost barely sees them.
The crowding problem and the t kernel
With symmetric SNE and a Gaussian kernel in the drawing, , groups tend to be squashed together at the center, with less separation than in the data (van der Maaten and Hinton show this with MNIST; in the small dataset below the effect is milder but measurable). This failure is called the crowding problem, and has a geometric cause you already know: volume geometry in high dimensions.
In a ball of radius in dimension , the fraction of volume within of the center is . With and , this is : 65% of volume is in the outermost 10% layer. Something similar happens with distances: under norm concentration, pairwise distances cluster around a typical value. See the left figure: for , the median distance between two uniform points is 1.28 times the ball’s radius, and in the plane (a disk) about 0.89 times. An enormous number of points are at “moderate” distances from one another, and the plane lacks room for so many: accommodates equidistant points (vertices of a regular simplex), whereas accommodates only 3.
The optimizer therefore pushes moderately distant points into too small a region to preserve nearby neighbors. Each exerts a tiny attraction (its is small), but there are so many that their sum squashes the center and leaves no room between groups.
van der Maaten and Hinton (2008) solve this by changing the kernel of the drawing, not the data.
Why does it help? Three properties:
- Heavy tails. For large , versus the Gaussian’s . In the center figure, at similarity is with and with the Gaussian: about 175 times more.
- Moderate distances pushed apart at low cost. If is small and is required (a pairwise reading), a Gaussian kernel calls for a drawing distance equal to the data distance (in units of ), whereas Cauchy calls for , with the constant fixed so maps to : a pair at is placed 10.4 units apart and one at 60.1 apart. Moderate distances are stretched greatly, freeing the center. (This is a pairwise reading: the actual solution depends on all pairs at once. The right figure plots it.)
- A mixture of Gaussians. : the Cauchy kernel is a continuous mixture of Gaussians of all widths. View a distant group of points as one point with a broad Gaussian, and the drawing behaves similarly at all scales at once; moreover, there are no exponentials to compute.
Now do it with a real embedding. Both panels use exactly the same (eight groups of 50 points in 10 dimensions, with neighboring groups’ neighborhoods touching), initialization and iterations: only the drawing kernel changes.
The three figures show the result: compared with the Gaussian, Cauchy gives lower final KL (0.54 versus 0.65: heavy tails allow a more like ), retains more neighbors (0.54 versus 0.43), and separates groups more (4.6 versus 3.3). Explore and not everything is monotonic: with KL is slightly lower (0.53), and with slightly higher (0.55), while separation keeps increasing as falls (3.4 with , 3.8 with 2, 6 with 0.5). Greater separation does not mean a better fit to : it is a choice of which distortion to accept. Kobak and coauthors (2019) use precisely to reveal substructure that leaves stuck together.
The gradient as a system of forces
t-SNE optimizes well because its gradient has a clean form.
Proof
Since and , . Only terms depending on contribute. Let : , so only pairs containing contribute, with opposite sign depending on whether is the first or second index. Since , and .
Data term. . Pairs and give the same value by symmetry of and , so the term is .
Normalization term. , because .
Adding the two terms yields the formula.
∎The guided proof exercise below follows this same derivation step by step. It has an immediate mechanical interpretation:
Gradient descent moves in direction : toward with a spring of stiffness (attraction: only the few data neighbors) and away from with force (repulsion: all pairs). The factor (the ) makes both forces decay with distance, and equilibrium is pairwise (when possible). Two properties follow immediately: attraction is as weak as is small, and repulsion of a very distant pair decays as (because and , while vector contributes a ), so distant groups look like point masses, the idea Barnes–Hut exploits later.
The figure shows both forces on each of 250 digits as optimization proceeds.
Two things to observe: (1) at equilibrium average attraction and repulsion almost cancel (net force is much smaller than either), not because they are zero but because they balance point by point; (2) digits in the same group attract through many neighbors and repel the others, producing islands.
Optimization: what makes it work
Cost is nonconvex, and t-SNE minimizes it using gradient descent with momentum and per-coordinate gains. This is van der Maaten and Hinton’s recipe, reproduced by their implementations and scikit-learn:
t-SNE optimization: given , repeat
with and a per-coordinate gain that increases by when gradient and velocity have different signs (velocity already points downhill and direction is maintained: accelerate) and is multiplied by when they agree (the last step crossed the valley bottom and the gradient now pushes back: slow down), bounded below by (Jacobs’s 1988 delta-bar-delta scheme). Momentum is for the first 250 iterations and thereafter, and 1000 iterations are typical.
The ingredients that change the outcome:
- Initialization. Start with points very close together for a smooth initial phase. The original paper samples (standard deviation ); scikit-learn and this lesson use standard deviation : random, , or the first two PCA components rescaled to that scale (scikit-learn’s default). This choice greatly affects global structure, as measured: Kobak and Linderman (2021) show that much of UMAP’s advantage over t-SNE in preserving global structure came from experiments comparing informatively initialized UMAP with randomly initialized t-SNE, and PCA-initialized t-SNE performs comparably. You will measure this in lab 2.
- Early exaggeration. For the first iterations all in the gradient are multiplied by (currently 12 for 250 iterations; the original paper used 4 for 50): attraction becomes while repulsion is unchanged. This is not equivalent to replacing with inside KL: then the coefficient of would be and repulsion would also be multiplied by (the whole gradient would scale, changing only the step size). Attraction dominates the dynamics and same-group points collapse together before repulsion separates them, giving groups free room to move relative to one another. Linderman and Steinerberger (2019) rigorously analyze this phase and obtain criteria for choosing and step size under well-clustered-data assumptions.
- Learning rate. Too small an leaves optimization unfinished; too large destabilizes it. Kobak and Berens (2019) recommend (that is, ) to keep the product from becoming too large; scikit-learn defaults to .
The relation between and matters: exaggeration multiplies the attraction gradient by , and an effective step with too large overshoots the springs’ equilibrium. See the effect in the figure above (restart from iteration 0, raise to 200 with and run: during the 250 exaggeration iterations the 250 digits do not cluster) and measure it in the lab.
Lab: exact t-SNE from scratch
The cell completes the algorithm: vectorized gradient (one matrix with and ), momentum, gains, early exaggeration and PCA initialization. Before using it, check the gradient against finite differences: this is the cheapest test that the derivation is correct.
import time
from sklearn.manifold import trustworthiness
def tsne_grad(P, Y, exag=1.0):
"""Gradiente de t-SNE (núcleo de Cauchy) con la atracción multiplicada por exag, y la matriz Q.
Con exag = 1 es el gradiente de KL(P || Q); con exag > 1 solo cambia el término de P."""
W = 1.0 / (1.0 + sq_dists(Y))
np.fill_diagonal(W, 0.0)
Q = W / W.sum()
M = (exag * P - Q) * W # (e p_ij - q_ij) (1 + d²)⁻¹
grad = 4.0 * (M.sum(1)[:, None] * Y - M @ Y) # 4 Σ_j M_ij (y_i - y_j)
return grad, Q
def kl_divergence(P, Q):
m = P > 0
return float((P[m] * np.log(P[m] / Q[m])).sum())
def pca_init(X, scale=1e-4):
Xc = X - X.mean(0)
_, _, Vt = np.linalg.svd(Xc, full_matrices=False)
Y = Xc @ Vt[:2].T
return Y / Y[:, 0].std() * scale # PC1 con desviación típica 1e-4
def tsne(X, perplexity=30.0, n_iter=500, lr=200.0, exag=12.0, exag_iter=250, init="pca", seed=0, P=None, record=()):
n = len(X)
if P is None:
P, _ = joint_probabilities(X, perplexity)
rs = np.random.RandomState(seed)
Y = pca_init(X) if init == "pca" else 1e-4 * rs.randn(n, 2)
V, ganancia, fotos = np.zeros_like(Y), np.ones_like(Y), {}
for t in range(n_iter):
temprano = t < exag_iter
grad, Q = tsne_grad(P, Y, exag if temprano else 1.0)
ganancia = np.where(np.sign(grad) != np.sign(V), ganancia + 0.2, ganancia * 0.8).clip(0.01)
V = (0.5 if temprano else 0.8) * V - lr * ganancia * grad
Y = Y + V
Y -= Y.mean(0)
if t + 1 in record:
fotos[t + 1] = Y.copy()
_, Q = tsne_grad(P, Y)
return Y, kl_divergence(P, Q), fotos
# 1. el gradiente analítico frente a diferencias finitas centradas
rs = np.random.RandomState(1)
Yc = rs.randn(len(X), 2)
g, _ = tsne_grad(P, Yc)
coste = lambda Y: kl_divergence(P, tsne_grad(P, Y)[1])
i, k, h = 7, 1, 1e-5
Yp, Ym = Yc.copy(), Yc.copy()
Yp[i, k] += h
Ym[i, k] -= h
print(f"gradiente analítico {g[i, k]:.9f}, diferencias finitas {(coste(Yp) - coste(Ym)) / (2 * h):.9f}")
# 2. t-SNE completo: tasa n/12, 500 iteraciones, 250 con exageración 12
t0 = time.time()
Y_mio, kl_mio, _ = tsne(X, P=P, n_iter=500, lr=21, exag_iter=250)
print(f"KL(P||Q) final = {kl_mio:.4f} en {time.time() - t0:.1f} s")
print(f"confiabilidad(10) = {trustworthiness(X, Y_mio, n_neighbors=10):.3f} pureza de los 5 vecinos = {purity(Y_mio, y):.3f}")The analytical gradient matches finite differences in every displayed digit, and the 20-line t-SNE separates digits as well as scikit-learn’s (you will check in lab 2). What remains is hard to see from final geometry: how it gets there. The next two cells repeat optimization with (the classic value in older implementations) and , with the usual exaggeration 12, measuring 5-neighbor purity after 100, 250 and 500 iterations. Then repeat the same setup without exaggeration.
P, _ = joint_probabilities(X, 30)
def tasas(exag):
for lr in (200, 21):
_, kl_final, fotos = tsne(X, P=P, n_iter=500, lr=lr, exag=exag, exag_iter=250, init="random", seed=0, record=(100, 250, 500))
pur = ", ".join(f"{t}: {purity(Y, y):.2f}" for t, Y in fotos.items())
print(f"exageración {exag:4.1f}, tasa {lr:3d} -> pureza a las {pur}; escala a las 250: {fotos[250].std():.1e}; KL final {kl_final:.3f}")
tasas(12.0)tasas(1.0)This honestly measures what happens on a small, easy dataset: without exaggeration everything converges (purity 0.97 or 0.98 already at 100 iterations), so here exaggeration is not necessary; with it only slightly lowers final KL (0.233 versus 0.242). Its beneficial effect is documented on large datasets (Linderman and Steinerberger, 2019; Kobak and Berens, 2019), not 250 digits. What the cell does show is risk: with and , at 100 and 250 iterations purity is at chance level (0.10 and 0.11; with 10 classes, a random neighbor shares class 10% of the time), and by 500 it has recovered purity (0.96) but with almost twice the final KL (0.427 versus 0.233). With clustering is already visible at 100 iterations (0.70). Also inspect the scale column: with and the cloud, starting at standard deviation , shrinks during exaggeration to about as groups organize (exaggerated attraction dominates repulsion), and only unfolds when exaggeration ends; with , however, it jumps to standard deviation around 2 units and stays there churning without clustering: each step moves points a distance comparable to the whole cloud’s size. At low perplexities, where the landscape has more local minima, exaggeration does help: the next two cells compare final KL with and without exaggeration at perplexity 5 for three initialization seeds.
P5, _ = joint_probabilities(X, 5)
def kl_semillas(exag):
kls = [tsne(X, P=P5, n_iter=600, lr=21, exag=exag, init="random", seed=s)[1] for s in range(3)]
print(f"perplejidad 5, exageración {exag:4.1f}: KL final por semilla = {', '.join(f'{k:.3f}' for k in kls)} (media {np.mean(kls):.3f})")
kl_semillas(12.0)kl_semillas(1.0)With exaggeration final KL is lower for all three seeds (mean 0.375 versus 0.394). The difference is small but consistent (do not treat it as a law: these are three runs on 250 points). It is consistent with exaggeration helping avoid poor minima, but is not proof.
Scaling: Barnes–Hut, interpolation and FFT
Exact t-SNE costs per iteration: is dense and every pair enters the gradient. At that is pairs per iteration. To reach hundreds of thousands of points, exploit gradient structure:
- Attraction is sparse. is practically zero except for about neighbors of each point ( is perplexity); tree implementations (van der Maaten, 2014, and scikit-learn) compute only for the nearest neighbors, with cost bound .
- Repulsion is dense but smooth. varies little for distant points and can be grouped. Barnes–Hut (1986, from N-body simulation) places points in a quadtree; for , a cell of size whose center of mass is distance away is replaced by a single point with the weight of all cell points if (scikit-learn and the figure below use the cell side for size; other implementations use half the side or diagonal, changing only the scale of ). With it is exact; larger gives fewer interactions and more error. van der Maaten (2014) obtains cost this way and reaches datasets of millions of objects; scikit-learn defaults to .
- FIt-SNE (Linderman, Rachh, Hoskins, Steinerberger and Kluger, 2017; published 2019) replaces the tree with piecewise polynomial interpolation of the kernel function on an equally spaced grid and computes the resulting convolution with the fast Fourier transform. The gradient bottleneck is precisely this convolution of kernel with point density. The same work introduces late exaggeration (mild exaggeration at the end) to clarify groups, and incorporates multithreaded approximate neighbor search for and out-of-core randomized PCA.
Try it with the real embedding of 250 digits: choose a point, move , and inspect the boxes used.
Savings grow with because the required number of cells grows like , not . With 250 points the saving is already sixfold at ; with points it is orders of magnitude.
What can be read from a t-SNE plot
Everything above lets us deduce what a plot says. Recall what the algorithm optimizes: preserving neighborhood probabilities , which depend on each perplexity-calibrated . Each adapts to local density, so group density and size are not preserved: a very dispersed group and a compact one receive the same number of effective neighbors and occupy similar areas. Between distant groups , so nothing fixes distances between them.
The next figure is a test bench: three groups of very different sizes and densities in the plane, at your chosen perplexity. Compare drawing and data and inspect the readouts.
Now the lesson’s most useful exercise: predict before looking. Three cases repeatedly published as “misreadings” (Wattenberg, Viégas and Johnson, 2016): noise, sizes and distances. Choose your prediction before running it.
What you should have seen: for noise, perplexity 2 produces about 20 nonexistent groups of at least 5 points (18 to 21 depending on initialization seed), perplexity 5 about 14, and perplexity 30 one. For sizes, the data ratio 4.92 becomes 1.00 at perplexity 30. For distances, at perplexity 30 the three centers become almost equidistant (ratios between 0.9 and 1.1, versus 0.50 : 1.00 : 1.50 in the data; hundredths may vary by browser); at 100 they become 0.41 : 1.25 : 1.33 and global geometry starts to reappear, because each point now has effective neighbors in other groups.
These cases and what you know yield a reading guide:
- Local neighborhoods are informative, with caveats: points close in the drawing are usually data neighbors, but there are false neighbors (KL asymmetry tolerates them) and real neighbors left far apart.
- Group sizes are not meaningful: perplexity calibration equalizes apparent density.
- Distances between groups are not meaningful either: few forces preserve them, and groups can appear closer or farther apart, or in a different arrangement, depending on initialization and perplexity.
- One perplexity is not enough. A group appearing only at low perplexity may be noise; one persisting across perplexities, seeds and initializations deserves investigation. At small perplexities noise forms nonexistent groups.
- Initialization matters for global structure. With PCA initialization, the drawing better preserves global arrangement and does not depend on seed (Kobak and Berens, 2019; Kobak and Linderman, 2021).
- Do not cluster the output and validate with the same picture. Any partition of the plane looks reasonable on the plane, and at low perplexity the algorithm also manufactures separation; the cell below measures this with noise.
- First reduce with PCA if is in the thousands: it is faster (distances dominate ‘s cost) and reduces noise; projection to 30–50 components is common.
Lab: reference t-SNE and preservation measures
First compare with the reference implementation. scikit-learn’s KL is calculated with its own (approximated with neighbors), so to compare fairly we evaluate both embeddings with the same above.
kl_en = lambda Y: kl_divergence(P, tsne_grad(P, Y)[1])
def compara(nombre, Y):
print(f"{nombre:24s} KL con mi P = {kl_en(Y):.4f} confiabilidad(10) = {trustworthiness(X, Y, n_neighbors=10):.3f} pureza(5) = {purity(Y, y):.3f}")
Y_sk = TSNE(2, perplexity=30, init="pca", random_state=0).fit_transform(X)
compara("scikit-learn", Y_sk)Y_mio, kl_mio, _ = tsne(X, P=P, n_iter=1000, lr=21)
compara("mío (1000 iteraciones)", Y_mio)Both embeddings have almost identical KL (0.216 and 0.218) and the same neighborhood quality: the 20-line algorithm reaches the same place as the reference implementation with approximations. Now measure preservation against perplexity, initialization and seed. We measure four things: trustworthiness with 10 neighbors (local: penalizes false neighbors in the drawing), preservation of 10 neighbors (fraction of each point’s 10 data neighbors still among its 10 drawing neighbors: penalizes lost neighbors), Spearman correlation between distances between the 10 class centers in data and drawing (global structure between groups), and the same correlation over all point pairs.
from scipy.stats import spearmanr
from scipy.spatial.distance import pdist
centros = lambda Z: np.array([Z[y == c].mean(0) for c in range(10)])
d_cent = pdist(centros(X))
d_todos = pdist(X)
def knn(Z, k=10):
D = sq_dists(Z)
np.fill_diagonal(D, np.inf)
return np.argsort(D, axis=1)[:, :k]
knn_X = knn(X)
def vecinos_conservados(Y, k=10):
"""Fracción media de los k vecinos de cada punto en los datos que siguen entre sus k vecinos en el dibujo."""
kY = knn(Y, k)
return np.mean([len(set(a) & set(b)) / k for a, b in zip(knn_X, kY)])
def medidas(Y):
return (trustworthiness(X, Y, n_neighbors=10), vecinos_conservados(Y),
spearmanr(d_cent, pdist(centros(Y)))[0], spearmanr(d_todos, pdist(Y))[0])
cab = "confiab.(10) vecinos(10) rho(centros) rho(pares)"
def fila_perplejidad(u):
Y = TSNE(2, perplexity=u, init="pca", random_state=0).fit_transform(X)
print(f"{u:11d} " + " ".join(f"{v:10.3f}" for v in medidas(Y)))
print(f"perplejidad {cab}")
fila_perplejidad(5)fila_perplejidad(30)fila_perplejidad(80)def fila_semilla(s):
Y = TSNE(2, perplexity=30, init="random", random_state=s).fit_transform(X)
print(f"{'random':14s} {s:7d} " + " ".join(f"{v:10.3f}" for v in medidas(Y)))
print(f"inicialización semilla {cab}")
m = medidas(Y_sk) # el t-SNE de perplejidad 30 con inicialización por PCA de más arriba
print(f"{'pca':14s} {'0':>7s} " + " ".join(f"{v:10.3f}" for v in m))
fila_semilla(0)fila_semilla(1)fila_semilla(2)Local trustworthiness barely changes with configuration (0.990 to 0.994 in every row): t-SNE does what it optimizes well. Preservation of 10 neighbors is more demanding (80% at perplexity 30) and distinguishes more: at perplexity 5 it drops to 74%, because each point commits to only about 5 effective neighbors and the rest of its 10 true neighbors can end up on another island; initialization and seed barely move it (0.800 to 0.806). What changes is global structure. At perplexity 5, correlation between class-center distances falls to 0.368, versus 0.755 at 30 and 0.703 at 80. With PCA initialization center correlation is 0.755 and, since initialization is deterministic, does not depend on seed; with random initialization it is 0.542, 0.697 and 0.642 depending on seed: worse on average and variable. This small measurement (250 points, 10 classes) points in the same direction as Kobak and Linderman’s (2021) larger-scale results.
The last cell addresses the most tempting methodological mistake: cluster the output and validate on the same picture. With 300 Gaussian noise points in dimension 30 (no groups), the cell runs k-means with 6 groups on each drawing and measures the partition’s silhouette in both drawing and data. As a control, it applies the same procedure to the cloud’s PCA projection.
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
ruido = np.random.RandomState(0).randn(300, 30)
def silueta(nombre, Z):
g = KMeans(6, n_init=5, random_state=0).fit_predict(Z)
print(f"{nombre:22s} silueta de k-means(6): en el dibujo {silhouette_score(Z, g):.3f}, en los datos {silhouette_score(ruido, g):.3f}")
silueta("PCA (control)", PCA(2).fit_transform(ruido))
silueta("t-SNE, perplejidad 2", TSNE(2, perplexity=2, init="pca", random_state=0).fit_transform(ruido))silueta("t-SNE, perplejidad 30", TSNE(2, perplexity=30, init="pca", random_state=0).fit_transform(ruido))In the data silhouette is zero in every case: the partition separates nothing. In the drawing it is always positive, and the control explains why this means nothing: k-means cuts any 2D cloud into compact pieces, whose silhouette is already 0.32 in the PCA projection without any gaps (on Kaufman and Rousseeuw’s classical scale, 0.26 to 0.50 is “weak structure that could be artificial”). t-SNE adds its own effect as perplexity falls: 0.33 at 30 and 0.41 at 2, because it manufactures the noise islands seen in the gallery. Validating a clustering on the same picture used to create it is circular. To claim groups exist, validate in the original space (or using another technique and separate data).
Variants and what comes next
Know these three lines of work:
- Heavier tails. With crowding is reduced further and subgroups left stuck together by are revealed (Kobak and coauthors, 2019); the crowding figure lets you try .
- Exaggeration. Sustained or late exaggeration (Linderman and coauthors, 2017) condenses groups. Böhm, Behrens and Kobak (2022) study the exaggeration factor as a continuous control weighting attraction against repulsion under the name attraction–repulsion spectrum, encompassing t-SNE and other neighbor-embedding methods.
- UMAP. The next lesson, UMAP and the attraction–repulsion spectrum, builds the algorithm and places it on that same spectrum, separating what its foundations say from what code actually optimizes.
Common mistakes
Exercises
Step 1 of 5. How do you rewrite to differentiate it?
More than one answer may be correct.
Summary
- SNE defines Gaussian with a per-point fixed by perplexity (effective number of neighbors). Entropy strictly decreases in precision : binary search converges to a unique .
- t-SNE symmetrizes (, so every point weighs at least ), uses kernel in the drawing and minimizes . KL asymmetry penalizes separating neighbors and tolerates bringing distant points together.
- Crowding. In high dimensions there are many more moderately distant points than room in the plane. Heavy tails (a Gaussian mixture, decay) stretch those distances cheaply and separate groups; with even more so.
- Gradient : attraction with (sparse), repulsion with (dense). Pointwise equilibrium.
- Optimization: descent with momentum (0.5, then 0.8) and gains, initialization at scale (PCA better than random for global structure), early exaggeration and of order . Barnes–Hut approximates only repulsion (); FIt-SNE uses interpolation and FFT.
- Interpretation: local neighborhoods, yes; group sizes, densities and inter-group distances, no. Repeat with multiple perplexities, seeds and initializations, do not cluster the output, and reduce first with PCA when is large.