Sub topic 13
UMAP step 2: laying out the graph
This chapter assumes you know how UMAP builds its weighted nearest-neighbour graph (previous chapter), what gradient descent does, and the basics of the umap-learn API.
What the layout must achieve
After step 1, every edge between two points has a weight between 0 and 1. This weight is the strength of the fuzzy connection in the original space. Step 2 searches for 2-D coordinates whose own edge weights match those of the graph.
UMAP computes a low-dimensional weight for each pair of points from their distance d:
w(d) = 1 / (1 + a * d^(2b))
The constants a and b are not tuned by hand. UMAP fits them so that w stays near 1 up to min_dist and then decays smoothly. This is how min_dist controls how tightly points may pack.
from umap.umap_ import find_ab_params
for min_dist in [0.0, 0.1, 0.5]:
a, b = find_ab_params(spread=1.0, min_dist=min_dist)
print(f"min_dist={min_dist}: a={a:.3f}, b={b:.3f}")Attraction and repulsion
UMAP minimises a cross-entropy between the high-dimensional weights and the low-dimensional ones. The loss splits into two forces:
- Attraction. Each graph edge pulls its two endpoints together, in proportion to the edge weight.
- Repulsion. Pairs that are not connected push each other apart.
Computing repulsion between all pairs would be too slow. UMAP uses negative sampling instead. For each edge update, it picks a few random points and pushes the current point away from them. The parameter negative_sample_rate sets how many it picks, and the default is 5.
Initialisation and epochs
UMAP starts from a spectral embedding of the graph by default (init="spectral"). This places connected regions near each other from the first step, so the global arrangement is more stable between runs than with random starts. The optimiser then runs for n_epochs passes. The learning rate falls linearly to zero. If you leave n_epochs unset, UMAP uses 500 for small datasets and 200 for large ones.
import umap
from sklearn.datasets import load_digits
X, y = load_digits(return_X_y=True)
for init in ["spectral", "random"]:
Z = umap.UMAP(init=init, random_state=0).fit_transform(X)
print(init, Z.shape)Common errors
- Reading inter-cluster distances as exact. The optimiser only enforces attraction along edges and sampled repulsion, so gaps between clusters are weakly constrained.
- Setting
n_epochstoo low. Clusters stay fuzzy and tangled because the attraction has not finished. - Using
init="random"and treating differences between seeds as real structure.
Exercise
Why does UMAP sample a few random points for repulsion instead of repelling every pair of points?
Show answer
Repelling every pair costs O(n^2) work per epoch. Negative sampling pushes each point away from only a few random points per edge update. Most random pairs are not neighbours, so this approximates the full repulsion at a much lower cost.