2.5.12Unsupervised Learning

UMAP for dimensionality reduction

3,029 words14 min readdifficulty · medium5 backlinks

Think of it like making a map of a crumpled piece of paper: you want neighborhoods to stay together, but you also want the overall layout to make sense.

Why UMAP? The Motivation

The Problem withCA: Linear projection loses manifold structure (think: projecting a Swiss roll).

The Problem with t-SNE:

  • Optimizes only local structure → global distances meaningless
  • Computationally expensive: O(n2)O(n^2)
  • Non-deterministic layout between runs
  • Doesn't preserve density information

UMAP's Solution:

  1. Model high-D data as a fuzy topological structure (Riemannian manifold)
  2. Construct a similar structure in low-D
  3. Find the layout that makes these two structures as similar as possible
  4. Use clever approximations to make it fast: O(n1.14)O(n^{1.14}) instead of O(n2)O(n^2)

Key Hyperparameters:

  • n_neighbors (kk): Controls local vs global structure balance (typical: 5-50)
  • min_dist: Minimum separation in low-D embedding (typical: 0.0-0.99)
  • metric: Distance function in high-D space (Euclidean, cosine, etc.)

Output: Low-dimensional embedding YRn×d\mathbf{Y} \in \mathbb{R}^{n \times d'} (typically d=2d' = 2 or 33)

Derivation from First Principles

Step 1: Build the High-Dimensional Graph

For each point xix_i, find its kk nearest neighbors. We model the "connectedness" between points as fuzy sets.

The Distance-to-Similarity Transform:

For point xix_i and its neighbor xjx_j, compute:

wij=exp(max(0,dijρi)σi)w_{ij} = \exp\left(-\frac{\max(0, d_{ij} - \rho_i)}{\sigma_i}\right)

Why this formula?

  • dijd_{ij}: Distance between points ii and jj
  • ρi\rho_i: Distance to the nearest neighbor of xix_i (makes each point "see" at least one neighbor with weight ~1)
  • σi\sigma_i: Local bandwidth chosen so that jN(i)wij=log2(k)\sum_{j \in N(i)} w_{ij} = \log_2(k) (ensures consistent local density modeling)
  • The exponential decay creates a smooth transition: close neighbors get high weights, distant ones fade to zero

Why ρi\rho_i? This is the "local connectivity" constraint. Each point must see its immediate nearest neighbor fully connected (weight = 1) to avoid isolated points. We subtract ρi\rho_i so the decay starts after the first neighbor.

Symmetrization (fuzy set union):

wijsym=wij+wjiwijwjiw_{ij}^{\text{sym}} = w_{ij} + w_{ji} - w_{ij} \cdot w_{ji}

This creates an undirected graph where connection strength reflects fuzy topological membership.

Step 2: Define the Low-Dimensional Layout

In the low-D space, we want similar fuzy connectivity. Use a different kernel:

vij=11+ayiyj22bv_{ij} = \frac{1}{1 + a \cdot ||y_i - y_j||_2^{2b}}

Why this t-distributionlike kernel?

  • Allows both tight clusters (small distances) and separated groups (large distances)
  • Parameters a,ba, b (typically a=1.929,b=0.7915a=1.929, b=0.7915 from fitting) control the spread
  • Heavy tails prevent "crowding problem" where too many points compress into small space

Step 3: Optimize the Cross-Entropy Loss

We want the low-D fuzy structure to match the high-D one. Measure disagrement with cross-entropy:

L=i,jwijsymlog(wijsymvij)+(1wijsym)log(1wijsym1vij)\mathcal{L} = \sum_{i,j} w_{ij}^{\text{sym}} \log\left(\frac{w_{ij}^{\text{sym}}}{v_{ij}}\right) + (1 - w_{ij}^{\text{sym}}) \log\left(\frac{1 - w_{ij}^{\text{sym}}}{1 - v_{ij}}\right)

