Sub topic 12
UMAP step 1: a weighted nearest-neighbour graph
This chapter assumes you know k-nearest neighbours, Euclidean distance, sparse matrices in SciPy, and the t-SNE affinities from earlier chapters. UMAP starts the way t-SNE does. It turns distances into a measure of "who is close to whom". It stores that measure as a sparse graph, not as a dense matrix of probabilities.
From points to a graph
For each point, UMAP finds its n_neighbors nearest neighbours. Each neighbour becomes a directed edge with a weight between 0 and 1. Weights near 1 mean "strongly connected". Points that are not neighbours get no edge, so the graph stays sparse.
Two local quantities set the weights for point i:
- rho_i is the distance to the nearest neighbour. Subtracting it means every point is fully connected to at least one neighbour. This is the local connectivity assumption, and it stops isolated points from floating free.
- sigma_i is a bandwidth found by search so that the weights of point i sum to log2(
n_neighbors).
The weight of the edge from i to j is exp(-(dij - rhoi) / sigmai). Because sigmai is fitted per point, dense and sparse regions both end up with the same total connectivity. This plays the same role as perplexity does in t-SNE.
Symmetrising the graph
The weight from i to j usually differs from the weight from j to i. UMAP combines them with a fuzzy union: w = a + b - a·b. The result is high if either direction is strong. It never exceeds 1.
A minimal implementation
This code is a simplified version of what umap-learn does internally. It leaves out approximate neighbour search and special cases.
import numpy as np
from scipy.optimize import brentq
from scipy.sparse import csr_matrix
from sklearn.datasets import load_digits
from sklearn.neighbors import NearestNeighbors
X, _ = load_digits(return_X_y=True)
n, k = X.shape[0], 15
dist, idx = NearestNeighbors(n_neighbors=k + 1).fit(X).kneighbors(X)
dist, idx = dist[:, 1:], idx[:, 1:] # drop each point itself
rho = dist[:, 0]
target = np.log2(k)
weights = np.zeros_like(dist)
for i in range(n):
shifted = np.maximum(dist[i] - rho[i], 0.0)
f = lambda s: np.exp(-shifted / s).sum() - target
sigma = brentq(f, 1e-6, 1e3)
weights[i] = np.exp(-shifted / sigma)
rows = np.repeat(np.arange(n), k)
W = csr_matrix((weights.ravel(), (rows, idx.ravel())), shape=(n, n))
G = W + W.T - W.multiply(W.T)
print("directed edges:", W.nnz)
print("symmetric edges:", G.nnz)
print("max weight:", G.max())The symmetric graph has more stored entries than the directed one, because every edge now appears in both directions. Every weight stays at or below 1.
What to watch for
- A small
n_neighborsmakes the graph reflect very local structure. It can split one real group into several pieces. - A large
n_neighborsconnects distant regions and smooths away fine detail. - The metric decides what "nearest" means. The graph is only as good as that choice.
- High-dimensional distances become less informative, so scale features and consider a PCA step first.
Exercise
A point sits far from all others, so its nearest neighbour is at distance 8. Why does it still get a weight of 1 to that neighbour?
Show answer
UMAP subtracts rho, the distance to the nearest neighbour, before applying the exponential. For the nearest neighbour the shifted distance is 0, so exp(0) = 1. This local connectivity rule keeps outliers attached to the graph.