Module contents
Lesson 17 of 24Core 105 min

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 nn points in RD\R^D with DD 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).

[ ]PCA versus t-SNE on 250 digitsBrowser
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 xi\vb{x}_i whose bandwidth σi\sigma_i determines how many points “count.” Here is the first practical problem. One shared σ\sigma 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 σi\sigma_i 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 Z(β)=∑je−βdjZ(\beta) = \sum_j e^{-\beta d_j} and Eβ[⋅]\E_\beta[\cdot] expectation under p(β)p(\beta), entropy in nats is H=log⁡Z+β Eβ[d]H = \log Z + \beta\,\E_\beta[d]. Since  ⁣d ⁣dβlog⁡Z=−Eβ[d]\frac{\dd}{\dd\beta}\log Z = -\E_\beta[d] and  ⁣d ⁣dβEβ[d]=−Var⁡β(d)\frac{\dd}{\dd\beta}\E_\beta[d] = -\Var_\beta(d) (derivative of an exponential family),

 ⁣dH ⁣dβ=−Eβ[d]+Eβ[d]+β  ⁣d Eβ[d] ⁣dβ=−β Var⁡β(d)<0\frac{\dd H}{\dd\beta} = -\E_\beta[d] + \E_\beta[d] + \beta\,\frac{\dd\,\E_\beta[d]}{\dd\beta} = -\beta\,\Var_\beta(d) < 0

while dd is nonconstant. The limits are those of the uniform distribution (β→0\beta \to 0) and the one concentrated on nearest points (β→∞\beta \to \infty). The intermediate value theorem gives existence and monotonicity gives uniqueness.

∎

Hence it is solved by binary search: start from any β\beta, 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 O(n)\bigO(n) 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 σ\sigma: perplexity soars for some points and plummets for others.

InteractiveOne bandwidth per point
Neighbors of selected point: size ∝pj∣i\propto p_{j\mid i}
Perplexity of p⋅∣ip_{\cdot\mid i} versus σ\sigma (bisection finds the intersection with the line)
0204060801000.050.10.31310σ (log scale)012345678
The 36 nearest neighbors, sorted by distance: pj∣ip_{j\mid i} (own scale)
0.135distance rank (1 = nearest)
  • selected point and its σi\sigma_i (circle) and 2σi2\sigma_i (dashed)
  • other points
  • bisection steps (0 is the seed)
15
σi\sigma_i of selected point0.515
Perplexity 2H2^{H}15.00
Entropy HH (bits)3.907
Bisection steps to 1e-520
110 points in the plane: a dense group (55 points), a sparse group (40), and 15 background points. The orange point is selected (click any other): its Gaussian of bandwidth σi\sigma_i (circle, with 2σi2\sigma_i dashed) and each neighbor's size, proportional to pj∣ip_{j\mid i}. Upper right, perplexity of p⋅∣ip_{\cdot\mid i} as a function of σ\sigma (monotonic, as the theorem states) and the lab's binary-search steps, numbered from the seed. Below, probabilities of the 36 nearest neighbors. Initially, perplexity 15 at a sparse-group point: σi=0.515\sigma_i = 0.515. Click a dense-group point and σi\sigma_i falls to about 0.13 (0.09 to 0.27 depending on the point): bandwidth adapts to local density (with perplexity 15, all 110 σi\sigma_i range from 0.09 to 1.24). With calibration off and σ=0.5\sigma = 0.5 for all, the 110 points' perplexities range from 1.1 to 53.2.

Typical values are 5 to 50 (van der Maaten and Hinton, 2008), and Kobak and Berens (2019) propose combining 30 with another of order n/100n/100 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.