Breaking this down:

  1. First term: If high-D says "connected" (wijw_{ij} high), penalize if low-D disagrees (vijv_{ij} low)
  2. Second term: If high-D says "disconnected" (wijw_{ij} low), penalize if low-D has them close (vijv_{ij} high)

Why cross-entropy? It's the natural measure of difference between probability distributions (fuzy sets are modeled as probabilities).

Optimization: Use stochastic gradient descent with:

  • Negative sampling (sample unconnected pairs to enforce repulsion)
  • Initial layout via spectral embedding (for speed)
  • Typical: 500 epochs, learning rate starts at 1.0

High-D Edge Weight: wij=exp(max(0,dijρi)σi)w_{ij} = \exp\left(-\frac{\max(0, d_{ij} - \rho_i)}{\sigma_i}\right)

Low-D Edge Weight: vij=11+ayiyj22bv_{ij} = \frac{1}{1 + a \cdot ||y_i - y_j||_2^{2b}}

Optimization Objective: minYi,jwijsymlog(wijsymvij)+(1wijsym)log(1wijsym1vij)\min_{\mathbf{Y}} \sum_{i,j} w_{ij}^{\text{sym}} \log\left(\frac{w_{ij}^{\text{sym}}}{v_{ij}}\right) + (1 - w_{ij}^{\text{sym}}) \log\left(\frac{1 - w_{ij}^{\text{sym}}}{1 - v_{ij}}\right)

Scenario: Embedings of 1000 MNIST digits

With n_neighbors=5:

  • Each point looks at only 5 nearest neighbors
  • High-D graph is very sparse
  • Low-D embedding emphasizes local structure: tight, well-separated digit clusters
  • May fragment large manifolds into disconnected pieces

With n_neighbors=50:

  • Each point looks at 50 neighbors
  • High-D graph is denser, captures broader context
  • Low-D embedding preserves global structure: relationships between digit groups visible
  • Clusters may blend more at boundaries

Why this behavior? The σi\sigma_i parameter adjusts to fit log2(k)\log_2(k) total weight. With small kk, only immediate neighbors matter → local focus. With large kk, distant connections get nonzero weight → global awareness.

Rule of thumb:

  • Small data or finding fine clusters: k[5,15]k \in [5, 15]
  • Large data or preserving global structure: k[30,100]k \in [30, 100]

Setup: 500 cells from single-cell RNA-seq, 2000 genes

With min_dist=0.0:

  • Points allowed to packightly
  • Calculation: Low-D kernel vij=11+ad2bv_{ij} = \frac{1}{1 + a \cdot d^{2b}} can approach 1 even when d0d \to 0
  • Result: Dense clusters, clear separation, preserves local density information
  • Use case: Identifying tight cell type clusters

With min_dist=0.8:

  • Points must maintain spacing
  • Calculation: Optimization penalizes d<0.8d < 0.8, forces repulsion
  • Result: More "inflated" layout, easier to see individual points, loses some density info
  • Use case: Visualization where point overlap hides structure

Why this step? min_dist directly modifies the attractive force in the gradient. Higher values add repulsion at short range.

Given: Point xix_i with kk neighbors at distances di1,di2,,dikd_{i1}, d_{i2}, \ldots, d_{ik} (sorted). Nearest neighbor distance ρi=di1\rho_i = d_{i1}.

Goal: Find σi\sigma_i such that: j=1kexp(max(0,dijρi)σi)=log2(k)\sum_{j=1}^{k} \exp\left(-\frac{\max(0, d_{ij} - \rho_i)}{\sigma_i}\right) = \log_2(k)

Why log2(k)\log_2(k)? This comes from information theory: perplexity (effective number of neighbors) should match kk. In t-SNE terms, perplexity=2entropy\text{perplexity} = 2^{\text{entropy}}. UMAP targets entropy = log2(log2(k))\log_2(\log_2(k)) for numerical stability.

