2.5.11Unsupervised Learning

t-SNE for visualization

2,921 words13 min readdifficulty · medium

The Core Idea

Goal: Map high-dimensional points x1,,xnRd\mathbf{x}_1, \ldots, \mathbf{x}_n \in \mathbb{R}^d to low-dimensional points y1,,ynR2\mathbf{y}_1, \ldots, \mathbf{y}_n \in \mathbb{R}^2 (or 3D) such that similar points stay similar.

How?

  1. In high-D space, define a probability pijp_{ij} that point ii picks jj as its neighbor (based on Gaussian similarity).
  2. In low-D space, define a probability qijq_{ij} thatipickspicksj$ (using a t-distribution with1 degree of freedom, heavier tails).
  3. Make qijq_{ij} match pijp_{ij} by minimizing the KL-divergence: KL(PQ)=ijpijlogpijqij\text{KL}(P \| Q) = \sum_{i \neq j} p_{ij} \log \frac{p_{ij}}{q_{ij}}.

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 pijp_{ij}

For each point ii, we compute conditional probability that ii picks jj as neighbor:

pji=exp(xixj2/2σi2)kiexp(xixk2/2σi2)p_{j|i} = \frac{\exp\left(-\|\mathbf{x}_i - \mathbf{x}_j\|^2 / 2\sigma_i^2\right)}{\sum_{k \neq i} \exp\left(-\|\mathbf{x}_i - \mathbf{x}_k\|^2 / 2\sigma_i^2\right)}

Why Gaussian? We model similarity as a Gaussian centered at xi\mathbf{x}_i. The σi\sigma_i (called perplexity in practice) controls neighborhood size.

Symmetrize to get joint probability:

pij=pji+pij2np_{ij} = \frac{p_{j|i} + p_{i|j}}{2n}

Why symmetrize? So pij=pjip_{ij} = p_{ji} (no direction bias), and ijpij=1\sum_{ij} p_{ij} = 1 (valid probability distribution).

Step 2: Low-Dimensional Similarities qijq_{ij}

In 2D, use Student's t-distribution (1 degree of freedom):

qij=(1+yiyj2)1kl(1+ykyl2)1q_{ij} = \frac{\left(1 + \|\mathbf{y}_i - \mathbf{y}_j\|^2\right)^{-1}}{\sum_{k \neq l} \left(1 + \|\mathbf{y}_k - \mathbf{y}_l\|^2\right)^{-1}}

Why t-distribution? Compare to Gaussian in low-D:

  • Gaussian: eyiyj2e^{-\|\mathbf{y}_i - \mathbf{y}_j\|^2} → decays fast, far points vanish.
  • t-distribution: (1+yiyj2)1(1 + \|\mathbf{y}_i - \mathbf{y}_j\|^2)^{-1} → decays slower (heavy tail), far points still contribute, giving them room to spread.

Step 3: Minimize KL Divergence

The cost function is:

C=KL(PQ)=ijpijlogpijqijC = \text{KL}(P \| Q) = \sum_{i \neq j} p_{ij} \log \frac{p_{ij}}{q_{ij}}

Why this direction (not KL(QP)\text{KL}(Q \| P))? KL(PQ)\text{KL}(P \| Q) heavily penalizes qijpijq_{ij} \ll p_{ij} (nearby points pushed apart) but lightly penalizes qijpijq_{ij} \gg p_{ij} (far points too close). We care more about preserving local structure (nearby points), so this asymetry is correct.

Gradient:

Cyi=4ji(pijqij)(yiyj)(1+yiyj2)1\frac{\partial C}{\partial \mathbf{y}_i} = 4 \sum_{j \neq i} \left(p_{ij} - q_{ij}\right) \left(\mathbf{y}_i - \mathbf{y}_j\right) \left(1 + \|\mathbf{y}_i - \mathbf{y}_j\|^2\right)^{-1}

Why this gradient?

  • (pijqij)(p_{ij} - q_{ij}): If pij>qijp_{ij} > q_{ij}, points i,ji,j are too far in2D → pull together. If pij<qijp_{ij} < q_{ij}, they're too close → push apart.
  • (yiyj)(\mathbf{y}_i - \mathbf{y}_j): direction of force.
  • (1+2)1(1 + \|\cdots\|^2)^{-1}: 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 pijp_{ij} 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 pijp_{ij} for all pairs (300 × 299 / 2 = 44,850 pairs).

  • For two points in cluster A, xixj20.5\|\mathbf{x}_i - \mathbf{x}_j\|^2 \approx 0.5, so pijp_{ij} is large.
  • For a point in A and a point in B, xixj225\|\mathbf{x}_i - \mathbf{x}_j\|^2 \approx 25, so pij0p_{ij} \approx 0.

Step 2: Initialize yi\mathbf{y}_i randomly in2D (say, uniform in [0.001,0.0001][-0.001, 0.0001]).

Step 3: Compute qijq_{ij} (initially all similar, ~1/44850).

Step 4: Compute gradient. Example: if point ii in cluster A is far from its true neighbor jj in2D, pijqij>0p_{ij} - q_{ij} > 0, gradient pulls them together.

