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 ), so every gradient step considers the whole cloud, and Barnes–Hut or grid interpolation is needed to reduce cost below 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 -neighbor graph and an unnormalized loss, allowing stochastic gradient optimization by sampling edges, with per-epoch cost proportional to edge count, , 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 yields something very like UMAP, and taking 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.
- , local connectivity. Subtracting the distance to the nearest neighbor ensures it always has weight : 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; removes that common part.
- , a personal measuring scale. In a dense region neighbors are close and is small; in a sparse one it is large. Thus all points distribute the same total mass, , 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 ; UMAP uses an exponential of . Since mass is distributed only among the neighbors, tail shape matters little.
exists and is unique as long as the nearest neighbor is not tied with too many others. Let and . Each term with is continuous and strictly increasing in , from (as ) to (as ); terms with are always . Thus strictly increases from to , and has a unique solution if . The right inequality holds for every (); the left fails only if at least neighbors share the minimum distance (especially duplicate points). Monotonicity justifies bisection: umap-learn takes 64 steps and, as a safeguard, prevents from falling below times mean neighbor distance.
Fuzzy union
Weights are asymmetric: can be among ‘s neighbors without being among ‘s, and even if it is, each measures with its own . UMAP interprets them as edge-existence probabilities according to each endpoint and combines them with the probabilistic sum : 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, , an average. For ,
(The first inequality is .) Union never lowers an edge: it suffices for either endpoint to consider it strong. Since , fuzzy degree satisfies . The difference is exactly , so equality holds only if no point selects , except perhaps those with (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 ( images, that is, ) with , the default. Neighbors are computed by brute force: at it is faster than any approximate structure. Bisection is performed for all points at once.
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 . Nearest-neighbor distance ranges from 9.43 to 28.97 (gray levels 0 to 16 in 64 pixels) and from 0.44 to 10.73: a factor of 24 between the finest and coarsest measuring scales. follows the spread of distances above almost exactly (correlation 0.976). Only 68.7% of directed edges are reciprocal, and union leaves 9189 undirected edges. Minimum degree is exactly , as the inequality predicts, and maximum 14.755. That excess is , 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:
- 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 , rescale distances so ‘s neighbors lie within a fixed-radius ball. This justifies each point having its own .
- Under the additional assumption that the manifold is locally connected, no point should be isolated: hence .
- Each point thus gives its own metric space, which a functor converts into a fuzzy simplicial set (a graph with weights in , considering only its 1-skeleton). The pointwise versions are incompatible and are combined using fuzzy-set union: the probabilistic sum.
- Another fuzzy set is built in the plane, with weights , 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 -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 with those of the binary -neighbor graph and UMAP’s embedding barely changed. Damrich and Hamprecht showed the actual optimizer does not reproduce , 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
a two-parameter family containing t-SNE’s Cauchy kernel (, unnormalized). Parameters are not chosen directly: they are least-squares fitted to target curve
at 300 points in . With defaults min_dist = 0.1 and spread = 1, this gives and . min_dist says up to what distance two points are considered “stuck together” in the plane: with large min_dist, 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, and couples all pairs: moving two points changes every other similarity. Here each summand depends only on and , and the loss is a sum of pairwise terms. This allows stochastic gradients over edges.
- There is an explicit repulsion term for every pair, . Since nearly every pair has , this pushes nearly every pair apart with weight .
For an isolated pair, is strictly convex on and its derivative vanishes at . That is, the nominal loss asks each pair to reproduce its weight: . Keep that conclusion in mind, because we will contradict it.
Optimization: stochastic gradient, negative sampling and spectral initialization
Forces on a pair
Let , so . Since ,
The first gradient points from to , so descending along it brings points together: attraction, with weight . The second has the opposite sign and pushes them apart: repulsion, with weight . Repulsion has a factor that explodes when points coincide; umap-learn replaces it with and clips each gradient component to before multiplying by the learning rate. With 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 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:
- Each directed graph edge (both directions of every symmetric edge are listed) is processed on average times per epoch: once every epochs. Edges with are removed before starting: they would be processed fewer than once in the entire optimization.
- When processing it, apply an attraction step to and the opposite step to .
- Choose points uniformly at random (
negative_sample_rate, default ), assume , and apply to , only to it, a step of repulsion from .
The learning rate starts at and falls linearly to ; epochs number 500 if and 200 otherwise. Per-epoch cost is proportional to times the number of edges, .
Spectral initialization
By default, umap-learn starts not from random points but from Laplacian eigenmaps of the fuzzy graph itself: eigenvectors to of normalized Laplacian , where and , rescaled so the maximum coordinate is 10 and with noise of standard deviation . 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 with largest eigenvalues have the smallest Laplacian eigenvalues) and fits and like umap-learn’s find_ab_params.
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, , , umap-learn’s values; with min_dist = 0.99, and , 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.
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 , 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.
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 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.
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 (, 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 , 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).
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}")npm run lab and open the connection link.| method | neighbors retained | 10-NN | global | |
|---|---|---|---|---|
| PCA | 0.830 | 0.118 | 0.613 | 0.815 |
| UMAP from scratch | 0.988 | 0.493 | 0.978 | 0.554 |
| umap-learn | 0.989 | 0.491 | 0.978 | 0.576 |
| openTSNE | 0.992 | 0.589 | 0.973 | 0.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.
Three takeaways, all using the interactive’s figures:
- Small
n_neighborsfragments. With , 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_neighborsis not simply “more global.” On digits global correlation rises monotonically with (0.22 to 0.53 withmin_dist = 0.1) while neighbors retained fall from their maximum at . On the 400-point Swiss roll, however, introduces shortcuts between layers and correlation with unrolled coordinates falls from 0.79 to 0.23: neighborhood scale now exceeds layer separation. min_distdoes 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 : UMAP equalizes densities, a direct consequence of each point measuring with its own .
What is actually optimized: the effective loss
Negative sampling looks like an innocent estimator of the gradient of . It is not: it distributes repulsion with weights unrelated to . Damrich and Hamprecht (2021) worked out the calculation.
Counting updates
Normalize epochs so each directed edge is processed in expectation times per epoch.
- Attraction. Edge and its twin both move both endpoints, so in one epoch each point of pair receives an expected attraction steps: on average, one step along the gradient of .
- Repulsion. Every time an edge headed by is processed, uniform points are selected. The expected number of times a particular repels in an epoch is , independent of . Symmetrically, repels an expected times.
If each negative sample also pushed (a correction proposed by the authors), pair would receive 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: versus . Three consequences:
- Target similarities become binary. Repeating the isolated-pair calculation with gives optimum . Since is of order , tiny for large , for every edge with , however small, and for nonedges. UMAP does not attempt to reproduce but the binary neighbor graph symmetrized by union.
- Total repulsion is times attraction, regardless of . Summing, , so total effective repulsion is (total attraction). The nominal sum, , is of order : their ratio grows like .
- 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 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.
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 : about 397 for edges with and 25 for those with . Repulsion steps are practically the same for all (13.30, 12.87 and 12.30), as predicted by with epochs, whose mean is 12.41 (edges have slightly more because their endpoints have greater degree): negative sampling knows nothing about . 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 of umap-learn’s final embedding on each graph edge.
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}")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 is 0.218 and final similarity is 0.876: only 21.2% of edges have , but 90.5% end with . The effective-loss optimum has median 0.924, much closer to measurement than the nominal ; Spearman correlation between and is only 0.44. Effective repulsion weights have median 0.0181 and maximum 0.0367, versus 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 .
In simulation, with 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 (about 11); with (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 by a factor during initial iterations. Böhm, Berens and Kobak maintain a factor throughout optimization and see what happens. With , and , the gradient of
is
With , 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 is equivalent to dividing repulsion by .
Böhm and coauthors describe that attraction–repulsion spectrum using four landmarks. is t-SNE: discrete, well-separated groups. Around the result resembles UMAP (their greatest distance correlation with UMAP occurred at on most datasets). Around it resembles ForceAtlas2, a graph-drawing algorithm. As 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 (), fraction of 15 neighbors retained fell from 0.34 at to 0.12 at and 0.06 at . Their explanation for UMAP falling near is the previous section’s: negative sampling greatly reduces effective repulsion.
The infinite-attraction limit
Why Laplacian eigenmaps? When is large, attraction contracts the cloud; as it becomes very small, all and . Linearizing the gradient (with centered cloud, ),
with the affinity-graph Laplacian. With simple gradient descent and rate , one step multiplies the component of along an eigenvector of with eigenvalue by . That component contracts if (and the step is not so long as to make it oscillate) and grows if , until the cloud is no longer small and linearization no longer holds. Thus:
- If the graph is connected and , with the smallest nonzero eigenvalue, all directions contract (the eigenvalue 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 lies between and , the direction contracts and the 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).
# 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 and , thresholds are and . Check the interactive: at the embedding is a nearly one-dimensional curve, and at scale falls to around . The threshold depends on data through : on MNIST, with , it must exceed 30 because Böhm and coauthors show uncollapsed embeddings at .
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 , then falls (0.79 at , 0.73 at ): UMAP resembles moderately exaggerated t-SNE and stops resembling it once attraction dominates. Within that interval the exact maximum is unreliable. Small- runs are most sensitive to rounding, because pure t-SNE has many local minima: with the same code, the maximum occurred at in Chrome and in Node, whereas from the runs agree to the third digit. The rest is robust. Correlation with eigenmaps rises almost uninterrupted from about 0.56 at to 0.855 at , 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 and . At the embedding is nearly a line and retains only 32% of neighbors; at 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 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 with centers on a planar curve and separated enough that the neighbor graph does not join them.
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}")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 coordinates , 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 , normally a neural network, set , and minimize the same loss over . 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 , take negatives per edge, compute on positives and 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 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.
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()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: versus 0.988, a difference of the same order Sainburg and coauthors found on MNIST. On 450 new points it loses somewhat more: 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
min_dist control in UMAP, and why does it not change the high-dimensional graph?Step 1 of 4. What is ?
tsne_grad(Y, P, rho), the gradient of with respect to (shape (n, 2)), without Python loops. The remaining code is provided: three Gaussian groups in (40 points each), affinities at perplexity 20, PCA initialization, and an optimizer with momentum and rate . Tests compare your gradient with finite differences, then run the spectrum at 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 / radion_jobs=-1 and obtain different embeddings, although both times you call np.random.seed(0) first. Why?Summary
- The fuzzy graph fixes (nearest neighbor gets weight 1) and (weights sum to ) for each point, then symmetrizes with union . Local normalization equalizes densities: fuzzy degree satisfies .
- In the plane, , with and fit to
min_distandspread;min_distdoes not touch the graph. Cross-entropy is unnormalized and decomposes by pairs: its pairwise optimum is . - With negative sampling, pair attraction is proportional to , but repulsion weighs , the same for every pair. The actual target is on each edge: UMAP reproduces the binary neighbor graph, and total repulsion is about times attraction.
- Multiplying t-SNE attraction by traverses a spectrum: is t-SNE, resembles UMAP, ForceAtlas2 and Laplacian eigenmaps, with collapse above .
- 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.