Solution via Binary Search:

  1. First neighbor: di1=ρid_{i1} = \rho_i, so wi1=exp(0)=1w_{i1} = \exp(0) = 1
  2. Other neighbors: wij=exp(dijρiσi)w_{ij} = \exp\left(-\frac{d_{ij} - \rho_i}{\sigma_i}\right) for j>1j > 1
  3. Target: 1+j=2kexp(dijρiσi)=log2(k)1 + \sum_{j=2}^{k} \exp\left(-\frac{d_{ij} - \rho_i}{\sigma_i}\right) = \log_2(k)

For k=15k=15: target =log2(15)3.906= \log_2(15) \approx 3.906

If σi\sigma_i too small → weights decay too fast → sum< target → increase σi\sigma_i If σi\sigma_i too large → weights decay too slowly → sum > target → decrease σi\sigma_i

Converge via binary search in ~20 iterations.

Example numbers (Manhattan distance on images):

  • k=15k = 15, ρi=45.2\rho_i = 45.2 pixels
  • Neighbor distances: 45.2, 52.1, 58.3, 67.8, 73.2, ...
  • Solved σi18.4\sigma_i \approx 18.4 pixels
  • Weights: 1.00, 0.71, 0.49, 0.28, 0.17, ... (sum≈ 3.906 ✓)

The Wrong Idea: UMAP and t-SNE do the same thing, UMAP is simply optimized better.

Why It Feels Right: Both produce2D scatter plots with clear clusters, both use neighbor graphs, both are nonlinear.

The Truth:

  1. Mathematical foundation differs:

    • t-SNE: KL-divergence between probability distributions
    • UMAP: Cross-entropy on fuzzy topological structures (category theory basis)
  2. Global structure:

    • t-SNE explicitly discards global distances (only preserves local neighborhoods)
    • UMAP balances local + global via the σi\sigma_i calibration and negative sampling strategy
  3. Inverse transform:

    • t-SNE: Cannot embed new points without retraining
    • UMAP: Can learn inverse mapping (new point → low-D) via parametric version
  4. Hyperparameter meaning:

    • t-SNE perplexity: "effective number of neighbors to consider"
    • UMAP n_neighbors: "balance local vs global" (affects graph connectivity fundamentally)

The Fix: Think of UMAP as "manifold learning with topological constraints" not "improved clustering visualization."

The Wrong Idea: "My dataset has 100,000 points, I'll use n_neighbors=5to keep computation fast."

Why It Feels Right: Smaller kk → sparser graph → faster computation.

The Problem:

  • With 100k points and k=5k=5, you have 500k edges
  • But the data may have natural clusters of size ~10,000
  • Each point only "sees" 5 neighbors → only local structure captured
  • Result: Large coherent structures fragment into many disconnected pieces
  • You get "archipelagos" instead of continents

The Fix:

  • For nn points, use k0.5nk \geq 0.5\sqrt{n} as minimum for global structure
  • For 100k points: use k150k \geq 150
  • UMAP's approximations keep this fast (nearest neighbor search via random projection forests)

Verification: Check graph connectivity:

from umap import UMAP
from scipy.sparsecsgraph import connected_components
 
umap_model = UMAP(n_neighbors=5)
umap_model.fit(X)
graph = umap_model.graph_
n_components, labels = connected_components(graph)
print(f"Disconnected components: {n_components}")  # Should be ~1, not ~1000
Recall Explain UMAP to a 12-year-old

Imagine you have a huge crumpled ball of yarn with1000 knots (your data points). The yarn has some structure—some knots are close together forming bunches, some are far apart. You want to lay this whole tangled mess flat on a table so you can see the pattern, but you need two rules:

Rule 1: Knots that are neighbors in the ball should stay neighbors on the table. If two knots were touching, don't put them on opposite sides of the table!

Rule 2: If two bunches of knots were far apart in the ball, keep them far apart on the table too. Don't make everything smosh into one blob.

UMAP's job is to untangle the yarn following both rules. Here's how:

  1. Build a friendship network: Each knot looks at its 15 closest neighbors and says "these are my friends" with different levels of friendship (super close friends get score 1.0, acquaintances get score 0.2).

  2. Make a flat map: Put all the knots on the table randomly to start. Now move them around: pull friends closer together, push non-friends farther apart.

  3. Keep adjusting: Do this 500 times until the friendship network on the table matches the friendship network in the original tangled ball.