Why this step? The gradient descent iteratively adjusts yi\mathbf{y}_i to make the2D distribution QQ match the high-D distribution PP.

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:

  1. Compute pijp_{ij} for60k points (sparse: only store top neighbors per point, ~1.8 billion pairs total → use approximate methods like Barnes-Hut to speed up).
  2. Run gradient descent for 5000 iterations.
  3. 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 (O(nd2)O(nd^2)) | Slow (O(n2)O(n^2), ~O(nlogn)O(n \log n) 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 rr has volume r100\propto r^{100}. In 2D, volume r2\propto r^2. So 100D neighbors can't all fit equidistant in 2D → they'd crowd/overlap.

Solution: The t-distribution (1+d2)1(1 + d^2)^{-1} decays like d2d^{-2} for large dd, much slower than Gaussian's ed2e^{-d^2}. This gives heavy tails: moderately-far points in 2D can still have non-negligible qijq_{ij}, so they repel less and spread out naturally.

Force analogy: Each pair (i,j)(i,j) exerts a force:

  • Attractive if pij>qijp_{ij} > q_{ij} (they should be closer).
  • Repulsive if pij<qijp_{ij} < q_{ij} (they should be farther).
  • The equilibrium pij=qijp_{ij} = q_{ij} 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

  1. Perplexity: Start with 30. Increase for large datasets (1M points → perplexity 50–100), decrease for tiny datasets (100 points → perplexity 5–15).
  2. 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.
  3. Preprocessing: Standardize features (mean=0, std=1) before t-SNE. High-variance features dominate distances.
  4. Coloring: Color points by known labels (if available) to validate cluster separation.
  5. Barnes-Hut approximation: For n>5000n > 5000, use Barnes-Hut t-SNE (available in scikit-learn) to reduce complexity from O(n2)O(n^2) to O(nlogn)O(n \log n).

#flashcards/ai-ml

What does t-SNE stand for? :: t-Distributed Stochastic Neighbor Embedding

What is the primary goal of t-SNE?
To map high-dimensional data to 2D/3D while preserving local neighborhood structure (similar points stay close).
Why does t-SNE use a t-distribution in low-D instead of a Gaussian?
The t-distribution has heavier tails, which solves the crowding problem by allowing moderately-far points to spread out naturally without overlapping.
What is the cost function t-SNE minimizes?
KL divergence: KL(PQ)=ijpijlogpijqij\text{KL}(P \| Q) = \sum_{i \neq j} p_{ij} \log \frac{p_{ij}}{q_{ij}}, where PP is high-D similarity and QQ is low-D similarity.
What is perplexity in t-SNE?
A hyperparameter controlling the effective number of neighbors each point considers (typically 5–50). It's 2H(Pi)2^{H(P_i)} where HH is entropy of the conditional distribution.
Why is t-SNE stochastic?
It uses random initialization of low-D coordinates and gradient descent, so different runs give different embedings (though cluster structure should be consistent).
Can you use t-SNE embedings for training a classifier?
No. t-SNE is for visualization only—it's non-parametric (no explicit mapping for new data) and stochastic. Use PCA or autoencoders for downstream tasks.
What does the gradient term (pijqij)(p_{ij} - q_{ij}) tell us?
If pij>qijp_{ij} > q_{ij}, points i,ji,j are too far in 2D (attractive force pulls them together). If pij<qijp_{ij} < q_{ij}, they're too close (repulsive force pushes apart).
Why shouldn't you interpret global distances in a t-SNE plot?
t-SNE only preserves local structure. The distance between clusters is arbitrary and can be distorted. Only cluster separation and density are meaningful.
What is the crowding problem?
In high dimensions, many points can be equidistant from a center (large volume). In 2D, they'd overlap (small volume). t-SNE's t-distribution solves this with heavy tails.
High-D conditional probability formula in t-SNE?
pji=exp(xixj2/2σi2)kiexp(xixk2/2σi2)p_{j|i} = \frac{\exp\left(-\|\mathbf{x}_i - \mathbf{x}_j\|^2 / 2\sigma_i^2\right)}{\sum_{k \neq i} \exp\left(-\|\mathbf{x}_i - \mathbf{x}_k\|^2 / 2\sigma_i^2\right)}

Low-D similarity formula in t-SNE? :: qij=(1+yiyj2)1kl(1+ykyl2)1q_{ij} = \frac{\left(1 + \|\mathbf{y}_i - \mathbf{y}_j\|^2\right)^{-1}}{\sum_{k \neq l} \left(1 + \|\mathbf{y}_k - \mathbf{y}_l\|^2\right)^{-1}}

What is early exaggeration in t-SNE?
Multiplying pijp_{ij} by 4 in the first ~250 iterations to create tight, well-separated clusters, then reducing to 1 for fine-tuning.
What is the typical complexity of t-SNE?
O(n2)O(n^2) for exact computation. Barnes-Hut approximation reduces it to O(nlogn)O(n \log n) for large datasets.
When should you use t-SNE over PCA?
When you need to visualize complex, non-linear cluster structures. PCA is better for quick EDA, preprocessing, or when you need interpretable axes.

Concept Map

Gaussian similarity

controls neighborhood

make symmetric

valid distribution

t-distribution similarity

match P

motivates heavy tails

minimize via

updates positions

penalizes near-point split

goal of

High-D data

Prob p_ij Gaussian

Prob q_ij t-distribution

Perplexity sigma_i

Symmetrize

KL divergence cost

Gradient descent

2D embedding

Crowding problem

Local neighborhoods preserved

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!

Go deeper — visual, from zero

Test yourself — Unsupervised Learning

Connections