Module contents
Lesson 18 of 24Advanced 100 min

UMAP and the attraction-repulsion spectrum

Build UMAP's fuzzy graph, cross-entropy objective and negative-sampling optimization; compare effective loss and the attraction–repulsion spectrum, then study parametric embeddings.

After this lesson you can

  • Build UMAP's fuzzy graph and compare it with t-SNE affinities.
  • Derive UMAP cross-entropy forces and negative-sampling optimization.
  • Explain the difference between nominal and effective loss.
  • Reproduce the attraction–repulsion spectrum by varying t-SNE exaggeration.
  • Train parametric UMAP in PyTorch and embed new points.

Before you start

Motivation: speed, scale and reproducibility

In the previous lesson you saw that t-SNE draws very distinct groups but has three practical problems. Its loss is normalized over all point pairs (the denominator Z=∑k≠lwklZ = \sum_{k \neq l} w_{kl}), so every gradient step considers the whole cloud, and Barnes–Hut or grid interpolation is needed to reduce cost below O(n2)\bigO(n^2) per iteration. These accelerations work well only in 2 or 3 dimensions. And groups’ relative positions depend strongly on the run.

UMAP (Uniform Manifold Approximation and Projection), published by McInnes, Healy and Melville in 2018, was presented as the answer to all three: faster, valid for any output dimension, more stable between runs and, as repeated for years, better at preserving global structure. Within a few years it replaced t-SNE as the default tool across entire fields (especially single-cell biology). The first two advantages are real and have a clear cause: UMAP uses an approximate kk-neighbor graph and an unnormalized loss, allowing stochastic gradient optimization by sampling edges, with per-epoch cost proportional to edge count, O(nk)\bigO(nk), rather than pair count.

The other two claims require nuance, supplied by later research with data. This lesson builds the algorithm piece by piece and then examines it with three studies:

  • Damrich and Hamprecht (2021) calculated in closed form the loss that negative sampling actually optimizes, and it is not the one in the original paper: actual repulsion is much weaker.
  • Böhm, Berens and Kobak (2022) showed that t-SNE and UMAP are two points on the same attraction–repulsion spectrum: multiplying t-SNE attraction by a factor ρ≈4\rho \approx 4 yields something very like UMAP, and taking ρ\rho to infinity yields Laplacian eigenmaps.
  • Kobak and Linderman (2021) showed that UMAP’s supposed global advantage arose from initialization, not the algorithm.

You will finish with UMAP from scratch, compared with reference implementations, and parametric UMAP: a network that learns the projection and applies it to new points in one pass.

The fuzzy neighbor graph

UMAP has two phases, like t-SNE: build a weighted similarity graph in the original space saying which points are neighbors, then seek points in the plane with a similar graph. The first phase is where it differs most from t-SNE.

Nearest-neighbor distance and a bandwidth for each point

This is UMAP graph construction, and each piece has a purpose.

  • ρi\rho_i, local connectivity. Subtracting the distance to the nearest neighbor ensures it always has weight 11: no point is isolated, however far from the rest. In high dimensions distances concentrate around a large value and neighbors are distinguished by excess over the nearest distance; ρi\rho_i removes that common part.
  • σi\sigma_i, a personal measuring scale. In a dense region neighbors are close and σi\sigma_i is small; in a sparse one it is large. Thus all points distribute the same total mass, log⁡2k\log_2 k, regardless of local density. This is the idea of t-SNE’s perplexity calibration, fixing a different quantity.
  • Exponential of distance, not its square. t-SNE uses a Gaussian kernel exp⁡(−dij2/2si2)\exp(-d_{ij}^2/2s_i^2); UMAP uses an exponential of dij−ρid_{ij} - \rho_i. Since mass is distributed only among the k−1k - 1 neighbors, tail shape matters little.

σi\sigma_i exists and is unique as long as the nearest neighbor is not tied with too many others. Let δj=dij−ρi≥0\delta_j = d_{ij} - \rho_i \ge 0 and f(σ)=∑j∈Nie−δj/σf(\sigma) = \sum_{j \in N_i} e^{-\delta_j/\sigma}. Each term with δj>0\delta_j > 0 is continuous and strictly increasing in σ\sigma, from 00 (as σ→0+\sigma \to 0^+) to 11 (as σ→∞\sigma \to \infty); terms with δj=0\delta_j = 0 are always 11. Thus ff strictly increases from ti=#{j:δj=0}≥1t_i = \#\{j : \delta_j = 0\} \ge 1 to k−1k - 1, and f(σ)=log⁡2kf(\sigma) = \log_2 k has a unique solution if ti<log⁡2k<k−1t_i < \log_2 k < k - 1. The right inequality holds for every k≥3k \ge 3 (log⁡23≈1.58<2\log_2 3 \approx 1.58 < 2); the left fails only if at least log⁡2k\log_2 k neighbors share the minimum distance (especially duplicate points). Monotonicity justifies bisection: umap-learn takes 64 steps and, as a safeguard, prevents σi\sigma_i from falling below 10−310^{-3} times mean neighbor distance.

InteractiveInside the fuzzy graph
ρ + σ
Directed weights wj∣i=exp⁡(−(dij−ρi)/σi)w_{j\mid i} = \exp(-(d_{ij} - \rho_i)/\sigma_i) for the k−1k - 1 neighbors of ii
0.00.51.00.510.650.660.750.800.850.85
  • wj∣iw_{j\mid i}
  • circle ρi\rho_i (weight 1) and ρi+σi\rho_i + \sigma_i (weight e−1e^{-1})
Below each bar, distance dijd_{ij} in the plane.
Weights
8
ρi\rho_i (distance to nearest neighbor)0.509
σi\sigma_i0.215
∑jwj∣i\sum_j w_{j\mid i} y log⁡2k\log_2 k3.000 = 3.000
Edges of ii after union and degree di=∑jμijd_i = \sum_j \mu_{ij}7, 3.25
Connected graph components1
The nearest neighbor always gets weight 1 (local connectivity). σi\sigma_i grows in the sparse cloud: each point measures distances using its own ruler, so weights sum to log⁡2k\log_2 k regardless of density.
80 points in the plane: a dense cloud on the left, a sparse one on the right, and a bridge between them. Hover over a point (or touch it): directed mode shows its k−1k - 1 edges with thickness proportional to wj∣iw_{j\mid i}, the circle of radius ρi\rho_i (weight 1), the circle of radius ρi+σi\rho_i + \sigma_i (weight e−1e^{-1}), and below, each neighbor's weight. Compare a dense-cloud point with a sparse one: how does σi\sigma_i change, and what do their weights sum to? Switch to fuzzy union and find dashed edges: neighbors that selected ii when ii did not select them. Lower kk to 3 and count components. Finish with t-SNE: where is the nearest neighbor's mass now?

Fuzzy union

Weights wj∣iw_{j\mid i} are asymmetric: jj can be among ii‘s neighbors without ii being among jj‘s, and even if it is, each measures with its own σ\sigma. UMAP interprets them as edge-existence probabilities according to each endpoint and combines them with the probabilistic sum a+b−aba + b - ab: probability that the edge exists according to at least one endpoint, if their opinions were independent. In fuzzy-set theory this is the union t-conorm.

Compare with t-SNE symmetrization, pij=(pj∣i+pi∣j)/2np_{ij} = (p_{j\mid i} + p_{i\mid j})/2n, an average. For a,b∈[0,1]a, b \in [0, 1],

max⁡(a,b)  ≤  a+b−ab  ≤  a+b,whereasmin⁡(a,b)≤a+b2≤max⁡(a,b).\max(a, b) \;\le\; a + b - ab \;\le\; a + b, \qquad\text{whereas}\qquad \min(a, b) \le \tfrac{a + b}{2} \le \max(a, b).

(The first inequality is a+b−ab−a=b(1−a)≥0a + b - ab - a = b(1 - a) \ge 0.) Union never lowers an edge: it suffices for either endpoint to consider it strong. Since μij≥wj∣i\mu_{ij} \ge w_{j\mid i}, fuzzy degree satisfies di≥∑jwj∣i=log⁡2kd_i \ge \sum_j w_{j\mid i} = \log_2 k. The difference is exactly ∑jwi∣j(1−wj∣i)\sum_j w_{i\mid j}(1 - w_{j\mid i}), so equality holds only if no point selects ii, except perhaps those with wj∣i=1w_{j\mid i} = 1 (its nearest neighbor). That degree returns at the heart of the lesson.

Lab: fuzzy graph from scratch

The cell builds UMAP’s graph on the first 1000 load_digits digits (8×88 \times 8 images, that is, d=64d = 64) with k=15k = 15, the default. Neighbors are computed by brute force: at n=1000n = 1000 it is faster than any approximate structure. Bisection is performed for all points at once.

[ ]UMAP fuzzy graph from scratchBrowser
import numpy as np
from scipy.sparse import csr_matrix
from sklearn.datasets import load_digits

X_all, y_all = load_digits(return_X_y=True)
X, y = X_all[:1000].astype(float), y_all[:1000]
n, k = len(X), 15                      # n_neighbors = 15, contando el propio punto, como umap-learn

def vecinos(X, k):
    """Los k vecinos más cercanos de cada punto (el propio punto en la columna 0) y sus distancias."""
    sq = (X ** 2).sum(1)
    D2 = np.maximum(sq[:, None] + sq[None, :] - 2 * X @ X.T, 0.0)
    np.fill_diagonal(D2, -1.0)         # el propio punto, siempre primero aunque haya duplicados
    idx = np.argsort(D2, axis=1, kind="stable")[:, :k]   # estable: hay muchos empates de distancias enteras
    dist = np.sqrt(np.maximum(np.take_along_axis(D2, idx, 1), 0.0))
    return dist, idx