The magic? UMAP doesn't just care about immediate neighbors (like t-SNE). It looks at your15 closest friends, and through them, learns about the whole neighborhood structure. That's why the final flat map shows both tight friend groups AND how those groups relate to each other across the table.

  • Unfold: Take curved high-D manifold and flatten it
  • Manifolds: Data lies on curved surfaces, not just in Euclidean space
  • And: Both local AND global structure (not "or")
  • Preserve: Keep topological relationships intact

Alternative: "Use My Awesome Projection" (when your t-SNE is too slow)

Hyperparameter Tuning Guide

Parameter Effect on Embedding Typical Range Choose Higher When Choose Lower When
n_neighbors Local↔ Global balance 5-100 Large dataset, want global structure Small dataset, want tight clusters
min_dist Cluster tightness 0.0-0.99 Want separated points, better viz Want accurate local density
metric Distance definition euclidean, cosine, etc. Data type demands (text→cosine) Euclidean works (images, tabular)
n_components Output dimensions 2-100 Downstream ML task Just visualization

Connections to Other Concepts

  • t-SNE: UMAP's predecessor for visualization, focuses only on local structure
  • PCA: Linear dimensionality reduction, fast but mises manifolds
  • Autoencoders: Neural alternative for dimensionality reduction with inverse mapping
  • Isomap: Earlier manifold learning method via geodesic distances
  • Spectral Clustering: Uses similar graph Laplacian concepts for initialization
  • Nearest Neighbors Algorithms: UMAP relies heavily on fast KNN search
  • Cross-Entropy Loss: Core optimization objective for matching distributions
  • Random Projection: Used internally for approximate nearest neighbor search
  • Topological Data Analysis: Provides mathematical foundation for fuzy simplicial sets

When to Use UMAP vs Alternatives

Use UMAP when:

  • Dataset size: 1k-10M points (scales well)
  • Need both local clusters AND global structure
  • Want reproducible results (set random_state)
  • Need to embed new points later (parametric UMAP)
  • Computational constraints (faster than t-SNE)

Use t-SNE when:

  • Dataset size: <10k points
  • Only care about local cluster separation for visualization
  • Have tried UMAP and clusters blend too much (increase n_neighbors if so)

Use PCA when:

  • Need linear interpretability (loadings)
  • Data actually is linear (rare!)
  • Want deterministic results
  • Need fast transforms for millions of points

Use Autoencoders when:

  • Have GPU resources
  • Need differentiable inverse mapping
  • Want to combine with other neural network losses

#flashcards/ai-ml

What does UMAP stand for? :: Uniform Manifold Approximation and Projection