CodeCalibrate a bandwidth
Implement 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 σ\sigma for which pj∝exp⁡(−dj/2σ2)p_j \propto \exp(-d_j/2\sigma^2) has the requested perplexity 2H2^{H}. Use entropy monotonicity in β=1/2σ2\beta = 1/2\sigma^2 (binary search, doubling β\beta 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.0
Shift+Enter to run

Lab: probabilities from scratch

The cell implements exactly the above: squared distances, binary search for σi\sigma_i (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 σi\sigma_i vary.

[ ]Binary search for sigma and the P matrixBrowser
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 σi\sigma_i 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 nn divergences, one per row, and its gradient is more complicated than that of a single joint distribution over pairs. The naive solution, defining pijp_{ij} as a Gaussian normalized over all pairs, has a serious flaw for outliers: if xi\vb{x}_i is far from everything, all its pijp_{ij} are tiny and the position of yi\vb{y}_i barely affects cost. t-SNE avoids this by symmetrizing the already calibrated conditionals and works with one joint distribution:

pij=pj∣i+pi∣j2n,qij=(1+∥yi−yj∥2)−1∑k≠l(1+∥yk−yl∥2)−1,C=KL⁡(P ∥ Q)=∑i≠jpijlog⁡pijqij.p_{ij} = \frac{p_{j\mid i} + p_{i\mid j}}{2n}, \qquad q_{ij} = \frac{(1 + \norm{\vb{y}_i - \vb{y}_j}^2)^{-1}}{\sum_{k \neq l}(1 + \norm{\vb{y}_k - \vb{y}_l}^2)^{-1}}, \qquad C = \KL(P \,\|\, Q) = \sum_{i \neq j} p_{ij}\log\frac{p_{ij}}{q_{ij}} .

Notice the change. Since ∑jpj∣i=1\sum_j p_{j\mid i} = 1, symmetrization gives ∑jpij=12n(1+∑jpi∣j)≥12n\sum_j p_{ij} = \tfrac{1}{2n}\big(1 + \sum_j p_{i\mid j}\big) \ge \tfrac{1}{2n}: every point, outlier or not, contributes at least 12n\tfrac{1}{2n} to the total, so there is always force on it. And PP sums to 1, making it one distribution over n(n−1)n(n-1) ordered pairs (or n(n−1)/2n(n-1)/2 pairs), not nn separate distributions.

What KL penalizes and what it lets through

The divergence KL⁡(P ∥ Q)\KL(P \,\|\, Q) is asymmetric, and its asymmetry determines which errors cost dearly. A pair’s term is pijlog⁡(pij/qij)p_{ij}\log(p_{ij}/q_{ij}). If pijp_{ij} is large (neighbors) and the drawing separates them (small qijq_{ij}), the logarithm is huge and multiplied by a large pijp_{ij}. If pijp_{ij} is nearly zero (not neighbors) and the drawing brings them together, the term is almost zero: weight pijp_{ij} cancels it, and the cost is only indirect, because QQ 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.

[ ]Two similarly sized errors with different costsBrowser
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 KL⁡(P ∥ Q)\KL(P\,\|\,Q), separating two neighbors costs 0.121, almost three times the 0.042 cost of bringing two distant points together; with reverse divergence KL⁡(Q ∥ P)\KL(Q\,\|\,P) the order reverses (0.049 versus 0.094). Venna and coauthors (2010) formulated this in information-retrieval terms: minimizing KL⁡(P ∥ Q)\KL(P\,\|\,Q) 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 pij≈0p_{ij} \approx 0 and cost barely sees them.

The crowding problem and the t kernel

With symmetric SNE and a Gaussian kernel in the drawing, qij∝exp⁡(−∥yi−yj∥2)q_{ij} \propto \exp(-\norm{\vb{y}_i - \vb{y}_j}^2), 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 RR in dimension DD, the fraction of volume within (1−ε)R(1-\varepsilon)R of the center is (1−ε)D(1-\varepsilon)^D. With D=10D = 10 and ε=0.1\varepsilon = 0.1, this is 0.910=0.3490.9^{10} = 0.349: 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 D=10D = 10, 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: RD\R^D accommodates D+1D + 1 equidistant points (vertices of a regular simplex), whereas R2\R^2 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 pijp_{ij} 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:

  1. Heavy tails. For large dd, w≈d−2w \approx d^{-2} versus the Gaussian’s e−d2/2e^{-d^2/2}. In the center figure, at d=4d = 4 similarity is 1/17=0.0591/17 = 0.059 with ν=1\nu = 1 and 3.4⋅10−43.4 \cdot 10^{-4} with the Gaussian: about 175 times more.
  2. Moderate distances pushed apart at low cost. If pijp_{ij} is small and qij∝pijq_{ij} \propto p_{ij} is required (a pairwise reading), a Gaussian kernel calls for a drawing distance equal to the data distance (in units of σ\sigma), whereas Cauchy calls for d≈2 e(dh2−1)/2−1d \approx \sqrt{2\,e^{(d_h^2 - 1)/2} - 1}, with the constant fixed so dh=σd_h = \sigma maps to d=1d = 1: a pair at 3σ3\sigma is placed 10.4 units apart and one at 4σ4\sigma 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.)
  3. A mixture of Gaussians. 11+d2=∫0∞e−t e−td2 ⁣dt\frac{1}{1+d^2} = \int_0^\infty e^{-t}\,e^{-t d^2}\dd t: 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.
InteractiveWhy a heavy-tailed kernel
Distance between two uniform points in a ball
00.511.500.511.52distance / R
Output similarity versus 2D distance
110⁻²10⁻⁴10⁻⁶0246distance d in 2D
2D distance required by a pair at dhd_h (in units of σ\sigma)
0.3110100100001234dₕ / σ
  • dimension-DD ball (histogram)
  • disk (2D)
  • Gaussian kernel
  • Student with chosen ν\nu
  • Student with ν=1\nu = 1 (t-SNE)
  • reference: dh=σd_h = \sigma requires d=1d = 1
10
1.00
Median pairwise distance, D=10D = 101.28 R
Median pairwise distance, 2D0.88 R
With ν=1.00\nu = 1.00, a pair at 3σ3\sigma requires in 2D10
With Gaussian kernel, the same pair requires3
Left, distribution of distance between two uniform points in the unit ball in dimension DD (blue histogram, 20,000 pairs) and in the plane (dashed): as DD increases it concentrates around a value greater than the disk's; vertical lines show medians. Center, output similarity of the Gaussian, Student kernel with your chosen ν\nu, and Cauchy (ν=1\nu = 1) against distance dd in 2D (logarithmic vertical scale by default: at d=6d = 6 there are over four orders of magnitude). Right, 2D distance required for a pair at distance dhd_h (in units of σ\sigma) if q∝pq \propto p is required, normalized so dh=σd_h = \sigma maps to d=1d = 1 (orange point): the Gaussian is the identity; with ν=1\nu = 1 it rises explosively. Initially D=10D = 10 and ν=1\nu = 1. Lower ν\nu to 0.5 for heavier tails; raise ν\nu to 30 to approach the Gaussian.

Now do it with a real embedding. Both panels use exactly the same PP (eight groups of 50 points in 10 dimensions, with neighboring groups’ neighborhoods touching), initialization and iterations: only the drawing kernel changes.

InteractiveCrowding in a real embedding
Gaussian kernel (symmetric SNE)
KL ...10 neighbors preserved ...separation ...
Student kernel with ν=1\nu = 1
KL ...10 neighbors preserved ...separation ...
  • group 1
  • group 2
  • group 3
  • group 4
  • group 5
  • group 6
  • group 7
  • group 8
Degrees of freedom ν\nu (right)
Data8 groups of 50 points in 10 dimensions
Eight Gaussian groups of 50 points in dimension 10 (centers about 6 units apart, σ=1\sigma = 1 per coordinate), perplexity 30, identical random initialization, exaggeration 12 for 100 iterations and 600 total iterations (rate 200; 100 with the Gaussian kernel and ν=20\nu = 20). Left: Gaussian kernel (symmetric SNE). Right: Student kernel with your chosen ν\nu (default 1: t-SNE). Below each panel: final KL, fraction of each point's 10 neighbors in 10D that remain its 10 neighbors in 2D, and separation (distance from each group center to the nearest group center divided by its RMS radius, averaged). Initially the Gaussian gives KL 0.65, 0.43 neighbors retained and separation 3.3; t-SNE gives KL 0.54, 0.54 and separation about 4.6 (the last figure can vary by a tenth across browsers). With ν=0.5\nu = 0.5 separation rises to about 6.

The three figures show the result: compared with the Gaussian, Cauchy gives lower final KL (0.54 versus 0.65: heavy tails allow a QQ more like PP), retains more neighbors (0.54 versus 0.43), and separates groups more (4.6 versus 3.3). Explore ν\nu and not everything is monotonic: with ν=2\nu = 2 KL is slightly lower (0.53), and with ν=0.5\nu = 0.5 slightly higher (0.55), while separation keeps increasing as ν\nu falls (3.4 with ν=5\nu = 5, 3.8 with 2, 6 with 0.5). Greater separation does not mean a better fit to PP: it is a choice of which distortion to accept. Kobak and coauthors (2019) use ν<1\nu < 1 precisely to reveal substructure that ν=1\nu = 1 leaves stuck together.

The gradient as a system of forces

t-SNE optimizes well because its gradient has a clean form.

Proof

Since ∑klpkl=1\sum_{kl}p_{kl} = 1 and log⁡qkl=log⁡wkl−log⁡Z\log q_{kl} = \log w_{kl} - \log Z, C=∑pkllog⁡pkl−∑klpkllog⁡wkl+log⁡ZC = \sum p_{kl}\log p_{kl} - \sum_{kl}p_{kl}\log w_{kl} + \log Z. Only terms depending on yi\vb{y}_i contribute. Let dkl2=∥yk−yl∥2d_{kl}^2 = \norm{\vb{y}_k - \vb{y}_l}^2: ∂dkl2∂yi=2(yk−yl)(δki−δli)\pd{d_{kl}^2}{\vb{y}_i} = 2(\vb{y}_k - \vb{y}_l)(\delta_{ki} - \delta_{li}), so only pairs containing ii contribute, with opposite sign depending on whether ii is the first or second index. Since w=(1+d2)−1w = (1 + d^2)^{-1}, ∂log⁡w∂d2=−w\pd{\log w}{d^2} = -w and ∂w∂d2=−w2\pd{w}{d^2} = -w^2.

Data term. −∑klpkl ∂log⁡wkl∂yi=∑klpklwkl 2(yk−yl)(δki−δli)-\sum_{kl}p_{kl}\,\pd{\log w_{kl}}{\vb{y}_i} = \sum_{kl}p_{kl}w_{kl}\,2(\vb{y}_k - \vb{y}_l)(\delta_{ki} - \delta_{li}). Pairs (i,j)(i, j) and (j,i)(j, i) give the same value by symmetry of PP and ww, so the term is 4∑jpijwij(yi−yj)4\sum_j p_{ij}w_{ij}(\vb{y}_i - \vb{y}_j).

Normalization term. ∂log⁡Z∂yi=1Z∑kl∂wkl∂d2 ∂dkl2∂yi=−4Z∑jwij2(yi−yj)=−4∑jqij wij(yi−yj)\pd{\log Z}{\vb{y}_i} = \frac{1}{Z}\sum_{kl}\pd{w_{kl}}{d^2}\,\pd{d_{kl}^2}{\vb{y}_i} = -\frac{4}{Z}\sum_j w_{ij}^2(\vb{y}_i - \vb{y}_j) = -4\sum_j q_{ij}\,w_{ij}(\vb{y}_i - \vb{y}_j), because wij2/Z=qijwijw_{ij}^2/Z = q_{ij}w_{ij}.

Adding the two terms yields the formula. □\square

∎

The guided proof exercise below follows this same derivation step by step. It has an immediate mechanical interpretation:

∂C∂yi=4∑jpijwij(yi−yj)⏟attraction toward data neighbors  −  4∑jqijwij(yi−yj)⏟repulsion from all points.\pd{C}{\vb{y}_i} = \underbrace{4\sum_j p_{ij}w_{ij}(\vb{y}_i - \vb{y}_j)}_{\text{attraction toward data neighbors}} \;-\; \underbrace{4\sum_j q_{ij}w_{ij}(\vb{y}_i - \vb{y}_j)}_{\text{repulsion from all points}} .

Gradient descent moves yi\vb{y}_i in direction −∂C∂yi-\pd{C}{\vb{y}_i}: toward yj\vb{y}_j with a spring of stiffness 4pijwij4p_{ij}w_{ij} (attraction: only the few data neighbors) and away from yj\vb{y}_j with force 4qijwij4q_{ij}w_{ij} (repulsion: all pairs). The factor wijw_{ij} (the (1+d2)−1(1 + d^2)^{-1}) makes both forces decay with distance, and equilibrium is pij=qijp_{ij} = q_{ij} pairwise (when possible). Two properties follow immediately: attraction is as weak as pijp_{ij} is small, and repulsion of a very distant pair decays as d−3d^{-3} (because q∝d−2q \propto d^{-2} and w∝d−2w \propto d^{-2}, while vector yi−yj\vb{y}_i - \vb{y}_j contributes a dd), 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.

InteractiveAttraction and repulsion live
250 digits (64 dimensions) in the plane, color = class
  • attraction (toward neighbors with large pijp_{ij})
  • repulsion (away from all, according to qijq_{ij})
12
21
Arrows
Speed (steps per frame)
Iteration0
Phase
KL(P ∥ Q)\mathrm{KL}(P\,\|\,Q)...
Class purity of 5 neighbors in 2D...
Mean attraction per point...
Mean repulsion per point...
Mean net force per point...
250 8×8 digits (25 per class), perplexity 30, random initialization with standard deviation 10−410^{-4}. Blue arrows are attraction on each point and red arrows repulsion (the negative of each gradient term, at the same scale: the 90th percentile of norms measures 20 pixels). Run, step one iteration at a time, or repeat from iteration 0: during early exaggeration attraction dominates and the cloud shrinks far below its initial scale (the drawing rescales itself, so it looks the same size); when it ends (iteration 250), groups expand and repulsion regains weight. Click a point to see its digit and 8 neighbors with greatest pijp_{ij}. Try raising η\eta to 200 with exaggeration active, and also turning it off. Readouts are measured on the current geometry: KL without exaggeration, class purity of the 5 closest 2D neighbors, and mean forces.

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 CC 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 Y(0)\mat{Y}^{(0)}, repeat

V(t+1)=μt V(t)−η G(t)⊙∇C(Y(t)),Y(t+1)=Y(t)+V(t+1),\mat{V}^{(t+1)} = \mu_t\,\mat{V}^{(t)} - \eta\,\mat{G}^{(t)} \odot \nabla C\big(\mat{Y}^{(t)}\big), \qquad \mat{Y}^{(t+1)} = \mat{Y}^{(t)} + \mat{V}^{(t+1)},

with V(0)=0\mat{V}^{(0)} = \mat{0} and G\mat{G} a per-coordinate gain that increases by 0.20.2 when gradient and velocity have different signs (velocity already points downhill and direction is maintained: accelerate) and is multiplied by 0.80.8 when they agree (the last step crossed the valley bottom and the gradient now pushes back: slow down), bounded below by 0.010.01 (Jacobs’s 1988 delta-bar-delta scheme). Momentum is μ=0.5\mu = 0.5 for the first 250 iterations and 0.80.8 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 Y(0)∼N(0,10−4I)\mat{Y}^{(0)} \sim \mathcal{N}(0, 10^{-4}\mat{I}) (standard deviation 10−210^{-2}); scikit-learn and this lesson use standard deviation 10−410^{-4}: random, N(0,10−8I)\mathcal{N}(0, 10^{-8}\mat{I}), 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 pijp_{ij} in the gradient are multiplied by α\alpha (currently 12 for 250 iterations; the original paper used 4 for 50): attraction becomes 4α∑jpijwij(yi−yj)4\alpha\sum_j p_{ij}w_{ij}(\vb{y}_i - \vb{y}_j) while repulsion is unchanged. This is not equivalent to replacing PP with αP\alpha P inside KL: then the coefficient of log⁡Z\log Z would be α\alpha and repulsion would also be multiplied by α\alpha (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 α\alpha and step size under well-clustered-data assumptions.
  • Learning rate. Too small an η\eta leaves optimization unfinished; too large destabilizes it. Kobak and Berens (2019) recommend η=n/α\eta = n/\alpha (that is, n/12n/12) to keep the product αη\alpha\eta from becoming too large; scikit-learn defaults to max⁡(n/(4α),50)\max(n/(4\alpha), 50).

The relation between η\eta and α\alpha matters: exaggeration multiplies the attraction gradient by α\alpha, and an effective step with αη\alpha\eta too large overshoots the springs’ equilibrium. See the effect in the figure above (restart from iteration 0, raise η\eta to 200 with α=12\alpha = 12 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 M\mat{M} with Mij=(αpij−qij)wijM_{ij} = (\alpha p_{ij} - q_{ij})w_{ij} and ∇i=4∑jMij(yi−yj)=4(∑jMij)yi−4∑jMijyj\nabla_i = 4\sum_j M_{ij}(\vb{y}_i - \vb{y}_j) = 4\big(\sum_j M_{ij}\big)\vb{y}_i - 4\sum_j M_{ij}\vb{y}_j), 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.

[ ]Exact t-SNE from scratch and gradient checkBrowser
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 η=200\eta = 200 (the classic value in older implementations) and η=n/12≈21\eta = n/12 \approx 21, with the usual exaggeration 12, measuring 5-neighbor purity after 100, 250 and 500 iterations. Then repeat the same setup without exaggeration.

[ ]Learning rate and exaggeration are not independent (with exaggeration)Browser
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)
[ ]Learning rate and exaggeration are not independent (without exaggeration)Browser
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 η=21\eta = 21 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 α=12\alpha = 12 and η=200\eta = 200, 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 η=n/12\eta = n/12 clustering is already visible at 100 iterations (0.70). Also inspect the scale column: with α=12\alpha = 12 and η=21\eta = 21 the cloud, starting at standard deviation 10−410^{-4}, shrinks during exaggeration to about 10−710^{-7} as groups organize (exaggerated attraction dominates repulsion), and only unfolds when exaggeration ends; with η=200\eta = 200, 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.

[ ]Exaggeration at low perplexity (with exaggeration)Browser
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)
[ ]Exaggeration at low perplexity (without exaggeration)Browser
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 O(n2)\bigO(n^2) per iteration: QQ is dense and every pair enters the gradient. At n=104n = 10^4 that is 10810^8 pairs per iteration. To reach hundreds of thousands of points, exploit gradient structure:

  • Attraction is sparse. pijp_{ij} is practically zero except for about 3u3u neighbors of each point (uu is perplexity); tree implementations (van der Maaten, 2014, and scikit-learn) compute PP only for the ⌊3u⌋\lfloor 3u \rfloor nearest neighbors, with cost bound O(un)\bigO(un).
  • Repulsion is dense but smooth. qijwijq_{ij}w_{ij} varies little for distant points and can be grouped. Barnes–Hut (1986, from N-body simulation) places points in a quadtree; for yi\vb{y}_i, a cell of size rr whose center of mass is distance dd away is replaced by a single point with the weight of all cell points if r/d<θr/d < \theta (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 θ\theta). With θ=0\theta = 0 it is exact; larger θ\theta gives fewer interactions and more error. van der Maaten (2014) obtains cost O(nlog⁡n)\bigO(n\log n) this way and reaches datasets of millions of objects; scikit-learn defaults to θ=0.5\theta = 0.5.
  • 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 (1+d2)−1(1 + d^2)^{-1} with point density. The same work introduces late exaggeration (mild exaggeration at the end) to clarify groups, and incorporates multithreaded approximate neighbor search for PP and out-of-core randomized PCA.

