Sub topic 13
UMAP step 2: laying out the graph
The previous chapter built UMAP's weighted nearest-neighbour graph. This chapter covers the second half: turning that graph into 2-D coordinates. It assumes you know gradient descent, the weighted graph from step 1 (each edge has a weight between 0 and 1), and the fit/transform interface of scikit-learn.
The goal: make the low-dimensional graph match the high-dimensional one
Step 1 gave every pair of neighbouring points a weight $w_{ij}$ in $[0, 1]$. You can read it as the strength of the claim "these two points are neighbours".
Step 2 searches for 2-D positions $y_i$ whose own edge weights match those values. The embedding has its own weights, computed from distances in the plane:
$$q{ij} = \frac{1}{1 + a\,\lVert yi - y_j \rVert^{2b}}$$
Here $a$ and $b$ are constants fixed before optimisation starts. The weight $q_{ij}$ is 1 when two points coincide and falls towards 0 as they move apart.
UMAP then minimises the cross-entropy between the two sets of weights, summed over point pairs:
$$C = \sum{i,j} \Big[ -w{ij}\log q{ij} - (1 - w{ij})\log(1 - q_{ij}) \Big]$$
Each term has a job:
- The first term, $-w \log q$, pulls points together when $w$ is large. It is the attractive force.
- The second term, $-(1-w)\log(1-q)$, pushes points apart when $w$ is small. It is the repulsive force.
Where a and b come from
You never set $a$ and $b$ directly. UMAP fits them so that the curve $q(d)$ approximates a target shape controlled by min_dist and spread. The target is 1 for distances up to min_dist, then decays exponentially:
$$\text{target}(d) = \begin{cases} 1 & d \le \text{min\dist} \\ e^{-(d - \text{min\dist})/\text{spread}} & d > \text{min\_dist} \end{cases}$$
The target has a flat top of width min_dist. Points closer than that incur almost no extra attraction, so they are not squeezed into a single spot. This is the mechanism behind the min_dist parameter from the previous chapter.
import numpy as np
from umap.umap_ import find_ab_params
a, b = find_ab_params(spread=1.0, min_dist=0.1)
print(f"a = {a:.3f}, b = {b:.3f}")
d = np.array([0.0, 0.1, 0.5, 1.0, 2.0, 4.0])
q = 1.0 / (1.0 + a * d ** (2 * b))
for dist, val in zip(d, q):
print(f"distance {dist:.1f} -> membership {val:.3f}")With the defaults you get roughly $a \approx 1.58$ and $b \approx 0.90$. The membership is near 1 at distance 0.1 and about 0.39 at distance 1.0. Rerun with min_dist=0.5 and the curve stays high for longer, so points are allowed to spread out.
Like t-SNE's Student-t kernel, this curve has a heavy tail, so moderately distant points still feel some pull.
Sampling edges and negative samples
Computing $C$ over all $n^2$ pairs would not scale. UMAP avoids this with stochastic gradient descent over sampled terms:
- Attraction uses real edges only. Each epoch, an edge with weight $w$ is selected with probability proportional to $w$ (relative to the largest weight). Heavy edges are updated often and light edges rarely. This is why the weights from step 1 matter even though the optimiser never reads them as a loss coefficient directly.
- Repulsion uses random pairs. For each selected edge, UMAP draws
negative_sample_raterandom points (default 5) and pushes the edge's endpoint away from each of them. It treats them as non-neighbours with $w = 0$. A random pair is almost always a true non-neighbour in a large dataset, so this approximation is cheap and mostly correct. - Updates are local. Each step moves only the points involved, so the cost per epoch is proportional to the number of edges, not to $n^2$.
The learning rate starts at learning_rate=1.0 and decays linearly to 0 over n_epochs. If you leave n_epochs=None, UMAP uses 500 epochs for small datasets (under about 10,000 points) and 200 for larger ones. Gradient components are clipped to a fixed range so one unlucky sample cannot fling a point far away.
No global normalisation
t-SNE divides by a sum over all pairs in the low-dimensional space, so every point's position affects every other point's probability. UMAP has no such normalisation. Repulsion is sampled and local. This is the main reason UMAP is faster. It also means UMAP's layout leans more heavily on its starting positions, which brings us to initialisation.
Initialisation matters
The default is init="spectral". UMAP computes eigenvectors of the graph Laplacian of the neighbour graph and uses the leading ones as starting coordinates. Spectral initialisation places connected regions of the graph near each other from the start. The optimiser then mostly refines local detail, so the coarse arrangement of clusters comes from the graph rather than from chance.
With init="random" the starting positions are noise. The optimiser must find the large-scale arrangement itself, and it often does so inconsistently. The result is that relative placement of clusters varies more between runs.
import umap
from sklearn.datasets import load_digits
from sklearn.manifold import trustworthiness
X, y = load_digits(return_X_y=True)
for init in ["spectral", "random"]:
for seed in [0, 1]:
Z = umap.UMAP(init=init, random_state=seed).fit_transform(X)
score = trustworthiness(X, Z, n_neighbors=10)
print(f"init={init:8s} seed={seed} trustworthiness={score:.3f}")Trustworthiness measures local neighbour preservation, so expect similar scores across rows. Local structure is usually fine either way. What changes is where the clusters sit relative to each other. Plot the four embeddings side by side to see it.
Parameters that affect the layout step
| Parameter | Default | Effect on layout |
|---|---|---|
| `min_dist` | 0.1 | Sets the flat top of the target curve, so it controls how tightly points pack. |
| `spread` | 1.0 | Sets the scale of the decay, together with `min_dist`. |
| `n_epochs` | auto (200 or 500) | More epochs refine the layout. Few epochs leave it under-converged. |
| `learning_rate` | 1.0 | Initial step size, decayed to 0. |
| `negative_sample_rate` | 5 | More negatives give stronger repulsion and more separated clusters. |
| `init` | `"spectral"` | Starting coordinates. |
| `repulsion_strength` | 1.0 | Weight on the repulsive term. |
n_neighbors and metric do not appear here because they act in step 1, before the layout begins.
Common errors
- Treating
min_distas a neighbourhood setting. It only changes the curve in the 2-D space. The neighbour graph is untouched, so the same neighbours are preserved. Only the packing differs. - Under-converged plots. Setting
n_epochsvery low gives blobs that look smooth but are not settled. Compare against a longer run if the picture looks unusually diffuse. - Over-reading cluster gaps. Repulsion is sampled and the objective has no term that makes inter-cluster distance meaningful. The size of a gap depends on initialisation and settings.
- Expecting
transformto refit.transformplaces new points using the fitted graph and then runs a short optimisation for the new points only. The training points do not move.
Exercise
You fit UMAP twice with the same data and parameters but init="random" and different seeds. Trustworthiness is nearly identical, yet the clusters appear in different relative positions. Explain why, using the optimisation steps described in this chapter.
Show answer
Trustworthiness measures local neighbourhoods, and the attract and repel updates are local, so both runs preserve neighbours equally well. UMAP has no global normalisation, and its repulsion is sampled from random points. With random initialisation, nothing fixes the large-scale arrangement, so each seed ends in a different coarse layout. Spectral initialisation would anchor the layout to the graph's structure and make the arrangement more consistent.