def rho_sigma(dist, k, iters=64):
    """rho_i y sigma_i por bisección (vectorizada) hasta que sum_j exp(-(d_ij - rho_i)/sigma_i) = log2(k)."""
    rho = dist[:, 1]
    delta = np.maximum(dist[:, 1:] - rho[:, None], 0.0)
    objetivo = np.log2(k)
    lo, hi, sig = np.zeros(len(dist)), np.full(len(dist), np.inf), np.ones(len(dist))
    for _ in range(iters):
        s = np.exp(-delta / sig[:, None]).sum(1)
        grande = s > objetivo          # suma demasiado grande: sigma demasiado grande
        hi = np.where(grande, sig, hi)
        lo = np.where(grande, lo, sig)
        sig = np.where(np.isinf(hi), 2 * sig, (lo + hi) / 2)
    return rho, sig, np.exp(-delta / sig[:, None])

dist, idx = vecinos(X, k)
rho, sigma, W = rho_sigma(dist, k)
filas = np.repeat(np.arange(n), k - 1)
A = csr_matrix((W.ravel(), (filas, idx[:, 1:].ravel())), shape=(n, n))   # pesos dirigidos w_{j|i}
mu = (A + A.T - A.multiply(A.T)).tocsr()                                    # unión difusa
grado = np.asarray(mu.sum(1)).ravel()

print(f"suma de cada fila: {W.sum(1).min():.6f} a {W.sum(1).max():.6f} (log2 k = {np.log2(k):.6f})")
print(f"rho:   mediana {np.median(rho):.2f}, rango [{rho.min():.2f}, {rho.max():.2f}]")
print(f"sigma: mediana {np.median(sigma):.2f}, rango [{sigma.min():.2f}, {sigma.max():.2f}]")
print(f"correlación entre sigma_i y la media de d_ij - rho_i: {np.corrcoef(sigma, (dist[:, 1:] - rho[:, None]).mean(1))[0, 1]:.3f}")
mutuas = A.multiply(A.T).nnz / A.nnz
print(f"aristas dirigidas: {A.nnz}; recíprocas: {100 * mutuas:.1f} %; aristas tras la unión: {mu.nnz // 2}")
print(f"grado difuso d_i: mínimo {grado.min():.3f}, mediana {np.median(grado):.3f}, máximo {grado.max():.3f}")

All rows sum exactly to log⁡215≈3.907\log_2 15 \approx 3.907. Nearest-neighbor distance ranges from 9.43 to 28.97 (gray levels 0 to 16 in 64 pixels) and σi\sigma_i from 0.44 to 10.73: a factor of 24 between the finest and coarsest measuring scales. σi\sigma_i follows the spread of distances above ρi\rho_i almost exactly (correlation 0.976). Only 68.7% of directed edges are reciprocal, and union leaves 9189 undirected edges. Minimum degree is exactly log⁡215\log_2 15, as the inequality predicts, and maximum 14.755. That excess 14.755−3.907=10.8514.755 - 3.907 = 10.85 is ∑jwi∣j(1−wj∣i)\sum_j w_{i\mid j}(1 - w_{j\mid i}), a sum of terms below 1: at least 11 points have that point among their neighbors. These are the hubs from the module’s first lesson.

What topological theory provides and what it does not

The UMAP paper derives the above from a theory of fuzzy simplicial sets, adapted from work by David Spivak. The argument in brief:

  1. Assume data are uniformly distributed over a Riemannian manifold. They are not, but we can pretend they are by changing the metric: if the metric is locally constant near xi\vb{x}_i, rescale distances so xi\vb{x}_i‘s kk neighbors lie within a fixed-radius ball. This justifies each point having its own σi\sigma_i.
  2. Under the additional assumption that the manifold is locally connected, no point should be isolated: hence ρi\rho_i.
  3. Each point thus gives its own metric space, which a functor converts into a fuzzy simplicial set (a graph with weights in [0,1][0, 1], considering only its 1-skeleton). The pointwise versions are incompatible and are combined using fuzzy-set union: the probabilistic sum.
  4. Another fuzzy set is built in the plane, with weights νij=Φ(∥yi−yj∥)\nu_{ij} = \Phi(\norm{\vb{y}_i - \vb{y}_j}), and their cross-entropy as fuzzy sets is minimized.

What the theory provides is a coherent motivation for local normalization, local connectivity and union. What it does not provide is a guarantee for the final embedding: no theorem says the result preserves topology, geodesic distances or density. The paper itself includes a “computational view” in which UMAP is simply a weighted kk-neighbor graph plus a force-directed graph drawing, and the next two sections show that this view explains the output. Two concrete facts confirm it. Böhm, Berens and Kobak replaced weights μij\mu_{ij} with those of the binary kk-neighbor graph and UMAP’s embedding barely changed. Damrich and Hamprecht showed the actual optimizer does not reproduce μij\mu_{ij}, but something very close to its binary version. In practice the theory really leaves two things: per-point normalization and a pairwise-decomposable loss.

The embedding: a low-dimensional curve and cross-entropy

In the plane, UMAP measures the similarity of two points with

νij=Φ(∥yi−yj∥),Φ(t)=11+a t2b,\nu_{ij} = \Phi(\norm{\vb{y}_i - \vb{y}_j}), \qquad \Phi(t) = \frac{1}{1 + a\, t^{2b}},

a two-parameter family containing t-SNE’s Cauchy kernel (a=b=1a = b = 1, unnormalized). Parameters are not chosen directly: they are least-squares fitted to target curve