Try it with the real embedding of 250 digits: choose a point, move θ\theta, and inspect the boxes used.

InteractiveBarnes–Hut in action
Cells used for the selected point
Interactions per point versus θ\theta
010020000.511.5
Mean relative repulsive-force error versus θ\theta
0 %5 %10 %15 %20 %00.511.5
  • cell summarized by its center of mass
  • point summed individually
0.50
Interactions for selected point41 of 249
Relative error of its repulsive force1.24 %
Mean interactions (250 points)41.0
Mean relative error1.23 %
The t-SNE embedding of 250 digits (colors = class), computed by the interactive engine with the same algorithm and settings as the lab (perplexity 30, PCA initialization, η=21\eta = 21, 1000 iterations). For the selected point (orange; click another), pink boxes are quadtree cells replaced by their center of mass (pink point) and orange circles are points summed individually. Raising θ\theta uses larger cells. Right, average interactions per point and mean relative error of repulsive force Fi=∑jwij2(yi−yj)F_i = \sum_j w_{ij}^2(\vb{y}_i - \vb{y}_j) against θ\theta (over 250 points). Initially θ=0.5\theta = 0.5: about 41 interactions instead of 249 with mean error 1.2%. With θ=1\theta = 1 these are 20 and 7.7%; with θ=1.5\theta = 1.5, 14 and 19.6%.

