t-SNE for visualization
The Core Idea
Goal: Map high-dimensional points to low-dimensional points (or 3D) such that similar points stay similar.
How?
- In high-D space, define a probability that point picks as its neighbor (based on Gaussian similarity).
- In low-D space, define a probability thatij$ (using a t-distribution with1 degree of freedom, heavier tails).
- Make match by minimizing the KL-divergence: .
Why t-distribution in low-D? The crowding problem: in100D, you can fit many points equidistant from a center. In 2D, they'd overlap. The t-distribution's heavy tails let moderately-distant points spread out more, reducing overlap.
Step-by-Step Derivation
Step 1: High-Dimensional Similarities
For each point , we compute conditional probability that picks as neighbor:
Why Gaussian? We model similarity as a Gaussian centered at . The (called perplexity in practice) controls neighborhood size.
Symmetrize to get joint probability:
Why symmetrize? So (no direction bias), and (valid probability distribution).
Step 2: Low-Dimensional Similarities
In 2D, use Student's t-distribution (1 degree of freedom):
Why t-distribution? Compare to Gaussian in low-D:
- Gaussian: → decays fast, far points vanish.
- t-distribution: → decays slower (heavy tail), far points still contribute, giving them room to spread.
Step 3: Minimize KL Divergence
The cost function is:
Why this direction (not )? heavily penalizes (nearby points pushed apart) but lightly penalizes (far points too close). We care more about preserving local structure (nearby points), so this asymetry is correct.
Gradient:
Why this gradient?
- : If , points are too far in2D → pull together. If , they're too close → push apart.
- : direction of force.
- : the t-distribution weight, ensures smooth gradients.
We optimize via gradient descent (often with momentum + early exaggeration trick).
Hyperparameters
Other key parameters:
- Learning rate (typically 100–1000): too low = slow convergence, too high = instability.
- Number of iterations (1000–5000): t-SNE optimizes via gradient descent, needs many steps.
- Early exaggeration (first ~250 iterations): multiply by 4 to create tight, well-separated clusters, then reduce to 1 for fine-tuning.
Worked Example1: 3D Gaussian Blobs to 2D
Data: 3 clusters in 3D, each cluster is a Gaussian blob with 100 points.
Cluster A: centered at (0,0,0), σ=0.5
Cluster B: centered at (5,0,0), σ=0.5
Cluster C: centered at (2.5, 4, 0), σ=0.5
Step 1: Compute for all pairs (300 × 299 / 2 = 44,850 pairs).
- For two points in cluster A, , so is large.
- For a point in A and a point in B, , so .
Step 2: Initialize randomly in2D (say, uniform in ).
Step 3: Compute (initially all similar, ~1/44850).
Step 4: Compute gradient. Example: if point in cluster A is far from its true neighbor in2D, , gradient pulls them together.
Why this step? The gradient descent iteratively adjusts to make the2D distribution match the high-D distribution .
Iterations: After 1000 steps, clusters A, B, C form3 distinct blobs in 2D. Global distances (A-to-B vs A-to-C) may be distorted, but within-cluster and between-cluster separation is preserved.
Worked Example 2: MNIST Digits
Data: 60,000 images 784 pixels each (28×28 flattened).
Perplexity = 30: Each digit considers ~30 neighbors.
Process:
- Compute for60k points (sparse: only store top neighbors per point, ~1.8 billion pairs total → use approximate methods like Barnes-Hut to speed up).
- Run gradient descent for 5000 iterations.
- Result: 10 distinct clusters (one per digit 0-9) in 2D. Some overlap (e.g., 4 and 9 are visually similar).
Why is this useful? A human can now visually inspect the learned representation: Are there outliers? Do digits form coherent clusters? Is there a smooth transition (manifold) between similar digits?
Common Mistakes
Comparison: PCA vs t-SNE
| Aspect | PCA | t-SNE | |--------|----| | Preserves | Global variance (linear) | Local neighborhoods (non-linear) | | Deterministic? | Yes | No (random init) | | Speed | Fast () | Slow (, ~ with Barnes-Hut) | | Interpretable axes? | Yes (principal components) | No (arbitrary coordinates) | | Use case | Quick EDA, preprocessing | Final visualization for publication/EDA |
Algorithm Pseudocode
1. Compute pairwise squared distances in high-D: D[i,j] = ||x_i - x_j||²
2. For each point i:
Binary search σ_i to achieve desired perplexity
Compute p_j|i = exp(-D[i,j] / 2σ_i²) / Σ_k exp(-D[i,k] / 2σ_i²)
3. Symmetrize: p_ij = (p_j|i + p_i|j) / 2n
4. Initialize y_i ~ N(0,10⁻⁴ I) randomly in 2D
5. For t = 1 to max_iter:
Compute q_ij = (1 + ||y_i - y_j||²)⁻¹ / Z
Compute gradient: ∂C/∂y_i = 4 Σ_j (p_ij - q_ij)(y_i - y_j)(1 + ||y_i - y_j||²)⁻¹
Update y_i via gradient descent with momentum
(Optional: early exaggeration in first 250 iters)
6. Return y_1, .., y_n (2D coordinates)
Why t-SNE Works: The Math Intuition
Crowding problem: In 100D, a sphere of radius has volume . In 2D, volume . So 100D neighbors can't all fit equidistant in 2D → they'd crowd/overlap.
Solution: The t-distribution decays like for large , much slower than Gaussian's . This gives heavy tails: moderately-far points in 2D can still have non-negligible , so they repel less and spread out naturally.
Force analogy: Each pair exerts a force:
- Attractive if (they should be closer).
- Repulsive if (they should be farther).
- The equilibrium is a local minimum of KL.
Recall Feynman Explanation (ELI12)
Imagine you have a giant map of a country with 100 roads connecting every city. You want to draw a simple2D map on paper. The problem: you can't fit all 100 roads without overlapping!
t-SNE is like a smart artist who says: "I'll keep close friends (neighboring cities) close on the paper. Far-away cities? I'll just push them somewhere far, even if the exact distance is wrong."
Why does it work? The artist uses a magic pen (the t-distribution) that lets moderately-far cities spread out smoothly without crashing into each other. A normal pen (Gaussian) would make them overlap.
So the final map shows neighborhoods clearly (you can see clusters), but the distance between clusters is squishy. Don't measure with a ruler—just enjoy the view!
Connections
- 2.5.1 PCA: Linear dimensionality reduction, preserves global variance. t-SNE is non-linear, preserves local structure.
- 2.5.10 UMAP: Similar goal (local structure preservation), but faster and deterministic with hyperparameters. Often compared to t-SNE.
- 2.4.3 K-Means Clustering: After t-SNE visualization, you might use k-means on the original high-D data to formally cluster.
- 3.2.1 Autoencoders: Non-linear dimensionality reduction via neural networks. Can be used for visualization + downstream tasks (unlike t-SNE).
- 1.3.5 KL Divergence: The core loss function in t-SNE. Understanding KL(P||Q) asymetry is crucial.
- 2.5.9 Manifold Learning: t-SNE assumes data lies on a low-D manifold in high-D space.
When to Use t-SNE
✅ Use when:
- You have high-dimensional data (50+ features) and want to visualize clusters for human interpretation.
- You need to explore data before modeling (EDA).
- You're presenting results in a paper/report and want a compelling2D scatter plot.
❌ Don't use when:
- You need reproducible, deterministic embedings (use PCA or UMAP).
- You need to embed new test data (t-SNE has no inverse mapping; use parametric t-SNE or autoencoders).
- Data is already low-D (3–5 features): just use scatter plots or PCA.
- You need embedings for downstream ML tasks (classification, regression): use PCA, LDA, or autoencoders.
Practical Tips
- Perplexity: Start with 30. Increase for large datasets (1M points → perplexity 50–100), decrease for tiny datasets (100 points → perplexity 5–15).
- Multiple runs: t-SNE is stochastic. Run 3–5 times with different seeds and check consistency. If results vary wildly, your data may not have clear structure.
- Preprocessing: Standardize features (mean=0, std=1) before t-SNE. High-variance features dominate distances.
- Coloring: Color points by known labels (if available) to validate cluster separation.
- Barnes-Hut approximation: For , use Barnes-Hut t-SNE (available in scikit-learn) to reduce complexity from to .
#flashcards/ai-ml
What does t-SNE stand for? :: t-Distributed Stochastic Neighbor Embedding
What is the primary goal of t-SNE?
Why does t-SNE use a t-distribution in low-D instead of a Gaussian?
What is the cost function t-SNE minimizes?
What is perplexity in t-SNE?
Why is t-SNE stochastic?
Can you use t-SNE embedings for training a classifier?
What does the gradient term tell us?
Why shouldn't you interpret global distances in a t-SNE plot?
What is the crowding problem?
High-D conditional probability formula in t-SNE?
Low-D similarity formula in t-SNE? ::
What is early exaggeration in t-SNE?
What is the typical complexity of t-SNE?
When should you use t-SNE over PCA?
Concept Map
Hinglish (regional understanding)
Intuition Hinglish mein samjho
Dekho, t-SNE ek aisa technique hai jo high-dimensional data ko 2D ya 3D mein visualize karne ke liye use hota hai. Socho tumhare pas 100 features hain (jaise 100 different measurements ofek image ya sensor data), aur tum chahte ho ki isko ek simple 2D graph pe plot karo taki patterns dikh sakein. PCA bhi yeh karta hai, lekin PCA sirf global variance dekhta hai—matlab overall spread. Agar tumhare data mein complex clusters hain jo non-linear hain (curved shapes, spirals), toh PCA unko squash kar dega aur sab ek dusre ke upar aa jaayenge.
t-SNE ka magic yeh hai ki yeh local neighborhoods preserve karta hai. Matlabagar do points high-dimensional space mein pas hain, toh 2D plot mein bhi pas rahenge. Yeh Gaussian similarity se high-D mein probability nikalta hai (kitna pas hain), aur low-D mein t-distribution use karta hai (jo heavy tails deta hai, matlab moderately-far points ko bhi jagah milti hai bina overlap kiye). Phir dono distributions ko match karne ke liye gradient descent chalata hai—ek force-based system jaise magnets attract ya repel karte hain. End result: clusters clearly alag-alag dikhte hain, aur tum visually samajh sakte ho ki data mein kya structure hai.
Lekin dhyan rakhna—t-SNE sirf visualization ke liye hai. Ismein randomness hai (har baar thoda alag result), aur global distances matlab nahi rakhte (cluster A aur B ke bech ki distance arbitrary hai). Isko downstream machine learning mein use mat karo (jaise classifier train karna); uske liye PCA ya autoencoder use karo. t-SNE ka use tab karo jab tumhe apne data ko explore karna ho ya paper mein ek clear, beautiful plot chahiye jo clusters dikhaye. Perplexity hyperparameter (typically 30) set karna zaroori hai—yeh control karta hai ki kitne neighbors consider kiye jayein. Zyada data ho toh perplexity badha do (50-100), kam ho toh ghatado (5-15). Multiple runs karo different random seeds ke sath to confirm ki clusters consistent hain. Overall, t-SNE ek powerful tool hai complex data ko samajhne ke liye—bas global distances ka interpretation mat karo, sirf local structure aur cluster separation dekho!