ψ(t)={1t≤min_dist,exp⁡ ⁣(−(t−min_dist)/spread)t>min_dist,\psi(t) = \begin{cases} 1 & t \le \texttt{min\_dist}, \\ \exp\!\big(-(t - \texttt{min\_dist})/\texttt{spread}\big) & t > \texttt{min\_dist}, \end{cases}

at 300 points in [0,3 spread][0, 3\,\texttt{spread}]. With defaults min_dist = 0.1 and spread = 1, this gives a≈1.577a \approx 1.577 and b≈0.895b \approx 0.895. min_dist says up to what distance two points are considered “stuck together” in the plane: with large min_dist, Φ\Phi stays near 1 longer and strongly connected points need not get as close, so groups expand. It does not enter the high-dimensional graph, computed earlier without it.

This is the UMAP cross-entropy objective. Two differences from t-SNE’s KL explain almost everything.

  • No normalization. In t-SNE, qij=wij/Zq_{ij} = w_{ij}/Z and ZZ couples all pairs: moving two points changes every other similarity. Here each summand depends only on yi\vb{y}_i and yj\vb{y}_j, and the loss is a sum of pairwise terms. This allows stochastic gradients over edges.
  • There is an explicit repulsion term for every pair, −(1−μij)log⁡(1−νij)-(1 - \mu_{ij})\log(1 - \nu_{ij}). Since nearly every pair has μij=0\mu_{ij} = 0, this pushes nearly every pair apart with weight 11.

For an isolated pair, h(ν)=−μlog⁡ν−(1−μ)log⁡(1−ν)h(\nu) = -\mu\log\nu - (1 - \mu)\log(1 - \nu) is strictly convex on (0,1)(0, 1) and its derivative −μ/ν+(1−μ)/(1−ν)-\mu/\nu + (1 - \mu)/(1 - \nu) vanishes at ν=μ\nu = \mu. That is, the nominal loss asks each pair to reproduce its weight: νij=μij\nu_{ij} = \mu_{ij}. Keep that conclusion in mind, because we will contradict it.

InteractiveThe low-dimensional curve and its forces
Horizontal axis: distance tt between two points in the plane
  • target ψ(t)\psi(t)
  • fit Φ(t)=1/(1+at2b)\Phi(t) = 1/(1 + a t^{2b})
  • t-SNE: 1/(1+t2)1/(1 + t^2)
View
0.10
1.00
aa1.577
bb0.895
Distance with Φ=1/2\Phi = 1/20.775
With min_dist = 0.1 and spread = 1 we obtain a≈1.577a \approx 1.577, b≈0.895b \approx 0.895, umap-learn defaults. With a=b=1a = b = 1 the curve is the t-SNE Cauchy kernel (orange). min_dist does not change the high-dimensional graph: it controls how tightly connected points can pack in the plane.
Above, dashed gray shows the target curve ψ\psi; blue shows the fit Φ(t)=1/(1+at2b)\Phi(t) = 1/(1 + a t^{2b}) with aa and bb computed live; orange shows t-SNE's Cauchy kernel. Move min_dist from 0 to 1: the flat section lengthens, aa falls and bb rises. In the force view, for a pair with weight μ\mu, attraction (teal) and repulsion (red) of the nominal loss cross exactly where Φ(t∗)=μ\Phi(t^*) = \mu. Raise μ\mu toward 1: equilibrium approaches 0. With high μ\mu, now raise min_dist: the same pair equilibrates farther apart.

Optimization: stochastic gradient, negative sampling and spectral initialization

Forces on a pair

Let s=∥yi−yj∥2s = \norm{\vb{y}_i - \vb{y}_j}^2, so ν=1/(1+asb)\nu = 1/(1 + a s^b). Since ∇yis=2(yi−yj)\grad_{\vb{y}_i} s = 2(\vb{y}_i - \vb{y}_j),

∇yi(−log⁡ν)=2ab sb−11+asb(yi−yj),∇yi(−log⁡(1−ν))=−2bs (1+asb)(yi−yj).\grad_{\vb{y}_i}\big(-\log\nu\big) = \frac{2ab\, s^{b-1}}{1 + a s^b}(\vb{y}_i - \vb{y}_j), \qquad \grad_{\vb{y}_i}\big(-\log(1 - \nu)\big) = -\frac{2b}{s\,(1 + a s^b)}(\vb{y}_i - \vb{y}_j).

The first gradient points from yj\vb{y}_j to yi\vb{y}_i, so descending along it brings points together: attraction, with weight μij\mu_{ij}. The second has the opposite sign and pushes them apart: repulsion, with weight 1−μij1 - \mu_{ij}. Repulsion has a factor 1/s1/s that explodes when points coincide; umap-learn replaces it with 1/(0.001+s)1/(0.001 + s) and clips each gradient component to [−4,4][-4, 4] before multiplying by the learning rate. With a=b=1a = b = 1 these forces can be compared term by term with the t-SNE gradient: you will do so in the final proof exercise.

Negative sampling

Computing the full gradient costs O(n2)\bigO(n^2) because of all-pairs repulsion. UMAP replaces it with stochastic gradient descent sampling attraction by edges and repulsion by negative sampling, the same word2vec trick (Mikolov and coauthors, 2013) used by node2vec and other graph embeddings. In umap-learn 0.5.12 each epoch does the following:

  1. Each directed graph edge (i,j)(i, j) (both directions of every symmetric edge are listed) is processed on average μij/μmax⁡\mu_{ij}/\mu_{\max} times per epoch: once every μmax⁡/μij\mu_{\max}/\mu_{ij} epochs. Edges with μij<μmax⁡/nepochs\mu_{ij} < \mu_{\max}/n_{\text{epochs}} are removed before starting: they would be processed fewer than once in the entire optimization.
  2. When processing it, apply an attraction step to yi\vb{y}_i and the opposite step to yj\vb{y}_j.
  3. Choose mm points kk uniformly at random (negative_sample_rate, default m=5m = 5), assume μik=0\mu_{ik} = 0, and apply to yi\vb{y}_i, only to it, a step of repulsion from yk\vb{y}_k.

The learning rate starts at 11 and falls linearly to 00; epochs number 500 if n≤10 000n \le 10\,000 and 200 otherwise. Per-epoch cost is proportional to mm times the number of edges, O(nkm)\bigO(nkm).

Spectral initialization

By default, umap-learn starts not from random points but from Laplacian eigenmaps of the fuzzy graph itself: eigenvectors 22 to p+1p + 1 of normalized Laplacian I−D−1/2MD−1/2\mat{I} - \mat{D}^{-1/2}\mat{M}\mat{D}^{-1/2}, where M=(μij)\mat{M} = (\mu_{ij}) and D=diag⁡(di)\mat{D} = \diag(d_i), rescaled so the maximum coordinate is 10 and with noise of standard deviation 10−410^{-4}. If the graph has multiple connected components, each is placed separately and their relative positions come from a separate calculation of inter-component distances. In the eigenmaps lesson you saw that the first Laplacian eigenvectors summarize coarse graph shape: this initialization brings global structure ready-made.

Lab: minimal UMAP from scratch

The first cell computes spectral initialization with eigsh (eigenvectors of D−1/2MD−1/2\mat{D}^{-1/2}\mat{M}\mat{D}^{-1/2} with largest eigenvalues have the smallest Laplacian eigenvalues) and fits aa and bb like umap-learn’s find_ab_params.

[ ]Spectral initialization and the a, b curveBrowser
from scipy.sparse import diags
from scipy.sparse.linalg import eigsh
from scipy.optimize import curve_fit

def init_espectral(mu, dim=2, seed=0):
    """Vectores propios 2..dim+1 del Laplaciano normalizado I - D^{-1/2} mu D^{-1/2}, escalados a coordenada máxima 10."""
    d = np.asarray(mu.sum(1)).ravel()
    Dm = diags(1 / np.sqrt(d))
    M = Dm @ mu @ Dm                    # mismos vectores propios que el Laplaciano normalizado
    vals, vecs = eigsh(M, k=dim + 1, which='LA', v0=np.ones(len(d)), tol=1e-8)
    orden = np.argsort(-vals)
    Y = vecs[:, orden[1:dim + 1]]
    Y = 10 * Y / np.abs(Y).max()
    return Y + np.random.default_rng(seed).normal(0, 1e-4, Y.shape), 1 - vals[orden]

def ajustar_ab(min_dist, spread=1.0):
    phi = lambda x, a, b: 1 / (1 + a * x ** (2 * b))
    x = np.linspace(0, 3 * spread, 300)
    psi = np.where(x < min_dist, 1.0, np.exp(-(x - min_dist) / spread))
    (a, b), _ = curve_fit(phi, x, psi)
    return a, b

Y0, lam = init_espectral(mu)
print("autovalores del Laplaciano normalizado:", np.round(lam, 4))
for md in [0.0, 0.1, 0.5, 0.99]:
    a, b = ajustar_ab(md)
    print(f"min_dist = {md:4}:  a = {a:.3f}, b = {b:.3f}")
a, b = ajustar_ab(0.1)

The first eigenvalue is 0 (the trivial eigenvector) and the next two are very small: the graph is well connected and its first two smooth coordinates provide initialization. With min_dist = 0.1, a=1.577a = 1.577, b=0.895b = 0.895, umap-learn’s values; with min_dist = 0.99, a=0.119a = 0.119 and b=1.916b = 1.916, a curve almost flat to 1 that falls quickly afterward.

The optimization loop follows umap-learn with one simplification: within each epoch, all scheduled edges are applied at once using np.bincount instead of sequentially. This makes the whole epoch a vectorized operation so the cell fits in the browser.

[ ]SGD with negative samplingBrowser
import time

def umap_sgd(mu, Y0, a, b, n_epochs=200, m=5, seed=0):
    """SGD con muestreo negativo como umap-learn, vectorizado por épocas (las aristas de una época se aplican a la vez)."""
    rng = np.random.default_rng(seed)
    G = mu.tocoo()
    G.data[G.data < G.data.max() / n_epochs] = 0.0     # poda de umap-learn
    G.eliminate_zeros()
    cab, col, w = G.row, G.col, G.data
    cada = w.max() / w                                   # épocas entre dos muestreos de cada arista
    proxima, proxima_neg = cada.copy(), cada / m
    Y, N = Y0.copy(), len(Y0)
    recorta = lambda g: np.clip(g, -4.0, 4.0)
    for ep in range(n_epochs):
        alfa = 1.0 - ep / n_epochs
        act = np.nonzero(proxima <= ep + 1)[0]
        i, j = cab[act], col[act]
        # atracción: -log Phi, mueve a los dos extremos
        dY = Y[i] - Y[j]
        s = (dY ** 2).sum(1)
        c = np.where(s > 0, -2 * a * b * s ** (b - 1) / (1 + a * s ** b), 0.0)
        g = recorta(c[:, None] * dY) * alfa
        for e in range(2):
            Y[:, e] += np.bincount(i, g[:, e], N) - np.bincount(j, g[:, e], N)
        proxima[act] += cada[act]
        # repulsión: m puntos al azar por arista, -log(1 - Phi), solo se mueve la cabeza
        nneg = ((ep + 1 - proxima_neg[act]) / (cada[act] / m)).astype(int)
        ii = np.repeat(i, nneg)
        kk = rng.integers(0, N, ii.size)
        dY = Y[ii] - Y[kk]
        s = (dY ** 2).sum(1)
        c = np.where(s > 0, 2 * b / ((0.001 + s) * (1 + a * s ** b)), 0.0)
        g = recorta(c[:, None] * dY) * alfa
        for e in range(2):
            Y[:, e] += np.bincount(ii, g[:, e], N)
        proxima_neg[act] += nneg * cada[act] / m
    return Y

t0 = time.perf_counter()
Y = umap_sgd(mu, Y0, a, b)
print(f"200 épocas en {time.perf_counter() - t0:.1f} s; aristas tras la poda: {(mu.data >= mu.data.max() / 200).sum() // 2}")

Evaluate using embedding quality metrics: trustworthiness T(10)T(10), the fraction of each point’s 10 neighbors that remain among its 10 neighbors in the plane, and, as a global measure, Spearman correlation between the 45 class-centroid distances in 64 dimensions and in the plane.

[ ]Evaluate the embeddingBrowser
import matplotlib.pyplot as plt
from scipy.stats import spearmanr
from scipy.spatial.distance import pdist
from sklearn.manifold import trustworthiness
from sklearn.decomposition import PCA

def vecinos_conservados(X, Y, k=10):
    _, a_ = vecinos(X, k + 1)
    _, b_ = vecinos(Y, k + 1)
    return np.mean([len(set(p) & set(q)) / k for p, q in zip(a_[:, 1:], b_[:, 1:])])

def global_centroides(X, Y, y):
    """Spearman entre las 45 distancias de centroides de clase en 64 dimensiones y en el plano."""
    cx = np.array([X[y == c].mean(0) for c in range(10)])
    cy = np.array([Y[y == c].mean(0) for c in range(10)])
    return spearmanr(pdist(cx), pdist(cy))[0]

Y_pca = PCA(2).fit_transform(X)
for nombre, Z in [("PCA", Y_pca), ("UMAP desde cero", Y)]:
    print(f"{nombre:16s} T(10) = {trustworthiness(X, Z, n_neighbors=10):.3f}   "
          f"vecinos conservados = {vecinos_conservados(X, Z):.3f}   global = {global_centroides(X, Z, y):.3f}")

plt.figure(figsize=(5, 4.5))
plt.scatter(Y[:, 0], Y[:, 1], c=y, cmap="tab10", s=4)
for c in range(10):
    plt.annotate(str(c), Y[y == c].mean(0), fontsize=12, weight="bold")
plt.xticks([]); plt.yticks([]); plt.title("UMAP desde cero: 1000 dígitos")
plt.show()

Our UMAP from scratch gives T(10)=0.989T(10) = 0.989 and retains 56.8% of 10 neighbors, versus 16.6% for PCA. It loses on the global measure: 0.602 versus PCA’s 0.719. (UMAP figures can vary in the second decimal across platforms: SGD amplifies eigsh rounding differences. Conclusions do not change.) This is not a coincidence of this run; the initialization section explains it. Now try starting from random points.

[ ]Same optimization, random initializationBrowser
Y_azar = umap_sgd(mu, np.random.default_rng(1).uniform(-10, 10, (n, 2)), a, b, seed=1)
for nombre, Z in [("init. espectral", Y), ("init. aleatoria", Y_azar)]:
    print(f"{nombre:16s} T(10) = {trustworthiness(X, Z, n_neighbors=10):.3f}   "
          f"vecinos conservados = {vecinos_conservados(X, Z):.3f}   global = {global_centroides(X, Z, y):.3f}")

Local structure barely changes (T=0.988T = 0.988, 56.0% of neighbors), but global correlation falls from 0.602 to 0.245. Remember the pattern: the algorithm decides who is near whom; initialization decides where each group ends up.

Comparison with reference implementations

The next cell needs umap-learn and openTSNE (pip install umap-learn opentsne) and runs on your computer. It combines the pieces above into a function with 500 epochs, as umap-learn does for n≤10 000n \le 10\,000, and compares it with umap-learn, openTSNE and PCA on the 1797 digits, using the same seeds. It adds accuracy of a 10-neighbor classifier on the embedding (5-fold cross-validation).

[ ]Our UMAP versus umap-learn and openTSNELocal GPU
import time, warnings
import numpy as np
import umap
from openTSNE import TSNE
from scipy.sparse import csr_matrix, diags
from scipy.sparse.csgraph import connected_components
from scipy.sparse.linalg import eigsh
from scipy.optimize import curve_fit
from scipy.spatial.distance import pdist
from scipy.stats import spearmanr
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.manifold import trustworthiness
from sklearn.model_selection import cross_val_score
from sklearn.neighbors import KNeighborsClassifier, NearestNeighbors
warnings.filterwarnings("ignore")

def umap_desde_cero(X, k=15, min_dist=0.1, n_epochs=500, m=5, seed=0):
    """Las piezas del laboratorio del navegador en una sola función (k vecinos exactos)."""
    n = len(X)
    dist, idx = NearestNeighbors(n_neighbors=k).fit(X).kneighbors(X)
    rho = dist[:, 1]
    delta = np.maximum(dist[:, 1:] - rho[:, None], 0.0)
    lo, hi, sig = np.zeros(n), np.full(n, np.inf), np.ones(n)
    for _ in range(64):
        s = np.exp(-delta / sig[:, None]).sum(1)
        g = s > np.log2(k)
        hi, lo = np.where(g, sig, hi), np.where(g, lo, sig)
        sig = np.where(np.isinf(hi), 2 * sig, (lo + hi) / 2)
    A = csr_matrix((np.exp(-delta / sig[:, None]).ravel(), (np.repeat(np.arange(n), k - 1), idx[:, 1:].ravel())), shape=(n, n))
    mu = (A + A.T - A.multiply(A.T)).tocsr()
    d = np.asarray(mu.sum(1)).ravel()
    Dm = diags(1 / np.sqrt(d))
    vals, vecs = eigsh(Dm @ mu @ Dm, k=3, which="LA", v0=np.ones(n), tol=1e-8)
    Y = vecs[:, np.argsort(-vals)[1:3]]
    rng = np.random.default_rng(seed)
    Y = 10 * Y / np.abs(Y).max() + rng.normal(0, 1e-4, (n, 2))
    x = np.linspace(0, 3, 300)
    (a, b), _ = curve_fit(lambda x, a, b: 1 / (1 + a * x ** (2 * b)), x, np.where(x < min_dist, 1.0, np.exp(-(x - min_dist))))
    G = mu.tocoo()
    G.data[G.data < G.data.max() / n_epochs] = 0.0
    G.eliminate_zeros()
    cab, col, w = G.row, G.col, G.data
    cada = w.max() / w
    prox, prox_neg = cada.copy(), cada / m
    for ep in range(n_epochs):
        alfa = 1.0 - ep / n_epochs
        act = np.nonzero(prox <= ep + 1)[0]
        i, j = cab[act], col[act]
        dY = Y[i] - Y[j]
        s = (dY ** 2).sum(1)
        c = np.where(s > 0, -2 * a * b * s ** (b - 1) / (1 + a * s ** b), 0.0)
        gr = np.clip(c[:, None] * dY, -4, 4) * alfa
        for e in range(2):
            Y[:, e] += np.bincount(i, gr[:, e], n) - np.bincount(j, gr[:, e], n)
        prox[act] += cada[act]
        nneg = ((ep + 1 - prox_neg[act]) / (cada[act] / m)).astype(int)
        ii = np.repeat(i, nneg)
        kk = rng.integers(0, n, ii.size)
        dY = Y[ii] - Y[kk]
        s = (dY ** 2).sum(1)
        c = np.where(s > 0, 2 * b / ((0.001 + s) * (1 + a * s ** b)), 0.0)
        gr = np.clip(c[:, None] * dY, -4, 4) * alfa
        for e in range(2):
            Y[:, e] += np.bincount(ii, gr[:, e], n)
        prox_neg[act] += nneg * cada[act] / m
    return Y

def medidas(X, y, Z, k=10):
    a_ = NearestNeighbors(n_neighbors=k + 1).fit(X).kneighbors(X, return_distance=False)[:, 1:]
    b_ = NearestNeighbors(n_neighbors=k + 1).fit(Z).kneighbors(Z, return_distance=False)[:, 1:]
    vec = np.mean([len(set(p) & set(q)) / k for p, q in zip(a_, b_)])
    cx = np.array([X[y == c].mean(0) for c in range(10)])
    cz = np.array([Z[y == c].mean(0) for c in range(10)])
    acc = cross_val_score(KNeighborsClassifier(10), Z, y, cv=5).mean()
    return trustworthiness(X, Z, n_neighbors=k), vec, acc, spearmanr(pdist(cx), pdist(cz))[0]

X, y = load_digits(return_X_y=True)
X = X.astype(float)
metodos = {
    "PCA": lambda: PCA(2).fit_transform(X),
    "UMAP desde cero": lambda: umap_desde_cero(X),
    "umap-learn": lambda: umap.UMAP(random_state=0).fit_transform(X),
    "openTSNE": lambda: np.asarray(TSNE(random_state=0, n_jobs=1).fit(X)),
}
print(f"{'método':16s} {'T(10)':>6s} {'vecinos':>8s} {'10-NN':>6s} {'global':>7s}")
for nombre, f in metodos.items():
    T, v, acc, g = medidas(X, y, f())
    print(f"{nombre:16s} {T:6.3f} {v:8.3f} {acc:6.3f} {g:7.3f}")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
methodT(10)T(10)neighbors retained10-NNglobal
PCA0.8300.1180.6130.815
UMAP from scratch0.9880.4930.9780.554
umap-learn0.9890.4910.9780.576
openTSNE0.9920.5890.9730.819

Our implementation matches umap-learn on all four measures within 0.02: applying each epoch’s edges at once and the other simplifications do not change the result. (Below 4096 points umap-learn also computes exact neighbors; above that it uses NN-descent, an approximate search.) Two interesting differences are in the last row. openTSNE retains more neighbors (0.589 versus 0.491), exactly as the next section’s spectrum predicts: more repulsion, better local neighborhoods. It also preserves class arrangement much better (0.819 versus 0.576), contrary to the methods’ reputations. The reason is that openTSNE defaults to PCA initialization, and PCA alone already gives 0.815 on this measure: the initialization section returns to this.

The two parameters that matter: n_neighbors and min_dist

In practice UMAP has two main knobs. n_neighbors changes the graph: how many neighbors each point considers and therefore the scale at which “neighborhood” is defined. min_dist changes only the plane’s curve. The interactive below separates their effects with actual umap-learn embeddings on three datasets.

Interactiven_neighbors and min_dist
3D data (oblique view)
UMAP with n_neighbors = 15 and min_dist = 0.1
  • spiral start
  • middle
  • end
Local: neighbors preserved (rows min_dist, columns n_neighbors)
35155015000.10.50.990.610.620.630.630.720.730.780.800.760.790.840.860.760.780.750.680.760.720.690.64
Global: Spearman correlation
35155015000.10.50.990.120.090.150.160.730.810.630.650.870.790.790.760.250.230.250.170.210.230.230.22
Data
15
0.1
Neighbors preserved (10)0.793
Spearman versus unrolled coordinates0.792
Graph components1
At k = 3 the graph and embedding split into dozens of pieces. With 5–15 neighbors UMAP unrolls the sheet (high correlation with unrolled coordinates). At 50 or more, shortcuts connect roll layers and global structure is lost: more neighbors do not mean more global structure under sparse sampling.
Precomputed umap-learn embeddings (spectral initialization, random_state = 0) for 5 n_neighbors and 4 min_dist values, rotated to keep orientation fixed. The two tables summarize 20 combinations: left, a local measure (neighbors retained); right, a global one (Spearman distance correlation). Start with the Swiss roll and vary n_neighbors: with 3 neighbors the graph has 28 components; between 5 and 15 the sheet unrolls; with 50 or more the graph joins roll layers and global correlation falls to 0.17–0.25. Switch to the clouds and inspect the size ratio between dense and sparse groups. On digits, move only min_dist: does which classes are together change?

Three takeaways, all using the interactive’s figures:

  • Small n_neighbors fragments. With k=3k = 3, the Swiss-roll graph has 28 components and digits have 12. UMAP has no force pulling distinct components together, so pieces remain wherever initialization leaves them.
  • Large n_neighbors is not simply “more global.” On digits global correlation rises monotonically with kk (0.22 to 0.53 with min_dist = 0.1) while neighbors retained fall from their maximum at k=15k = 15. On the 400-point Swiss roll, however, k≥50k \ge 50 introduces shortcuts between layers and correlation with unrolled coordinates falls from 0.79 to 0.23: neighborhood scale now exceeds layer separation.
  • min_dist does not move the graph. With the same neighbors, groups tighten or expand, but who is next to whom does not change. In the clouds, the dense group’s radius is 0.30 times the sparse group’s, and in the embedding that ratio is 0.46 to 0.91 for every k≥5k \ge 5: UMAP equalizes densities, a direct consequence of each point measuring with its own σi\sigma_i.

What is actually optimized: the effective loss

Negative sampling looks like an innocent estimator of the gradient of CC. It is not: it distributes repulsion with weights unrelated to 1−μij1 - \mu_{ij}. Damrich and Hamprecht (2021) worked out the calculation.

Counting updates

Normalize epochs so each directed edge (i,j)(i, j) is processed in expectation μij/μmax⁡\mu_{ij}/\mu_{\max} times per epoch.

  • Attraction. Edge (i,j)(i, j) and its twin (j,i)(j, i) both move both endpoints, so in one epoch each point of pair {i,j}\{i, j\} receives an expected 2μij/μmax⁡2\mu_{ij}/\mu_{\max} attraction steps: on average, one step along the gradient of 2μij(−log⁡νij)/μmax⁡2\mu_{ij}\big(-\log\nu_{ij}\big)/\mu_{\max}.
  • Repulsion. Every time an edge headed by ii is processed, mm uniform points are selected. The expected number of times a particular kk repels ii in an epoch is ∑j(μij/μmax⁡)(m/n)=dim/(nμmax⁡)\sum_j (\mu_{ij}/\mu_{\max})(m/n) = d_i m/(n\mu_{\max}), independent of μik\mu_{ik}. Symmetrically, ii repels kk an expected dkm/(nμmax⁡)d_k m/(n\mu_{\max}) times.

If each negative sample also pushed yk\vb{y}_k (a correction proposed by the authors), pair {i,k}\{i, k\} would receive (di+dk)m/(nμmax⁡)(d_i + d_k)m/(n\mu_{\max}) repulsion steps on both points, and the expected update would be exactly the gradient of a loss writable in closed form:

The contrast with nominal loss lies in repulsion weight: 1−μij1 - \mu_{ij} versus rij=(di+dj)m/2nr_{ij} = (d_i + d_j)m/2n. Three consequences:

  1. Target similarities become binary. Repeating the isolated-pair calculation with h(ν)=−μlog⁡ν−rlog⁡(1−ν)h(\nu) = -\mu\log\nu - r\log(1 - \nu) gives optimum ν∗=μ/(μ+r)\nu^* = \mu/(\mu + r). Since rr is of order dˉm/n\bar d m/n, tiny for large nn, ν∗≈1\nu^* \approx 1 for every edge with μij>0\mu_{ij} > 0, however small, and ν∗=0\nu^* = 0 for nonedges. UMAP does not attempt to reproduce μij\mu_{ij} but the binary neighbor graph symmetrized by union.
  2. Total repulsion is mm times attraction, regardless of nn. Summing, ∑i<j(di+dj)=(n−1)∑idi=2(n−1)∑i<jμij\sum_{i<j}(d_i + d_j) = (n - 1)\sum_i d_i = 2(n - 1)\sum_{i<j}\mu_{ij}, so total effective repulsion is mn−1n∑i<jμij≈m×m\frac{n-1}{n}\sum_{i<j}\mu_{ij} \approx m \times (total attraction). The nominal sum, ∑i<j(1−μij)\sum_{i<j}(1 - \mu_{ij}), is of order n2/2n^2/2: their ratio grows like n/(mdˉ)n/(m\bar d).
  3. This is why UMAP compacts groups. With much less repulsion than nominal, attraction wins and groups tighten. This is the same direction as multiplying t-SNE’s attraction: the next section turns it into a spectrum.

Damrich and Hamprecht measured this on C. elegans data: mean 1−μij1 - \mu_{ij} was 0.9999, whereas the largest effective repulsion weight was 0.0043, and nominal repulsive loss was two orders of magnitude larger than actual.

Check: count the updates

The cell traverses umap_sgd’s sampling schedule without moving anything and counts, for each pair, how many attraction and repulsion steps would be applied.

[ ]Counting negative-sampling updatesBrowser
def contar(mu, n_epochs=200, m=5, seed=0):
    """Cuenta, sin mover nada, las atracciones y repulsiones que reparte el programa de muestreo de umap_sgd."""
    rng = np.random.default_rng(seed)
    G = mu.tocoo()
    cab, col, w = G.row, G.col, G.data
    cada = w.max() / w
    proxima, proxima_neg = cada.copy(), cada / m
    N = mu.shape[0]
    claves_atr, claves_rep = [], []
    for ep in range(n_epochs):
        act = np.nonzero(proxima <= ep + 1)[0]
        i = cab[act]
        claves_atr.append(i * N + col[act])                  # arista dirigida (i, j): mueve a i y a j
        proxima[act] += cada[act]
        nneg = ((ep + 1 - proxima_neg[act]) / (cada[act] / m)).astype(int)
        ii = np.repeat(i, nneg)
        claves_rep.append(ii * N + rng.integers(0, N, ii.size))   # k empuja a i
        proxima_neg[act] += nneg * cada[act] / m
    atr = np.bincount(np.concatenate(claves_atr), minlength=N * N).reshape(N, N)
    rep = np.bincount(np.concatenate(claves_rep), minlength=N * N).reshape(N, N)
    return atr + atr.T, rep + rep.T     # por par no ordenado {i, k}, sumando las dos direcciones

atr, rep = contar(mu)
mu_d = mu.toarray()
arista = np.triu(mu_d > 0, 1)
no_arista = np.triu(mu_d == 0, 1)
print(f"repulsiones totales / atracciones totales = {rep[arista | no_arista].sum() / atr[arista].sum():.2f}   (m = 5)")
print(f"lo que pide la pérdida nominal: sum(1 - mu) / sum(mu) = {(1 - mu_d)[arista | no_arista].sum() / mu_d[arista].sum():.0f}")
fuerte = arista & (mu_d > 0.9)
debil = arista & (mu_d < 0.1)
for nombre, msk in [("aristas con mu > 0.9", fuerte), ("aristas con mu < 0.1", debil), ("pares sin arista", no_arista)]:
    print(f"{nombre:22s} atracciones medias {atr[msk].mean():7.2f}   repulsiones medias {rep[msk].mean():5.2f}")
r_esp = 200 * 5 * (grado[:, None] + grado[None, :]) / (n * mu.data.max())
print(f"repulsiones esperadas por par, T m (d_i + d_k)/(n mu_max): media {r_esp[no_arista].mean():.2f}")

A pair’s attraction steps are proportional to μij\mu_{ij}: about 397 for edges with μ>0.9\mu > 0.9 and 25 for those with μ<0.1\mu < 0.1. Repulsion steps are practically the same for all (13.30, 12.87 and 12.30), as predicted by Tm(di+dk)/(nμmax⁡)T m(d_i + d_k)/(n\mu_{\max}) with T=200T = 200 epochs, whose mean is 12.41 (edges have slightly more because their endpoints have greater degree): negative sampling knows nothing about μ\mu. In total, repulsion is 4.98 times attraction, whereas nominal loss would require 160 times more.

Measured in umap-learn

The local cell makes the same comparison with the real implementation on the 1797 digits: it measures νij\nu_{ij} of umap-learn’s final embedding on each graph edge.

[ ]Effective loss measured in umap-learnLocal GPU
r = umap.UMAP(random_state=0).fit(X)
G = r.graph_.tocoo()
a, b = r._a, r._b
sup = G.row < G.col
i, j, mu = G.row[sup], G.col[sup], G.data[sup]
d = np.asarray(r.graph_.sum(1)).ravel()
n, m = len(X), 5
nu = 1 / (1 + a * ((r.embedding_[i] - r.embedding_[j]) ** 2).sum(1) ** b)
rep = (d[i] + d[j]) * m / (2 * n)
print(f"n = {n}, aristas = {len(mu)}, grado difuso: mediana {np.median(d):.2f}, media {d.mean():.2f}")
print(f"mediana de mu en las aristas: {np.median(mu):.3f};  de nu: {np.median(nu):.3f};  de nu* = mu/(mu + r): {np.median(mu / (mu + rep)):.3f}")
print(f"aristas con mu > 0.5: {100 * (mu > 0.5).mean():.1f} %;  con nu > 0.5: {100 * (nu > 0.5).mean():.1f} %")
print(f"peso repulsivo efectivo r_ij: mediana {np.median(rep):.4f}, máximo {rep.max():.4f}")
atr_total = mu.sum()
rep_nominal = n * (n - 1) / 2 - atr_total
rep_efectiva = m * (n - 1) / (2 * n) * d.sum()
print(f"sum mu = {atr_total:.0f};  repulsión nominal sum(1 - mu) = {rep_nominal:.0f};  efectiva = {rep_efectiva:.0f}")
print(f"nominal / efectiva = {rep_nominal / rep_efectiva:.0f};  efectiva / atracción = {rep_efectiva / atr_total:.2f}")
print(f"correlación de Spearman entre mu y nu en las aristas: {spearmanr(mu, nu)[0]:.2f}")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The graph of 1797 digits has 17,118 edges and median fuzzy degree 5.93. On edges, median μij\mu_{ij} is 0.218 and final similarity νij\nu_{ij} is 0.876: only 21.2% of edges have μ>0.5\mu > 0.5, but 90.5% end with ν>0.5\nu > 0.5. The effective-loss optimum ν∗=μ/(μ+r)\nu^* = \mu/(\mu + r) has median 0.924, much closer to measurement than the nominal ν=μ\nu = \mu; Spearman correlation between μ\mu and ν\nu is only 0.44. Effective repulsion weights have median 0.0181 and maximum 0.0367, versus 1−μij≈11 - \mu_{ij} \approx 1 for nearly all pairs. In total, nominal repulsion (1,608,059) is 57 times effective (28,218), and effective is 5.00 times attraction (5647), exactly mm.

InteractiveThe loss actually optimized
Full gradient of effective loss with m=5m = 5 (500 digits, a=b=1a = b = 1)
  • 0
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
View
Repulsion
5
Total attraction ∑i<jμij\sum_{i<j}\mu_{ij}…
Total repulsion ∑i<jrij\sum_{i<j} r_{ij}…
Repulsion / attraction…
Iteration0 / 500
Class separation…
Neighbors preserved (10)…
With negative sampling, total repulsion is almost exactly mm times attraction regardless of nn. With little repulsion classes compact; for large mm the result approaches nominal loss.
In 'Simulation', 500 digits and their fuzzy graph with k=15k = 15 are optimized by full gradient descent (no sampling, a=b=1a = b = 1) with nominal repulsion 1−μ1 - \mu or effective repulsion (di+dj)m/2n(d_i + d_j)m/2n. Readouts compare total repulsion with total attraction and finally measure class separation and neighbors retained. Toggle the two repulsions; then vary mm from 1 to 100: at which mm does effective resemble nominal? In 'Measured in umap-learn', each point is an edge from a real run on the 1797 digits: if UMAP optimized nominal loss, they would lie on the diagonal.

In simulation, with m=5m = 5 total repulsion is 4.99 times attraction and with nominal repulsion 80.3 times: 16 times more with only 500 points. Classes are more separated with effective loss (separation about 7 versus about 5 with nominal), and more still with m=1m = 1 (about 11); with m=50m = 50 (about 5.6) the result already resembles nominal loss. Neighbors retained barely change (0.69 to 0.72): the force balance moves group separation, not local neighborhoods. (Optimization amplifies rounding differences, so your browser may differ in the second decimal of these final readouts; total weights are exact.)

The attraction–repulsion spectrum

t-SNE with exaggeration

In t-SNE, early exaggeration multiplies pijp_{ij} by a factor during initial iterations. Böhm, Berens and Kobak maintain a factor ρ\rho throughout optimization and see what happens. With wij=1/(1+∥yi−yj∥2)w_{ij} = 1/(1 + \norm{\vb{y}_i - \vb{y}_j}^2), Z=∑k≠lwklZ = \sum_{k \neq l} w_{kl} and qij=wij/Zq_{ij} = w_{ij}/Z, the gradient of

Lρ(Y)=−ρ∑i≠jpijlog⁡wij+log⁡ZL_\rho(\mat{Y}) = -\rho\sum_{i \neq j} p_{ij}\log w_{ij} + \log Z

is

∇yiLρ=4∑j(ρ pij−qij) wij (yi−yj).\grad_{\vb{y}_i} L_\rho = 4\sum_{j}\big(\rho\, p_{ij} - q_{ij}\big)\, w_{ij}\,(\vb{y}_i - \vb{y}_j).

With ρ=1\rho = 1, L1L_1 is t-SNE’s KL up to a constant. The first term is attraction along graph edges and the second repulsion among all pairs: multiplying attraction by ρ\rho is equivalent to dividing repulsion by ρ\rho.

Böhm and coauthors describe that attraction–repulsion spectrum using four landmarks. ρ=1\rho = 1 is t-SNE: discrete, well-separated groups. Around ρ≈4\rho \approx 4 the result resembles UMAP (their greatest distance correlation with UMAP occurred at 4≤ρ<154 \le \rho < 15 on most datasets). Around ρ≈30\rho \approx 30 it resembles ForceAtlas2, a graph-drawing algorithm. As ρ→∞\rho \to \infty it reaches Laplacian eigenmaps. Along the spectrum strong repulsion gives more discrete groups and better neighbor preservation; strong attraction gives more continuous, elongated manifolds. On MNIST (n=70 000n = 70\,000), fraction of 15 neighbors retained fell from 0.34 at ρ=1\rho = 1 to 0.12 at ρ=4\rho = 4 and 0.06 at ρ=30\rho = 30. Their explanation for UMAP falling near ρ≈4\rho \approx 4 is the previous section’s: negative sampling greatly reduces effective repulsion.

The infinite-attraction limit

Why Laplacian eigenmaps? When ρ\rho is large, attraction contracts the cloud; as it becomes very small, all wij→1w_{ij} \to 1 and Z→n(n−1)Z \to n(n - 1). Linearizing the gradient (with centered cloud, ∑jyj=0\sum_j \vb{y}_j = \vb{0}),

∇yiLρ  ≈  4ρ∑jpij(yi−yj)−4n(n−1)∑j(yi−yj)=4[ρ (LPY)i−1n−1yi],\grad_{\vb{y}_i} L_\rho \;\approx\; 4\rho\sum_j p_{ij}(\vb{y}_i - \vb{y}_j) - \frac{4}{n(n-1)}\sum_j(\vb{y}_i - \vb{y}_j) = 4\big[\rho\,(\mat{L}_P\mat{Y})_i - \tfrac{1}{n-1}\vb{y}_i\big],

with LP=diag⁡(P1)−P\mat{L}_P = \diag(P\vb{1}) - P the affinity-graph Laplacian. With simple gradient descent and rate η\eta, one step multiplies the component of Y\mat{Y} along an eigenvector v\vb{v} of LP\mat{L}_P with eigenvalue λ\lambda by 1−4η(ρλ−1/(n−1))1 - 4\eta(\rho\lambda - 1/(n-1)). That component contracts if ρλ>1/(n−1)\rho\lambda > 1/(n - 1) (and the step is not so long as to make it oscillate) and grows if ρλ<1/(n−1)\rho\lambda < 1/(n - 1), until the cloud is no longer small and linearization no longer holds. Thus:

  • If the graph is connected and ρ>ρc=1/((n−1)λ2)\rho > \rho_c = 1/\big((n - 1)\lambda_2\big), with λ2\lambda_2 the smallest nonzero eigenvalue, all directions contract (the eigenvalue 00 direction, the constant vector, is a translation removed by centering) and the cloud collapses toward a point. The slowest-contracting directions have the smallest eigenvalues: what remains, rescaled, are the first nontrivial eigenvectors of the affinity Laplacian, namely Laplacian eigenmaps.
  • If ρ\rho lies between 1/((n−1)λ3)1/((n - 1)\lambda_3) and 1/((n−1)λ2)1/((n - 1)\lambda_2), the λ3\lambda_3 direction contracts and the λ2\lambda_2 direction does not: the embedding becomes one-dimensional.

This is the same idea Linderman and Steinerberger (2019) used to analyze early exaggeration: with negligible repulsion, gradient descent acts like power iteration on the Laplacian. The cell computes thresholds for the 500 digits in the interactive below (the first 50 of each class, perplexity 30).

[ ]The collapse thresholdBrowser
# Los 500 dígitos del interactivo del espectro: los 50 primeros de cada clase.
sel = np.concatenate([np.nonzero(y_all == c)[0][:50] for c in range(10)])
X5 = X_all[sel].astype(float)
n5 = len(X5)
sq5 = (X5 ** 2).sum(1)
D2 = np.maximum(sq5[:, None] + sq5[None, :] - 2 * X5 @ X5.T, 0.0)

def afinidades_tsne(D2, perp=30.0, iters=100):
    """p_{j|i} con perplejidad dada (bisección en beta, vectorizada) y P simétrica de t-SNE."""
    N = len(D2)
    Dm = D2 + np.diag(np.full(N, np.inf))
    Dm = Dm - Dm.min(1, keepdims=True)
    lo, hi, beta = np.zeros(N), np.full(N, np.inf), np.ones(N)
    for _ in range(iters):
        Pc = np.exp(-Dm * beta[:, None])
        s = Pc.sum(1)
        H = np.log(s) + beta * (np.where(np.isinf(Dm), 0, Dm) * Pc).sum(1) / s
        alta = H > np.log(perp)        # entropía alta: núcleo demasiado ancho, sube beta
        lo = np.where(alta, beta, lo)
        hi = np.where(alta, hi, beta)
        beta = np.where(np.isinf(hi), 2 * beta, (lo + hi) / 2)
    Pc = Pc / Pc.sum(1, keepdims=True)
    return (Pc + Pc.T) / (2 * N)

P5 = afinidades_tsne(D2)
L5 = np.diag(P5.sum(1)) - P5
lam5 = np.linalg.eigvalsh(L5)
print("autovalores más pequeños del Laplaciano de P:", lam5[:4])
for t in (1, 2):
    print(f"rho_c con lambda_{t + 1}: 1/((n - 1) lambda) = {1 / ((n5 - 1) * lam5[t]):.1f}")

With λ2≈8.18×10−5\lambda_2 \approx 8.18 \times 10^{-5} and λ3≈9.71×10−5\lambda_3 \approx 9.71 \times 10^{-5}, thresholds are ρ≈24.5\rho \approx 24.5 and ρ≈20.6\rho \approx 20.6. Check the interactive: at ρ=24\rho = 24 the embedding is a nearly one-dimensional curve, and at ρ=30\rho = 30 scale falls to around 10−2610^{-26}. The threshold depends on data through (n−1)λ2(n - 1)\lambda_2: on MNIST, with n=70 000n = 70\,000, it must exceed 30 because Böhm and coauthors show uncollapsed embeddings at ρ=30\rho = 30.

InteractiveA continuum of embeddings
t-SNE with ρ=1\rho = 1 (optimizing…)
UMAP (umap-learn)
Laplacian eigenmaps
  • 0
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
Readouts versus ρ\rho (logarithmic scale), one mark per completed run
0.000.250.500.751.001241030100collapse
  • neighbors preserved (15)
  • correlation with UMAP
  • correlation with eigenmaps
1
Iteration0 / 750
Neighbors preserved (15)…
Distance correlation with UMAP…
Correlation with eigenmaps…
Scale (maximum coordinate)…
Exact t-SNE running in your browser on 500 digits (perplexity 30, PCA initialization, 250 early-exaggeration iterations and 500 with ρ\rho). Right, references: umap-learn UMAP (also PCA initialized) and Laplacian eigenmaps of the 15-neighbor graph. Each completed run leaves three marks on the lower graph: neighbors retained and distance correlations with UMAP and eigenmaps. Start at ρ=1\rho = 1 and sweep: over what range of ρ\rho is it most like UMAP? What happens to neighbor preservation? Move from 20 to 24 to 30 and compare with thresholds calculated in the cell.

On this small dataset the spectrum retains the paper’s features, though less clearly. Distance correlation with UMAP stays high, 0.82 to 0.85, throughout 1≤ρ≤41 \le \rho \le 4, then falls (0.79 at ρ=6\rho = 6, 0.73 at ρ=8\rho = 8): UMAP resembles moderately exaggerated t-SNE and stops resembling it once attraction dominates. Within that interval the exact maximum is unreliable. Small-ρ\rho runs are most sensitive to rounding, because pure t-SNE has many local minima: with the same code, the maximum occurred at ρ=1.5\rho = 1.5 in Chrome and ρ=4\rho = 4 in Node, whereas from ρ=3\rho = 3 the runs agree to the third digit. The rest is robust. Correlation with eigenmaps rises almost uninterrupted from about 0.56 at ρ=1\rho = 1 to 0.855 at ρ=20\rho = 20, just below the first threshold. Neighbors retained fall from 0.74 to 0.58 over that interval; UMAP retains 0.701, t-SNE’s level between ρ=1.5\rho = 1.5 and ρ=2\rho = 2. At ρ=24\rho = 24 the embedding is nearly a line and retains only 32% of neighbors; at ρ≥30\rho \ge 30 everything contracts toward a point. Beyond the thresholds the result is not a useful embedding: it is the collapse predicted by linearization.

Global structure depends primarily on initialization

In 2019 Becht and coauthors compared t-SNE and UMAP on single-cell data and concluded UMAP preserved global structure better and was more reproducible. Kobak and Linderman (2021) repeated the comparison on the same three datasets (320,000 to 820,000 cells) and observed that Becht and coauthors had run t-SNE with random initialization and UMAP with its default spectral initialization. They added randomly initialized UMAP and PCA-initialized t-SNE. With the same random initialization, both preserved global structure poorly (measured as Pearson correlation between pairwise distances in original space and embedding); with informative initialization, both preserved it similarly. Their conclusion: the advantage came entirely from initialization, and the practical lesson is to avoid random initialization. This textbook example shows why claims based on plots need metrics and a controlled comparison: changing two things at once (algorithm and initialization) and attributing the effect to one.

The mechanism is that of the whole lesson. Attraction acts only on neighbor-graph edges, and between groups without edges the only force is repulsion that vanishes as a power of distance when they are far apart (both forces in the proof exercise decay as s−2s^{-2} per pair). Nothing in the loss says where one group should lie relative to a distant one, so the optimizer largely preserves initial arrangement. The cell takes this to an extreme: 12 Gaussian groups in R50\R^{50} with centers on a planar curve and separated enough that the neighbor graph does not join them.

[ ]Initialization determines global structureLocal GPU
rng = np.random.default_rng(0)
K, por_grupo, D = 12, 150, 50
Q, _ = np.linalg.qr(rng.standard_normal((D, D)))
t = np.arange(K, dtype=float)
centros = np.c_[12 * t, 30 * np.sin(t / 2.2)] @ Q[:2]          # una curva plana dentro de R^50
Xg = np.concatenate([c + rng.standard_normal((por_grupo, D)) for c in centros])
lab = np.repeat(np.arange(K), por_grupo)

def global_grupos(Z):
    cz = np.array([Z[lab == g].mean(0) for g in range(K)])
    return spearmanr(pdist(cz), pdist(centros))[0]

ncomp = connected_components(NearestNeighbors(n_neighbors=15).fit(Xg).kneighbors_graph(Xg), directed=False)[0]
pca = PCA(2).fit_transform(Xg)
print(f"componentes conexas del grafo de 15 vecinos: {ncomp};  PCA sola: global = {global_grupos(pca):.3f}")
variantes = {
    "UMAP, init. espectral": lambda s: umap.UMAP(random_state=s).fit_transform(Xg),
    "UMAP, init. PCA": lambda s: umap.UMAP(random_state=s, init=10 * pca / np.abs(pca).max()).fit_transform(Xg),
    "UMAP, init. aleatoria": lambda s: umap.UMAP(random_state=s, init="random").fit_transform(Xg),
    "t-SNE, init. PCA": lambda s: np.asarray(TSNE(random_state=s, initialization="pca", n_jobs=1).fit(Xg)),
    "t-SNE, init. aleatoria": lambda s: np.asarray(TSNE(random_state=s, initialization="random", n_jobs=1).fit(Xg)),
}
for nombre, f in variantes.items():
    g = [global_grupos(f(s)) for s in range(3)]
    print(f"{nombre:24s} global (3 semillas) = {np.round(g, 3)}   media {np.mean(g):.3f}")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The 15-neighbor graph has 12 connected components, one per group, and PCA alone perfectly preserves center order (Spearman correlation 1.000 among 66 centroid distances). With random initialization both methods lose all global information: averages −0.055 (UMAP) and −0.032 (t-SNE) over three seeds. With the same PCA initialization, both retain a similar portion: 0.609 for UMAP and 0.593 for t-SNE. This is Kobak and Linderman’s result at lab scale. Optimization undoes some initial ordering as groups separate and has no force to restore it: there are no inter-group edges.

The most striking row is UMAP with default spectral initialization: −0.076. With 12 components, Laplacian eigenvectors say nothing about where each group goes (each component contributes its own zero eigenvalue), and umap-learn’s separate placement does not recover the order. Spectral initialization is informative when the graph is connected, as with digits; when it is not, PCA initialization is the safe choice (init= accepts an array).

Parametric UMAP

A network instead of a coordinate table

UMAP, like t-SNE, is nonparametric: it optimizes the nn coordinates yi\vb{y}_i, and no function maps a new point to the plane. umap-learn offers transform, which finds the new point’s training neighbors, calculates weights, and optimizes its position with other points fixed: it works, but costs a neighbor search and a small optimization for every batch of new points.

The alternative is a parametric embedding: choose a family of functions fθ:Rd→Rpf_\theta: \R^d \to \R^p, normally a neural network, set yi=fθ(xi)\vb{y}_i = f_\theta(\vb{x}_i), and minimize the same loss over θ\theta. The idea is old: van der Maaten applied it to t-SNE in 2009 with a deep network. Sainburg, McInnes and Gentner (2021) applied it to UMAP. UMAP’s loss sums over edges and negative pairs, so it trains with mini-batches like any network: sample edges with probability proportional to μij\mu_{ij}, take mm negatives per edge, compute −log⁡ν-\log\nu on positives and −log⁡(1−ν)-\log(1 - \nu) on negatives, and take an Adam step. This is the usual training loop with an unsupervised loss, and PyTorch code follows the correspondence between mathematics and framework from the neural-network lesson.

What is gained:

  • Embedding new points is a forward pass. Sainburg and coauthors describe nonparametric t-SNE and UMAP embeddings of new data as several orders of magnitude slower than parametric ones.
  • Other losses can be added. A decoder with reconstruction loss (a UMAP-regularized autoencoder), classification loss with few labels, or global-structure loss: the authors propose maximizing Pearson correlation between data and embedding distances within each batch.

Their numbers show that, with the same loss, the network loses little. Two-dimensional trustworthiness, calculated on 10,000 training points, was 0.9573 for parametric versus 0.9601 for original UMAP on MNIST, and 0.9733 versus 0.9777 on Fashion-MNIST.

Lab: parametric UMAP in PyTorch

The cell trains a perceptron with three 256-unit hidden layers on the GPU on 75% of the digits (1347), using umap-learn’s fuzzy graph and m=5m = 5 uniform negatives per edge, for 10,000 steps with batches of 512 edges. It then embeds the remaining 25% (450 never-seen digits) with one network pass and compares with umap-learn’s transform. This is small training: network, graph and data fit easily on any GPU, and it also works more slowly on CPU.

[ ]Parametric UMAP in PyTorchLocal GPU
import torch
from sklearn.model_selection import train_test_split
from umap.umap_ import fuzzy_simplicial_set, find_ab_params

Xn = X / 16.0
Xtr, Xte, ytr, yte = train_test_split(Xn, y, test_size=0.25, random_state=0, stratify=y)
G, _, _ = fuzzy_simplicial_set(Xtr, n_neighbors=15, random_state=np.random.RandomState(0), metric="euclidean")
G = G.tocoo()
dev = "cuda" if torch.cuda.is_available() else "cpu"
cab = torch.tensor(G.row, dtype=torch.long, device=dev)
col = torch.tensor(G.col, dtype=torch.long, device=dev)
peso = torch.tensor(G.data, dtype=torch.float32, device=dev)
a, b = find_ab_params(1.0, 0.1)
Xt = torch.tensor(Xtr, dtype=torch.float32, device=dev)

torch.manual_seed(0)
red = torch.nn.Sequential(
    torch.nn.Linear(64, 256), torch.nn.ReLU(),
    torch.nn.Linear(256, 256), torch.nn.ReLU(),
    torch.nn.Linear(256, 256), torch.nn.ReLU(),
    torch.nn.Linear(256, 2),
).to(dev)
opt = torch.optim.Adam(red.parameters(), lr=1e-3)
phi = lambda s: 1 / (1 + a * s.clamp_min(1e-12) ** b)       # s = distancia al cuadrado
B, m, pasos = 512, 5, 10_000
for paso in range(pasos):
    e = torch.multinomial(peso, B, replacement=True)          # aristas con probabilidad proporcional a mu
    i, j = cab[e], col[e]
    k = torch.randint(0, len(Xt), (B * m,), device=dev)       # m negativos por arista, uniformes
    Z = red(Xt)
    zi = Z[i]
    pos = phi(((zi - Z[j]) ** 2).sum(1))
    neg = phi(((zi.repeat_interleave(m, 0) - Z[k]) ** 2).sum(1))
    perdida = -torch.log(pos.clamp_min(1e-4)).mean() - m * torch.log((1 - neg).clamp_min(1e-4)).mean()
    opt.zero_grad()
    perdida.backward()
    opt.step()
    if paso % 2500 == 0 or paso == pasos - 1:
        print(f"paso {paso:5d}  pérdida {perdida.item():.3f}")

with torch.no_grad():
    Etr = red(Xt).cpu().numpy()
    Ete = red(torch.tensor(Xte, dtype=torch.float32, device=dev)).cpu().numpy()
ref = umap.UMAP(random_state=0).fit(Xtr)
Ute = ref.transform(Xte)

def resumen(nombre, Ztr, Zte):
    acc = KNeighborsClassifier(10).fit(Ztr, ytr).score(Zte, yte)
    print(f"{nombre:22s} T(10) entren. {trustworthiness(Xtr, Ztr, n_neighbors=10):.3f}   "
          f"T(10) prueba {trustworthiness(Xte, Zte, n_neighbors=10):.3f}   10-NN prueba {acc:.3f}")

resumen("UMAP paramétrico", Etr, Ete)
resumen("umap-learn + transform", ref.embedding_, Ute)
p = PCA(2).fit(Xtr)
resumen("PCA", p.transform(Xtr), p.transform(Xte))

Xte_t = torch.tensor(Xte, dtype=torch.float32, device=dev)
t0 = time.perf_counter()
for _ in range(20):
    with torch.no_grad():
        red(Xte_t)
if dev == "cuda":
    torch.cuda.synchronize()
t_red = (time.perf_counter() - t0) / 20
t0 = time.perf_counter()
ref.transform(Xte)
t_tr = time.perf_counter() - t0
print(f"incrustar los {len(Xte)} puntos de prueba: la red tarda {t_tr / t_red:.0f} veces menos que transform")
del red, Xt, Xte_t, cab, col, peso
if dev == "cuda":
    torch.cuda.empty_cache()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Loss falls from 35.8 on the first step to between 0.70 and 0.84 from step 2500; as each batch is a sample, it fluctuates without falling further. On training points the network matches umap-learn: T(10)=0.984T(10) = 0.984 versus 0.988, a difference of the same order Sainburg and coauthors found on MNIST. On 450 new points it loses somewhat more: T(10)=0.952T(10) = 0.952 versus 0.975, and a 10-neighbor classifier trained on the training embedding correctly classifies 92.4% of test digits versus 97.6% for transform (and 63.6% for PCA). This is the price of replacing per-point optimization, which places each new digit next to its true neighbors, with a function learned from only 1347 examples. In return the network embeds 450 test points thousands of times faster than transform (over 3000 times in test runs; the exact ratio depends on hardware), and can be combined with other losses or reused as an encoder.

Common mistakes

Exercises

NumericA fuzzy-graph weight
A point has ρi=1\rho_i = 1 and σi=0.5\sigma_i = 0.5. One neighbor is at distance dij=1.5d_{ij} = 1.5. What is its directed weight wj∣iw_{j\mid i}?
NumericFuzzy union
For two points, wj∣i=0.6w_{j\mid i} = 0.6 and wi∣j=0.5w_{i\mid j} = 0.5. What is UMAP's symmetric weight μij\mu_{ij}?
QuizWhat min_dist does
What does min_dist control in UMAP, and why does it not change the high-dimensional graph?
ProofUMAP forces versus t-SNE forces
Prove: With a=b=1a = b = 1, let wij=1/(1+s)w_{ij} = 1/(1 + s) with s=∥yi−yj∥2s = \norm{\vb{y}_i - \vb{y}_j}^2. Pair {i,j}\{i, j\} contributes −μijlog⁡wij−(1−μij)log⁡(1−wij)-\mu_{ij}\log w_{ij} - (1 - \mu_{ij})\log(1 - w_{ij}) to UMAP loss, with gradient with respect to yi\vb{y}_i equal to 2μijwij(yi−yj)−2(1−μij)wij21−wij(yi−yj)2\mu_{ij} w_{ij}(\vb{y}_i - \vb{y}_j) - 2(1 - \mu_{ij})\frac{w_{ij}^2}{1 - w_{ij}}(\vb{y}_i - \vb{y}_j). Attraction has the form of t-SNE's 4pijwij(yi−yj)4p_{ij}w_{ij}(\vb{y}_i - \vb{y}_j), and repulsion changes wij2/Zw_{ij}^2/Z to wij2/(1−wij)w_{ij}^2/(1 - w_{ij}).
0
Use ∇yis=2(yi−yj)\grad_{\vb{y}_i} s = 2(\vb{y}_i - \vb{y}_j).

Step 1 of 4. What is ∇yi(−log⁡wij)\grad_{\vb{y}_i}(-\log w_{ij})?

NumericThe similarity UMAP actually seeks
In a dataset of n=10 000n = 10\,000 points, an edge has μij=0.2\mu_{ij} = 0.2 and both endpoints have fuzzy degree di=dj=6d_i = d_j = 6. With m=5m = 5 negative samples, what similarity νij∗\nu^*_{ij} minimizes its effective-loss term?
NumericWhen does t-SNE collapse?
In t-SNE with exaggeration ρ\rho on n=1000n = 1000 points, the smallest nonzero eigenvalue of affinity Laplacian LP=diag⁡(P1)−P\mat{L}_P = \diag(P\vb{1}) - P is λ2=2×10−5\lambda_2 = 2 \times 10^{-5}. Above what ρ\rho do all embedding directions contract once it is small?
Codet-SNE with exaggeration: three points on the spectrum
Implement tsne_grad(Y, P, rho), the gradient of Lρ(Y)=−ρ∑i≠jpijlog⁡wij+log⁡ZL_\rho(\mat{Y}) = -\rho\sum_{i \neq j}p_{ij}\log w_{ij} + \log Z with respect to Y\mat{Y} (shape (n, 2)), without Python loops. The remaining code is provided: three Gaussian groups in R10\R^{10} (40 points each), affinities at perplexity 20, PCA initialization, and an optimizer with momentum and rate n/(4ρ)n/(4\rho). Tests compare your gradient with finite differences, then run the spectrum at ρ=1,2,4\rho = 1, 2, 4 and measure group separation (mean centroid distance divided by mean group radius).
import numpy as np

def tsne_grad(Y, P, rho):
  """Gradiente de L_rho = -rho * sum_{i != j} p_ij log w_ij + log Z, con w_ij = 1/(1 + |y_i - y_j|^2)."""
  # tu código: w_ij, Z, q_ij = w_ij / Z y la suma 4 * sum_j (rho p_ij - q_ij) w_ij (y_i - y_j)
  return np.zeros_like(Y)

# ----- datos y optimizador (no hace falta tocarlos) -----
rng = np.random.default_rng(0)
C = rng.normal(0, 6, (3, 10))
X = np.concatenate([C[g] + rng.normal(0, 1, (40, 10)) for g in range(3)])
grupo = np.repeat(np.arange(3), 40)

def afinidades(X, perp=20.0):
  D2 = ((X[:, None, :] - X[None, :, :]) ** 2).sum(-1)
  N = len(X)
  Dm = D2 + np.diag(np.full(N, np.inf))
  Dm = Dm - Dm.min(1, keepdims=True)
  lo, hi, beta = np.zeros(N), np.full(N, np.inf), np.ones(N)
  for _ in range(100):
      Pc = np.exp(-Dm * beta[:, None])
      s = Pc.sum(1)
      H = np.log(s) + beta * (np.where(np.isinf(Dm), 0, Dm) * Pc).sum(1) / s
      alta = H > np.log(perp)
      lo, hi = np.where(alta, beta, lo), np.where(alta, hi, beta)
      beta = np.where(np.isinf(hi), 2 * beta, (lo + hi) / 2)
  Pc = Pc / Pc.sum(1, keepdims=True)
  return (Pc + Pc.T) / (2 * N)

P = afinidades(X)
Xc = X - X.mean(0)
Y0 = Xc @ np.linalg.svd(Xc, full_matrices=False)[2][:2].T
Y0 = Y0 / Y0[:, 0].std() * 1e-4

def tsne(P, rho, Y0, iters=400, temprana=100):
  Y, upd, n = Y0.copy(), np.zeros_like(Y0), len(Y0)
  for it in range(iters):
      ex = max(12.0, rho) if it < temprana else rho
      upd = (0.5 if it < temprana else 0.8) * upd - n / (4 * ex) * tsne_grad(Y, P, ex)
      Y = Y + upd
  return Y

def separacion(Y, grupo):
  c = np.array([Y[grupo == g].mean(0) for g in range(3)])
  radio = np.mean([np.linalg.norm(Y[grupo == g] - c[g], axis=1).mean() for g in range(3)])
  entre = np.mean([np.linalg.norm(c[a] - c[b]) for a in range(3) for b in range(a + 1, 3)])
  return entre / radio
Shift+Enter to run
QuizWhere global structure comes from
UMAP is often credited with better global-structure preservation than t-SNE. What mainly explains that difference in published comparisons?
QuizReading a UMAP plot
In a default UMAP embedding, group A occupies twice the area of B, and group C is much farther from A than B. What can you conclude about the original data without further checks?
QuizSame seed, different result
You run umap-learn twice on the same data with n_jobs=-1 and obtain different embeddings, although both times you call np.random.seed(0) first. Why?

Summary

Key idea
UMAP is a neighbor-embedding method: a kk-neighbor graph with pointwise normalized weights and a force-directed drawing. Its negative sampling optimizes a loss with much less repulsion than nominal, placing it on the t-SNE spectrum near exaggeration ρ≈4\rho \approx 4; global structure is set mainly by initialization.
  • The fuzzy graph fixes ρi\rho_i (nearest neighbor gets weight 1) and σi\sigma_i (weights sum to log⁡2k\log_2 k) for each point, then symmetrizes with union a+b−aba + b - ab. Local normalization equalizes densities: fuzzy degree satisfies di≥log⁡2kd_i \ge \log_2 k.
  • In the plane, ν=1/(1+a t2b)\nu = 1/(1 + a\,t^{2b}), with aa and bb fit to min_dist and spread; min_dist does not touch the graph. Cross-entropy is unnormalized and decomposes by pairs: its pairwise optimum is ν=μ\nu = \mu.
  • With negative sampling, pair attraction is proportional to μij\mu_{ij}, but repulsion weighs (di+dj)m/2n(d_i + d_j)m/2n, the same for every pair. The actual target is ν∗=μ/(μ+r)≈1\nu^* = \mu/(\mu + r) \approx 1 on each edge: UMAP reproduces the binary neighbor graph, and total repulsion is about mm times attraction.
  • Multiplying t-SNE attraction by ρ\rho traverses a spectrum: ρ=1\rho = 1 is t-SNE, ρ≈4\rho \approx 4 resembles UMAP, ρ≈30\rho \approx 30 ForceAtlas2 and ρ→∞\rho \to \infty Laplacian eigenmaps, with collapse above ρc=1/((n−1)λ2)\rho_c = 1/((n - 1)\lambda_2).
  • Relative arrangement of groups without edges between them is not fixed by either loss: it comes from initialization. With the same informative initialization, t-SNE and UMAP preserve global structure similarly.
  • Parametric UMAP trains a network with the same loss and projects new points with a forward pass, thousands of times faster than transform.