What is the key difference between UMAP and t-SNE in terms of structure preservation?
UMAP preserves both local neighborhoods AND global structure; t-SNE focuses only on local structure and discards global distances
What is the role of the parameter ρᵢ in UMAP's edge weight formula?
ρᵢ is the distance to the nearest neighbor of point xᵢ. It ensures local connectivity by making the nearest neighbor have weight ≈1 (the exponential decay starts after ρᵢ)
What is the purpose of the σᵢ parameter in UMAP?
σᵢ is the local bandwidth parameter chosen so that the sum of edge weights equals log₂(k), ensuring consistent local density modeling across all points
Why does UMAP use cross-entropy as its loss function?
Cross-entropy measures the difference between probability distributions. UMAP models high-D and low-D structures as fuzy probability sets, so cross-entropy quantifies how well the low-D layout matches the high-D topology
What happens if you set n_neighbors too small on a large dataset?
The graph becomes too sparse and only captures local structure, causing large coherent structures to fragment into many disconnected components ("archipelagos")
What is the typical computational complexity of UMAP?
O(n^1.14) due to approximate nearest neighbor search and sparse graph optimization, compared to O(n²) for t-SNE
How does the min_dist parameter affect UMAP embedings?
min_dist controls minimum point separation in low-D space. Lower values (→0.0) create denser clusters preserving local density; higher values (→0.99) create more spread-out layouts for better visualization
What is the fuzy set union formula UMAP uses for symmetrization?
w_ij^sym = w_ij + w_ji - w_ij · w_ji (probabilistic OR operation for combining directed edges)
Why does UMAP's low-D kernel use the form1/(1 + a·d^(2b)) instead of exponential decay?
The heavy-tailed t-distribution-like kernel prevents the "crowding problem" by allowing both tight local clusters and well-separated global groups without compression
What does it mean that UMAP has a "parametric" version?
Parametric UMAP learns a neural network mapping from high-D to low-D, allowing new points to be embedded without retraining (unlike standard t-SNE)
What is the target value for the sum of edge weights in UMAP and why?
log₂(k) where k is n_neighbors. This comes from perplexity calibration ensuring effective number of neighbors matches k, analogous to t-SNE's perplexity but adapted for UMAP's framework
What initialization does UMAP typically use for the low-D layout?
Spectral embedding (eigenvectors of graph Laplacian) to start near a good solution and speed up convergence
How does UMAP handle negative sampling in optimization?
During SGD, UMAP samples unconnected point pairs and applies repulsive forces to prevent all points from collapsing together, balancing the attractive forces from connected edges
What is a rule of thumb for choosing n_neighbors based on dataset size?
For n points, use at minimum k ≥ 0.5√n to maintain global structure connectivity. For 100k points, this suggests k ≥ 150

Concept Map

motivates

modeled by

step 1 build

distance-to-similarity

fuzzy union

step 2 define

compared with

compared with

optimizes into

n_neighbors controls

min_dist and a,b shape

High-D Data on Manifold

Limits of PCA and t-SNE

UMAP Embedding

k Nearest Neighbors Graph

High-D Fuzzy Weights w_ij

Symmetrized Graph

Low-D Fuzzy Weights v_ij

Match Two Structures

Hyperparameters

Low-D Embedding Y

Hinglish (regional understanding)

Intuition Hinglish mein samjho

UMAP ek powerful technique hai jo high-dimensional data ko 2D ya 3D mein visualize karne ke liye use hoti hai, par ye sirf visualization sezyada hai. Socho tumhare pas 10,000 features wala dataset hai (jaise genomics data ya image pixels) — PCA ye linearly project karega aur manifold structure miss ho jayega, t-SNE sirf local clusters dikhayega par global relationships kho jayengi. UMAP ka genius ye hai ki wo dono balance karta hai: local neighborhoods ko preserve kare AUR overall data landscape ka shape bhi maintain kare.

Technique simple hai conceptually: pehle high-dimensional space mein har point apne k-nearest neighbors dekhe aur unse "connection strength" calculate kare (exponential decay function use karke, jahan nearest neighbor ko hamesha full weight mile). Phir low-dimensional space mein points ko randomly place karo aur iteratively move karo — connected points ko pas lao, disconnected ko door rakho. Optimization cross-entropy loss minimize karta hai, jo essentially keh raha hai "high-D graph aur low-D graph ka topology match karo."

Key hyperparameters simple hain: n_neighbors control karta hai local vs global balance (small value = tight clusters focus, large value = global structure preserved), aur min_dist control karta hai ki low-D mein points kitne pas aa sakte hain (0.0 = dense clusters, 0.8 = spread out for better viz). Real-world applications mein — single-cell biology se lekar recommendation systems tak — UMAP ne t-SNE ko replace kar diya hai kyunki ye faster hai (lakh points bhi handle kare), reproducible hai, aur global structure preserve karta hai jo downstream clustering aur analysis ke liye zaroori hai.

Mathematical beauty ye hai ki UMAP fuzy topological structures use karta hai (category theory se inspired), matlab har point-pair ko

Go deeper — visual, from zero

Test yourself — Unsupervised Learning

Connections