Savings grow with nn because the required number of cells grows like log⁡n\log n, not nn. With 250 points the saving is already sixfold at θ=0.5\theta = 0.5; with 10510^5 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 pijp_{ij}, which depend on each perplexity-calibrated σi\sigma_i. Each σi\sigma_i 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 pij≈0p_{ij} \approx 0, 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.

InteractiveWhat t-SNE preserves
Data (original plane)
t-SNE with perplexity 30 (computing)
  • A (diffuse)
  • B (dense)
  • C (medium)
30
Iteration0 / 500
Cost KL(P ∥ Q)\mathrm{KL}(P\,\|\,Q)...
Relative to meandatat-SNE
radius of A1.89...
radius of B0.35...
radius of C0.76...
distance AB1.04...
distance AC1.23...
distance BC0.73...
Three Gaussian groups in the plane (170, 150 and 110 points with σ=1.3,0.22\sigma = 1.3, 0.22 and 0.550.55), left, and t-SNE run in your browser (500 iterations, random initialization, rate 100, exaggeration 12 for 100 iterations), right. The table gives each group's RMS radius and pairwise center distances, divided by their mean for comparison despite t-SNE not preserving scale. Initially (perplexity 30), dense group B, about five times narrower than diffuse A in the data, occupies a similar area, and inter-group distances are almost equal although they are unequal in the data. Change perplexity: very low values fragment the groups. Between 2 and 100 (with two seeds), B's relative radius never falls below 0.82, versus 0.35 in the data. Try another seed: each group's position changes, relative size barely does.

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.

