Tutorials › Statistical Methods for Single-Cell RNA Sequencing › Building UMAP’s Nearest-Neighbor Graph

Dimension Reduction and Embeddings · Tutorial 216 of 700

Building UMAP’s Nearest-Neighbor Graph

See how UMAP converts local cell-to-cell distances into directed, adaptively weighted neighbor edges before those edges are combined into a fuzzy graph.

Intermediate 12 min read

What You'll Learn

  • Distinguish the directed k-nearest-neighbor search from the later graph-combination step.
  • Define UMAP’s local offset and local scale for each cell.
  • Calculate directed edge weights from distances and local scales.
  • Understand the target sum used to estimate a local scale.
  • Diagnose ties, duplicates, unsuitable representations, and approximate scale searches.
  • Compare UMAP’s local weighting with hard neighbor graphs and fixed-bandwidth weights.

From Cell Distances to Directed Edges

UMAP’s graph construction begins with cells represented as points in a space where a distance has been chosen. The representation might be a set of selected principal-component scores rather than the original gene counts. The first graph-building task is local: for each cell, identify a specified number of nearby cells. The second is to convert those distances into edge weights that adapt to how tightly or loosely the neighborhood is spaced.

These weights are directed because the neighborhood and the distance scale are calculated separately for each cell. Cell \(j\) can be among cell \(i\)’s nearest neighbors without cell \(i\) being among cell \(j\)’s nearest neighbors. Even when each cell selects the other, the two directed weights can differ. This tutorial stops at those directed weights; combining them into a fuzzy graph is a distinct subsequent step.

Definition: Given \(n\) cells and a distance \(d_{ij}\) between cells \(i\) and \(j\), a directed \(k\)-nearest-neighbor graph contains an edge \(i\to j\) when \(j\) is among the \(k\) closest cells to \(i\). The edge’s directed membership weight is \(w_{i\to j}\), calculated using cell \(i\)’s local distance offset and scale.

The calculation assumes that the chosen representation and distance are meaningful for the neighborhoods of interest, that distances are nonnegative, and that each cell has at least \(k\) other cells available. It does not require normally distributed cell coordinates. However, the resulting graph depends on the representation, distance metric, value of \(k\), and handling of ties. It is a description of local geometry in the chosen space, not evidence by itself of biological interaction or causation.

Nearest Neighbors, Local Offsets, and Local Scales

For each cell \(i\), UMAP identifies its \(k\) nearest other cells and their distances. The cell itself is excluded. Write the ordered neighbor distances as \(d_{i(1)}\le d_{i(2)}\le\cdots\le d_{i(k)}\). In the simplest setting, the local offset \(\rho_i\) is the distance to the nearest neighbor, \(d_{i(1)}\). More generally, implementations can set \(\rho_i\) using a local-connectivity choice that interpolates among the nearest-neighbor distances. That adjustment controls how many very close neighbors receive full weight; it does not change the basic weighting formula.

The local scale \(\sigma_i>0\) controls how quickly weights fall as a neighbor’s distance exceeds \(\rho_i\). Given \(\rho_i\) and \(\sigma_i\), the directed edge weight is

$$ w_{i\to j}=\exp\left(-\frac{\max(0,d_{ij}-\rho_i)}{\sigma_i}\right). $$

Distances at or below \(\rho_i\) therefore receive weight 1. Beyond that offset, weight decreases exponentially. A small \(\sigma_i\) makes it decrease quickly; a large \(\sigma_i\) makes it decrease more gradually. The scale is local: cells in crowded and sparse regions can have different values of \(\sigma_i\), even though the same weighting rule applies to both.

UMAP selects \(\sigma_i\) by approximately matching a target sum of the weights over cell \(i\)’s nearest neighbors:

$$ \sum_{j\in N_k(i)} \exp\left(-\frac{\max(0,d_{ij}-\rho_i)}{\sigma_i}\right) \approx \log_2(k), $$

where \(N_k(i)\) is the set of \(k\) nearest neighbors of \(i\). The target \(\log_2(k)\) is not a claim that exactly \(\log_2(k)\) neighbors have nonzero weights: all selected neighbors generally have positive weights. Rather, it sets the approximate total membership weight and helps calibrate neighborhoods locally. Implementations find a suitable scale by a bounded numerical search, typically binary search, and may apply small-scale safeguards for numerical stability.

