UMAP for dimensionality reduction
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:
- Non-deterministic layout between runs
- Doesn't preserve density information
UMAP's Solution:
- Model high-D data as a fuzy topological structure (Riemannian manifold)
- Construct a similar structure in low-D
- Find the layout that makes these two structures as similar as possible
- Use clever approximations to make it fast: instead of
Key Hyperparameters:
- n_neighbors (): 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 (typically or )
Derivation from First Principles
Step 1: Build the High-Dimensional Graph
For each point , find its nearest neighbors. We model the "connectedness" between points as fuzy sets.
The Distance-to-Similarity Transform:
For point and its neighbor , compute:
Why this formula?
- : Distance between points and
- : Distance to the nearest neighbor of (makes each point "see" at least one neighbor with weight ~1)
- : Local bandwidth chosen so that (ensures consistent local density modeling)
- The exponential decay creates a smooth transition: close neighbors get high weights, distant ones fade to zero
Why ? This is the "local connectivity" constraint. Each point must see its immediate nearest neighbor fully connected (weight = 1) to avoid isolated points. We subtract so the decay starts after the first neighbor.
Symmetrization (fuzy set union):
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:
Why this t-distributionlike kernel?
- Allows both tight clusters (small distances) and separated groups (large distances)
- Parameters (typically 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:
Breaking this down:
- First term: If high-D says "connected" ( high), penalize if low-D disagrees ( low)
- Second term: If high-D says "disconnected" ( low), penalize if low-D has them close ( 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:
Low-D Edge Weight:
Optimization Objective:
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 parameter adjusts to fit total weight. With small , only immediate neighbors matter → local focus. With large , distant connections get nonzero weight → global awareness.
Rule of thumb:
- Small data or finding fine clusters:
- Large data or preserving global structure:
Setup: 500 cells from single-cell RNA-seq, 2000 genes
With min_dist=0.0:
- Points allowed to packightly
- Calculation: Low-D kernel can approach 1 even when
- 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 , 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 with neighbors at distances (sorted). Nearest neighbor distance .
Goal: Find such that:
Why ? This comes from information theory: perplexity (effective number of neighbors) should match . In t-SNE terms, . UMAP targets entropy = for numerical stability.
Solution via Binary Search:
- First neighbor: , so
- Other neighbors: for
- Target:
For : target
If too small → weights decay too fast → sum< target → increase If too large → weights decay too slowly → sum > target → decrease
Converge via binary search in ~20 iterations.
Example numbers (Manhattan distance on images):
- , pixels
- Neighbor distances: 45.2, 52.1, 58.3, 67.8, 73.2, ...
- Solved 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:
-
Mathematical foundation differs:
- t-SNE: KL-divergence between probability distributions
- UMAP: Cross-entropy on fuzzy topological structures (category theory basis)
-
Global structure:
- t-SNE explicitly discards global distances (only preserves local neighborhoods)
- UMAP balances local + global via the calibration and negative sampling strategy
-
Inverse transform:
- t-SNE: Cannot embed new points without retraining
- UMAP: Can learn inverse mapping (new point → low-D) via parametric version
-
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 → sparser graph → faster computation.
The Problem:
- With 100k points and , 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 points, use as minimum for global structure
- For 100k points: use
- 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 ~1000Recall 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:
-
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).
-
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.
-
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?
What is the role of the parameter ρᵢ in UMAP's edge weight formula?
What is the purpose of the σᵢ parameter in UMAP?
Why does UMAP use cross-entropy as its loss function?
What happens if you set n_neighbors too small on a large dataset?
What is the typical computational complexity of UMAP?
How does the min_dist parameter affect UMAP embedings?
What is the fuzy set union formula UMAP uses for symmetrization?
Why does UMAP's low-D kernel use the form1/(1 + a·d^(2b)) instead of exponential decay?
What does it mean that UMAP has a "parametric" version?
What is the target value for the sum of edge weights in UMAP and why?
What initialization does UMAP typically use for the low-D layout?
How does UMAP handle negative sampling in optimization?
What is a rule of thumb for choosing n_neighbors based on dataset size?
Concept Map
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