InteractivePredict before looking
The 200 points come from an isotropic Gaussian in 20 dimensions: there are no groups. What will you see with perplexity 2?
Choose an option to run t-SNE on these data.
Case
Three synthetic cases in dimension 10 or 20. Choose an option and t-SNE runs (500 iterations, identical random initialization in all). Left, two data coordinates (the others are isotropic noise at the same scale, so true geometry is visible); right, the result. Below, run measurements: groups of at least 5 points in noise (by connectivity), ratio of radii of two groups sized 5 to 1, and distances between three groups arranged on a line (at 0, 8 and 24). You can then change perplexity. Results are discussed after the figure: predict before reading them.

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 DD is in the thousands: it is faster (distances dominate PP‘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 PP (approximated with neighbors), so to compare fairly we evaluate both embeddings with the same PP above.

[ ]My t-SNE versus scikit-learn with the same P (1 of 2: scikit-learn)Browser
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)
[ ]My t-SNE versus scikit-learn with the same P (2 of 2: yours)Browser
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.

[ ]Effect of perplexityBrowser
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)
[ ]Effect of perplexity (30)Browser
fila_perplejidad(30)
[ ]Effect of perplexity (80)Browser
fila_perplejidad(80)
[ ]Effect of initialization and seedBrowser
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)
[ ]Effect of seed (1)Browser
fila_semilla(1)
[ ]Effect of seed (2)Browser
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.