Key distinction: \(k\) determines which cells are candidates for edges; the local scale \(\sigma_i\) determines the weights of those edges. Changing \(k\) can alter both the neighbor set and the target sum, while changing the local scale changes weights without changing that cell’s selected neighbor set.

Worked Calculations

Worked Example: Finding a Cell’s Neighbors and Weights

Suppose four hypothetical cells lie on a one-dimensional coordinate axis at 0, 1, 3, and 7. Use the ordinary absolute difference as the distance. For the cell at 0, call it A, take \(k=3\), use the nearest-neighbor offset, and suppose the fitted local scale is \(\sigma_A=1.35\). Verify the neighbors and calculate their directed weights.

The distances from A to the other cells are 1 to B, 3 to C, and 7 to D. Thus \(N_3(A)=\{B,C,D\}\), and the nearest-neighbor offset is \(\rho_A=1\). Substituting into the weight formula gives

$$ w_{A\to B}=\exp\left(-\frac{\max(0,1-1)}{1.35}\right)=1, \qquad w_{A\to C}=\exp\left(-\frac{3-1}{1.35}\right)\approx 0.227. $$

For D, the exponent uses \(7-1=6\), so \(w_{A\to D}=\exp(-6/1.35)\approx 0.0117\). The three weights sum to approximately \(1.239\). This is not expected to equal \(\log_2(3)\approx1.585\), because the example stipulated a scale rather than estimating one. With the scale fitted to the target, the sum would be approximately 1.585, subject to search precision and implementation safeguards.

Worked Example: Estimating the Local Scale

For another hypothetical cell, suppose the three neighbor distances are 1, 2, and 4. Use \(\rho_i=1\) and \(k=3\). Find a scale that approximately meets the target-sum condition.

The nearest neighbor contributes weight 1. The remaining weights give the equation

$$ 1+\exp(-1/\sigma_i)+\exp(-3/\sigma_i)=\log_2(3)\approx1.585. $$

A numerical search tests positive values of \(\sigma_i\). At \(\sigma_i=1.35\), the left side is

$$ 1+\exp(-1/1.35)+\exp(-3/1.35) \approx 1+0.477+0.108 =1.585. $$

Thus \(\sigma_i\approx1.35\) is a suitable scale to three significant figures. Increasing \(\sigma_i\) increases each exponential term with a positive distance beyond \(\rho_i\), so the sum increases; decreasing \(\sigma_i\) decreases it. This monotonic behavior makes binary search appropriate. The calculation calibrates the total weight, not a hard count of neighbors retained.

Worked Example: Why Reciprocal Edges Can Have Different Weights

Suppose two hypothetical cells A and B are each in the other’s nearest-neighbor set, and their shared distance is 2. For A, let \(\rho_A=1\) and \(\sigma_A=0.5\). For B, let \(\rho_B=0.5\) and \(\sigma_B=2\). Calculate the two directed weights.

For A’s edge to B,

$$ w_{A\to B}=\exp\left(-\frac{2-1}{0.5}\right)=\exp(-2)\approx0.135. $$

For B’s edge to A,

$$ w_{B\to A}=\exp\left(-\frac{2-0.5}{2}\right) =\exp(-0.75)\approx0.472. $$

The edge from B to A has the larger weight because B’s offset leaves a smaller excess distance and B’s scale makes that excess decay more gradually. The weights are not contradictory: each is calculated from its source cell’s local geometry. A directed graph need not have equal reciprocal weights.

Why the Scale Search Works

For fixed \(\rho_i\), define the target-sum function as the sum of the \(k\) edge weights at a proposed scale \(\sigma_i\). For any neighbor with \(d_{ij}\le\rho_i\), its contribution is constantly 1. For a neighbor with \(d_{ij}>\rho_i\), its contribution is \(\exp(-(d_{ij}-\rho_i)/\sigma_i)\). Its derivative with respect to \(\sigma_i\) is

$$ \frac{d}{d\sigma_i}\exp\left(-\frac{d_{ij}-\rho_i}{\sigma_i}\right) = \exp\left(-\frac{d_{ij}-\rho_i}{\sigma_i}\right) \frac{d_{ij}-\rho_i}{\sigma_i^2}>0. $$

