Sub topic 12
UMAP step 1: a weighted nearest-neighbour graph
This chapter assumes you know basic Python and NumPy, scikit-learn's fit/transform interface, Euclidean distance, and how to read a sparse matrix. UMAP works in two stages. First it builds a weighted graph that describes which points are close in the original space. Then it lays that graph out in two dimensions. This chapter covers only the first stage.
What the graph has to capture
Think of each point as a node. An edge between two nodes carries a weight between 0 and 1, which you can read as "how strongly these two points belong together". Strong edges join close neighbours, and weak edges join distant ones.
A plain k-nearest-neighbour (kNN) graph with distances as weights would work badly on real data, for two reasons:
- Density varies. A point in a dense region has neighbours at distance 0.5. A point in a sparse region has its nearest neighbour at distance 5. A single global distance scale treats the sparse point as poorly connected.
- Neighbour relations are not symmetric. Point A can list B among its 15 nearest neighbours while B does not list A.
UMAP fixes the first problem with a per-point distance scale and the second with a symmetrisation rule.
Step 1: find the neighbours
For each point UMAP finds its n_neighbors nearest neighbours under the chosen metric. For large data it uses an approximate search (nearest-neighbour descent), not an exhaustive one. The result is two arrays of shape (n_points, k), one holding neighbour indices and one holding distances.
Step 2: local connectivity with rho
For point i, let rho_i be the distance to its nearest neighbour. UMAP subtracts rho_i from every distance for that point. The nearest neighbour then sits at adjusted distance 0 and gets weight exactly 1.
This is the "local connectivity" assumption. Every point is fully connected to at least one other point, however isolated it is. Isolated points therefore do not end up as disconnected dust.
Step 3: local scale with sigma
Next UMAP picks a bandwidth sigma_i for each point and defines the directed weight from i to neighbour j as:
w(i -> j) = exp( -(d(i, j) - rho_i) / sigma_i )sigma_i is chosen so that the weights of point i add up to a fixed target:
sum over j of exp( -(d(i, j) - rho_i) / sigma_i ) = log2(k)The target depends only on k. A point in a sparse region therefore gets a large sigma_i, and a point in a dense region gets a small one. Each point ends up with the same total weight spread over its neighbours. This is the same idea as t-SNE's perplexity calibration, but with a simpler target and without normalising the weights into probabilities.
The left side grows steadily as sigma_i increases, so a binary search finds the solution.
Step 4: symmetrise with the fuzzy union
After steps 2 and 3, the edge i -> j and the edge j -> i can have different weights, and one of them can be missing. UMAP combines them as a probabilistic OR:
w(i, j) = a + b - a*b where a = w(i -> j), b = w(j -> i)If either direction is strong, the combined edge is strong. If one direction is missing, b = 0 and the weight is just a. The result is symmetric and still lies between 0 and 1.
Building it by hand
This code reproduces the construction with scikit-learn and SciPy. It is a simplified version of what umap-learn does internally.
import numpy as np
from scipy.sparse import csr_matrix
from sklearn.datasets import load_digits
from sklearn.neighbors import NearestNeighbors
def fuzzy_graph(X, k=15):
# kneighbors() with no argument excludes each point from its own list.
nn = NearestNeighbors(n_neighbors=k).fit(X)
dist, idx = nn.kneighbors()
n = X.shape[0]
target = np.log2(k)
rho = dist[:, 0]
sigma = np.empty(n)
for i in range(n):
d = np.maximum(dist[i] - rho[i], 0.0)
lo, hi = 1e-8, 1e4
for _ in range(64): # binary search for sigma
mid = (lo + hi) / 2
if np.exp(-d / mid).sum() > target:
hi = mid
else:
lo = mid
sigma[i] = (lo + hi) / 2
w = np.exp(-np.maximum(dist - rho[:, None], 0.0) / sigma[:, None])
rows = np.repeat(np.arange(n), k)
A = csr_matrix((w.ravel(), (rows, idx.ravel())), shape=(n, n))
B = A + A.T - A.multiply(A.T) # fuzzy union
return A, B.tocsr(), rho, sigma
X, y = load_digits(return_X_y=True)
A, B, rho, sigma = fuzzy_graph(X, k=15)
print("directed edges:", A.nnz)
print("symmetric edges:", B.nnz // 2)
print("max asymmetry:", abs(B - B.T).max())
print("rho range:", rho.min().round(2), rho.max().round(2))
print("sigma range:", sigma.min().round(2), sigma.max().round(2))
print("strongest edge weight:", B.max())The symmetric graph has more edges than n * k / 2 whenever neighbour relations are one-sided, and the asymmetry prints as 0. The sigma values differ from point to point, which is the density adaptation at work. Fitting umap.UMAP(...) also gives you a sparse matrix in its graph_ attribute. It is built the same way, so you can use it to check that your own results look similar.
What the parameters do to the graph
| Parameter | Effect on the graph | Typical consequence |
|---|---|---|
| `n_neighbors` (k) | Number of candidate edges per point, and the target `log2(k)` | Small k gives a sparse graph that emphasises fine local detail. Large k gives a denser graph that emphasises global structure. |
| `metric` | The distance used for neighbour search and for `d(i, j)` | A different metric changes which points count as neighbours. |
| `local_connectivity` | How many nearest neighbours get weight 1 (default 1) | Higher values connect points more firmly to their surroundings. |
min_dist does not appear here. It only affects the layout stage, which the next chapter covers.
Edge cases and failure modes
- Duplicate points. If a point has an exact duplicate,
rho_iis 0 and some adjusted distances are 0. The construction still works, but the graph then connects those duplicates with weight 1. - Noise features. The graph is only as good as the distances behind it. If hundreds of irrelevant features dominate Euclidean distance, the neighbour lists are poor and no layout can repair that. Scale the features and consider a PCA step first.
- Hubs. In very high dimensions a few points appear in many neighbour lists. They get many strong incoming edges and can distort the layout.
- Approximate search. The nearest-neighbour search is approximate. Two runs with different seeds can build slightly different graphs, which is one source of run-to-run variation.
Exercises
Exercise
A point's nearest neighbour is at distance 4.0, and its other neighbours are at 4.5, 5.0 and 6.0. Which neighbour gets weight exactly 1, and why?
Show answer
The nearest neighbour at distance 4.0 gets weight 1. After subtracting rho (4.0), its adjusted distance is 0, so exp(0) = 1. This is the local connectivity assumption.
Exercise
Point A lists B as a neighbour with directed weight 0.6. B does not list A, so the reverse weight is 0. What is the symmetric weight, and what would it be if the reverse weight were 0.5?
Show answer
With a missing reverse edge the weight is 0.6 + 0 - 0.60 = 0.6. With a reverse weight of 0.5 it is 0.6 + 0.5 - 0.60.5 = 0.8.
Exercise
Why does a point in a sparse region get a larger sigma than a point in a dense region?
Show answer
The weights of each point must add up to log2(k). A sparse-region point has larger adjusted distances, so exp(-d/sigma) is small unless sigma is large. The binary search therefore settles on a larger sigma to reach the same total.