[ ]Clustering t-SNE: noise that looks like structureBrowser
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))
[ ]Clustering t-SNE: noise that looks like structure (perplexity 30)Browser
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 ν<1\nu < 1 crowding is reduced further and subgroups left stuck together by ν=1\nu = 1 are revealed (Kobak and coauthors, 2019); the crowding figure lets you try ν=0.5\nu = 0.5.
  • 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

ProofDeriving the t-SNE gradient
Prove: Let PP be symmetric with ∑k≠lpkl=1\sum_{k\neq l}p_{kl} = 1, wkl=(1+∥yk−yl∥2)−1w_{kl} = (1 + \norm{\vb{y}_k - \vb{y}_l}^2)^{-1}, Z=∑a≠bwabZ = \sum_{a\neq b}w_{ab}, qkl=wkl/Zq_{kl} = w_{kl}/Z and C=∑k≠lpkllog⁡(pkl/qkl)C = \sum_{k\neq l}p_{kl}\log(p_{kl}/q_{kl}). Then ∂C∂yi=4∑j≠i(pij−qij) wij (yi−yj)\pd{C}{\vb{y}_i} = 4\sum_{j\neq i}(p_{ij} - q_{ij})\,w_{ij}\,(\vb{y}_i - \vb{y}_j).
0
Use dkl2=∥yk−yl∥2d_{kl}^2 = \norm{\vb{y}_k - \vb{y}_l}^2 and differentiate the data and normalization terms separately.