Consequently, the target sum is nondecreasing in the scale and strictly increasing whenever at least one selected neighbor lies beyond the offset. This gives the search a reliable direction: if a trial sum is too small, increase the scale; if it is too large, decrease it. As the scale approaches zero, weights beyond the offset approach zero, while as the scale grows, those weights approach 1. In ordinary cases these limits bracket the intended target. Tied distances, a large number of distances at or below the offset, and numerical bounds can complicate exact matching, which is one reason implementations use approximate searches and safeguards.

The basic derivation also explains the role of the offset. Subtracting \(\rho_i\) makes the closest neighborhood distances a reference point, so weights are driven by distance beyond that local reference rather than by the absolute distance from the cell. The scale then adapts the rate of decay to the local spacing.

Diagnostics, Alternatives, and Limitations

Before interpreting a constructed graph, check the inputs and the resulting neighborhoods. Confirm which cell representation and distance metric were used; inspect whether nearest-neighbor distances look plausible; and check for duplicate points, ties, missing or non-finite distances, and cells whose neighbors are unexpectedly dominated by technical or batch structure. A scale search that repeatedly reaches a numerical bound, or a cell with many tied distances, deserves attention. These checks do not establish that a chosen representation is biologically appropriate, but they can reveal when the graph is not behaving as intended.

The local weighting has a practical advantage over a hard \(k\)-nearest-neighbor graph: a hard graph gives every selected edge the same weight and every unselected edge weight zero, whereas UMAP’s directed weights distinguish closer from farther selected neighbors. It also differs from a single fixed-bandwidth Gaussian weighting of all distances. A fixed bandwidth applies a common decay scale; UMAP estimates a separate scale for each cell, adapting to local density. This adaptation is useful when neighborhood spacing varies, but it also means edge weights are relative to local scales and are not direct, globally comparable measurements of physical distance.

The directed weights are also distinct from the conditional similarities used in t-SNE. Both methods encode local relationships, but UMAP’s construction uses a local offset and a scale chosen to match a target sum, rather than t-SNE’s perplexity-calibrated probability distribution. These are different constructions, so one method’s parameters or edge weights should not be interpreted as though they were the other’s.

Several limitations remain. Nearest-neighbor search can be approximate in large data sets, so different search settings may change neighbor identities. Results are sensitive to the input representation and metric; an unsuitable distance can make even a correctly computed graph scientifically unhelpful. Ties and duplicate cells may yield several equal distances, and local scale safeguards can mean the target sum is not matched exactly. Finally, directed weights alone do not establish the final graph used by UMAP’s embedding procedure. Their later combination is a separate operation.

Common mistake: “A cell has \(k\) neighbors, so its \(k\) edge weights should all be equal, and every neighbor should have weight \(1/k\).” This confuses a hard neighbor count with UMAP’s weighted construction. The \(k\) nearest cells define the candidate edges; each weight depends on its distance, the source cell’s offset, and its local scale. The target is an approximate sum of weights, not an equal allocation across \(k\) edges.

Check Your Understanding

Answer each question, then compare your reasoning with the solutions.

  1. If \(d_{ij}\le\rho_i\), what is \(w_{i\to j}\), and why?
  2. For a fixed neighbor with \(d_{ij}>\rho_i\), what happens to its weight when \(\sigma_i\) increases?
  3. Two cells are reciprocal nearest neighbors. Must their directed weights be equal? Explain.
  4. What does \(k\) determine, and what does the local scale determine?
  5. Give one reason the target sum might not be matched exactly in an implementation.

Solutions. (1) Its weight is 1 because \(\max(0,d_{ij}-\rho_i)=0\), so the exponent is zero and \(\exp(0)=1\). (2) Its weight increases, since a larger scale makes the negative exponent closer to zero. (3) No. Each direction uses the source cell’s own offset and scale, which can differ. (4) \(k\) selects the candidate neighbor set; the local scale controls how the weights of those directed edges decay with distance beyond the offset. (5) A bounded approximate search, tied distances, numerical safeguards, or many distances at or below the offset can prevent exact matching.

Clinical Biostats