Step 1 of 5. How do you rewrite CC to differentiate it?

NumericEntropy of a uniform distribution over 30 neighbors
A point's distribution pj∣ip_{j\mid i} is uniform over 30 neighbors and zero elsewhere. What is its entropy HH in bits? (And what is its perplexity?)
QuizWhat can be read from a t-SNE plot
You have a t-SNE plot of data (perplexity 30, PCA initialization). Which readings are valid?

More than one answer may be correct.

NumericPerplexity of a specific distribution
A point has neighborhood probabilities pj∣i=(0.5, 0.25, 0.125, 0.125)p_{j\mid i} = (0.5,\ 0.25,\ 0.125,\ 0.125) over four neighbors. What is its perplexity 2H2^{H}?
QuizWhich error KL penalizes
t-SNE uses KL⁡(P ∥ Q)\KL(P\,\|\,Q), not KL⁡(Q ∥ P)\KL(Q\,\|\,P). Which embedding error is penalized more?
NumericHow much heavier is the Cauchy tail?
At distance d=4d = 4 in the drawing, how many times greater is unnormalized similarity of the Cauchy kernel (1+d2)−1(1 + d^2)^{-1} than Gaussian kernel e−d2/2e^{-d^2/2}? (Both equal 1 at d=0d = 0.)
QuizExaggeration and learning rate
With 250 points, exaggeration α=12\alpha = 12 and η=200\eta = 200, neighbor purity remains at chance at the end of exaggeration, while with η=21\eta = 21 it reaches 0.7. What is the most plausible explanation?
QuizWhat Barnes–Hut accelerates
Barnes–Hut and its variants accelerate t-SNE gradient computation. Which part do they approximate, and why?

Summary

Key idea
t-SNE converts distances to perplexity-calibrated neighborhood probabilities and seeks a drawing with the same probabilities by minimizing KL⁡(P ∥ Q)\KL(P\,\|\,Q), using a Cauchy kernel in the drawing to solve the crowding problem. Its gradient is a force system (attraction to data neighbors, repulsion from all points), so it preserves local neighborhoods well and discards group sizes and distances.
  • SNE defines Gaussian pj∣ip_{j\mid i} with a per-point σi\sigma_i fixed by perplexity 2H2^{H} (effective number of neighbors). Entropy strictly decreases in precision β=1/2σ2\beta = 1/2\sigma^2: binary search converges to a unique σi\sigma_i.
  • t-SNE symmetrizes (pij=(pj∣i+pi∣j)/2np_{ij} = (p_{j\mid i} + p_{i\mid j})/2n, so every point weighs at least 1/2n1/2n), uses kernel (1+d2)−1(1 + d^2)^{-1} in the drawing and minimizes KL⁡(P ∥ Q)\KL(P\,\|\,Q). 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, d−2d^{-2} decay) stretch those distances cheaply and separate groups; with ν<1\nu < 1 even more so.
  • Gradient ∂C∂yi=4∑j(pij−qij)wij(yi−yj)\pd{C}{\vb{y}_i} = 4\sum_j(p_{ij} - q_{ij})w_{ij}(\vb{y}_i - \vb{y}_j): attraction with PP (sparse), repulsion with QQ (dense). Pointwise equilibrium.
  • Optimization: descent with momentum (0.5, then 0.8) and gains, initialization at scale 10−410^{-4} (PCA better than random for global structure), early exaggeration and η\eta of order n/αn/\alpha. Barnes–Hut approximates only repulsion (O(nlog⁡n)\bigO(n\log n)); 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 DD is large.