t-Distributed Stochastic Neighbor Embedding (t-SNE)
t-SNE is a non-linear dimensionality-reduction method used mainly to visualize high-dimensional data in two or three dimensions. Its central idea is simple: if two samples are close neighbors in the original feature space, t-SNE tries to place them close together on the map.
t-SNE in Simple Words
The central objective
Preserve useful local neighborhood relationships when making a low-dimensional visualization.
t-SNE is commonly used to inspect embeddings, image features, text representations, biological measurements and other datasets where each sample may have tens, hundreds or thousands of values. It is an exploratory visualization tool, not a classifier and not proof that visible groups are real-world classes.
Why t-SNE Is Useful
Humans can easily inspect a scatter plot with two or three axes, but not a point described by 64, 500 or 1,000 features. t-SNE gives us a low-dimensional map that can make local relationships easier to inspect.
Example: E-commerce customers
Imagine every customer is represented by browsing, purchase, category-interest and engagement features. We cannot directly draw a 500-dimensional scatter plot. t-SNE can map those samples into 2D so we can inspect which customers end up as local neighbors.
PCA and t-SNE answer different questions
| PCA | t-SNE |
|---|---|
| Linear transformation | Non-linear embedding |
| Focuses on directions of feature variance | Focuses strongly on neighborhood probabilities |
| Has reusable components for later transformation | Scikit-learn t-SNE is primarily a fit-and-visualize workflow |
PCA can be a useful first step before t-SNE when the original feature count is very high. Reducing to a moderate number of dimensions first can remove some noise and make t-SNE faster.
Core Philosophy of t-SNE
One idea per visual: keep close neighbors close
High-dimensional space
C •
D • • E
2D t-SNE map
C •
D • E •
Illustration only. Absolute positions, axes and cluster spacing are not direct measurements of the original feature space.
Think of a classroom friendship map. If Alice's closest friends are Bob and Carla, a useful map should try to keep Bob and Carla near Alice. But the exact distance between the “football group” and the “music group” should not automatically be interpreted as a precise real-world distance.
A t-SNE plot is not a clustering algorithm
t-SNE can make visually separated islands even though it is not directly assigning semantic cluster labels. If you need formal clustering, use and evaluate a clustering method separately rather than treating every visible island as a guaranteed class.
Fundamental Concepts in t-SNE
1. Similarities
Convert high-dimensional neighborhood relationships into probabilities.
2. Low-dimensional map
Represent low-dimensional similarities with a heavy-tailed t-distribution.
3. Optimization
Move map points to reduce the mismatch measured by KL divergence.
Distance & high-dimensional similarity
With the default metric, t-SNE starts from Euclidean-style relationships between samples and converts distances into neighborhood probabilities. A smaller distance generally means a stronger neighborhood relationship.
Euclidean distance: easy worked example
A = (1, 2), B = (4, 6)
d = √[(4 − 1)² + (6 − 2)²]
d = √[3² + 4²]
d = √[9 + 16]
d = √25 = 5
High-dimensional probabilities
t-SNE does not try to copy every raw distance into 2D. It converts high-dimensional affinities into probabilities: close neighbors get larger probability mass than distant points. Different samples can use different Gaussian bandwidths so that the neighborhood scale matches the chosen perplexity.
Student t-distribution and the crowding problem
In the low-dimensional map, t-SNE uses a Student t-distribution with heavy tails. The heavy tail gives moderately distant points more room in the map and reduces the tendency for many points to crowd into the center.
Simple interpretation
High-dimensional Gaussian affinities answer: who should be neighbors?
Low-dimensional t-distribution answers: how should those neighborhood relationships be represented on the map?
Step-by-Step Working of t-SNE
KL Divergence
t-SNE minimizes the mismatch between high-dimensional neighborhood probabilities P and low-dimensional neighborhood probabilities Q using Kullback-Leibler divergence:
Tiny KL contribution example
Suppose p = 0.20 and q = 0.10
p × ln(p/q) = 0.20 × ln(2)
≈ 0.20 × 0.693
≈ 0.139
The real t-SNE objective sums contributions across many pairs. This one pair is only for understanding the formula.
Gradient-based optimization repeatedly changes the low-dimensional coordinates to reduce this objective. Because the objective is non-convex, different initializations or random seeds can end at different local solutions.
Understanding perplexity
Perplexity is related to the effective neighborhood size t-SNE considers. It is not simply “the number of clusters” and it does not directly tell t-SNE how many groups to create.
Lower perplexity
Uses a smaller effective neighborhood and can emphasize very local relationships.
Middle value
Often a useful starting point, but still needs inspection rather than blind acceptance.
Higher perplexity
Uses a broader effective neighborhood and may smooth over smaller-scale patterns.
Do not memorize “5 = local” and “50 = global” as fixed rules
Different perplexity values can produce noticeably different shapes, sizes and spacing. In Scikit-learn, perplexity must also be smaller than the number of samples. It is sensible to inspect more than one reasonable value rather than declaring one plot to be the truth.
What must not be over-interpreted?
Cluster size
A larger island on the map does not necessarily mean a proportionally larger high-dimensional group.
Distance between islands
Far-apart islands are not guaranteed to be equally far apart in the original space.
Shape
The outline of a t-SNE island can change with perplexity, initialization and optimization.
Axes
t-SNE axis 1 and axis 2 do not have the direct feature meaning that original variables have.
Preprocessing Before t-SNE
Because neighborhood methods depend on distances, feature scale matters. If one meaningful numerical feature ranges from 0–1 and another from 0–1,000,000, the larger-scale feature can dominate the distance calculation unless that scale difference is intentional.
Scaling
Often useful when comparable numerical features use very different units. Do not standardize mechanically if the feature geometry has a domain-specific meaning.
PCA/SVD first
For very high-dimensional data, reducing to a moderate dimension first can speed up t-SNE and suppress some noise.
Python Implementation of t-SNE
Scikit-learn provides TSNE. The built-in handwritten-digits dataset used below has 64 input features per image, not 784. The target labels are used only to color the final plot; t-SNE itself does not train on those labels.
Python Code: t-SNE on handwritten digits
import matplotlib.pyplot as plt
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
from sklearn.preprocessing import StandardScaler
# 1. Load data
digits = load_digits()
X = digits.data # 1797 samples, 64 features
y = digits.target # used only for plot colors
# 2. Put numerical features on a comparable scale
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# 3. Optional pre-reduction before t-SNE
pca = PCA(n_components=40, random_state=42)
X_reduced = pca.fit_transform(X_scaled)
# 4. Build a 2D t-SNE embedding
tsne = TSNE(
n_components=2,
perplexity=30,
init="pca",
learning_rate="auto",
max_iter=1000,
random_state=42
)
X_tsne = tsne.fit_transform(X_reduced)
print("Original shape:", X.shape)
print("After PCA:", X_reduced.shape)
print("t-SNE shape:", X_tsne.shape)
print("Final KL divergence:", round(tsne.kl_divergence_, 3))
# 5. Visualize
plt.figure(figsize=(10, 8))
plt.scatter(
X_tsne[:, 0],
X_tsne[:, 1],
c=y,
cmap="tab10",
s=12
)
plt.title("t-SNE Visualization of Handwritten Digits")
plt.show()Expected deterministic console output
Original shape: (1797, 64) After PCA: (1797, 40) t-SNE shape: (1797, 2) Final KL divergence: 0.83
The exact last digits of the KL value can depend on library/platform details. The important output is the 2D embedding shape and the visualization.
t-SNE is not a normal train → transform-new-data pipeline in Scikit-learn
The Scikit-learn TSNE interface provides the fitted embedding for the samples used during fitting; it does not provide the same reusable transform() workflow as PCA. That is one reason t-SNE is best treated here as an exploratory visualization method rather than a production feature transformer for incoming samples.
Advantages, Limitations & Comparisons
Useful strengths
- Local visualization: Can make neighborhood structure easier to inspect.
- Non-linear embedding: Can reveal patterns not visible in a simple linear 2D projection.
- Representation inspection: Useful for exploring learned embeddings and feature spaces.
Important limitations
- Computational cost: Considerably more expensive than PCA on large datasets.
- Non-convex optimization: Different seeds or settings can produce different maps.
- Global geometry: Large-scale distances and cluster sizes can be misleading.
- No ordinary transform: Scikit-learn t-SNE is not a drop-in feature transformer for unseen samples.
t-SNE vs PCA
| Feature | t-SNE | PCA |
|---|---|---|
| Transformation | Non-linear embedding | Linear projection |
| Main teaching focus | Local neighborhoods | Feature variance directions |
| Reusable transform | Not in Scikit-learn TSNE | Yes |
| Typical use | Exploratory 2D/3D visualization | Visualization or dimensionality reduction |
What about UMAP?
UMAP is another popular non-linear embedding method. Its behavior, speed and global/local trade-offs depend on its own settings and implementation, so avoid memorizing a blanket rule such as “UMAP always preserves global structure better.” The safest comparison is to understand each method's objective and test sensible settings on the dataset at hand.
Common t-SNE Mistakes
- Treating every island as a confirmed cluster. A t-SNE map is evidence for exploration, not automatic semantic clustering.
- Reading between-cluster distance literally. Large gaps in 2D are not precise measurements of original-space separation.
- Using only one perplexity or seed. The map can change; inspect stability rather than trusting one attractive image.
- Ignoring feature scale. Distance-based neighborhoods can be dominated by large numerical units.
- Using t-SNE as a normal production feature transformer. Scikit-learn TSNE does not expose the same out-of-sample transform workflow as PCA.
Quick FAQ
Does t-SNE find clusters?
It creates an embedding that often makes local groups visually apparent, but it is not itself a semantic clustering algorithm.
Is perplexity the number of neighbors?
It is related to an effective neighborhood size through the entropy of the neighborhood probability distribution. Thinking “rough neighborhood scale” is useful; treating it as an exact K-nearest-neighbor count is too literal.
Should I run PCA before t-SNE?
For very high-dimensional data, pre-reducing to a moderate dimension with PCA for dense data or TruncatedSVD for sparse data can reduce noise and computation. It is not mandatory for every small dataset.
Final Summary
t-SNE is a non-linear method designed primarily for visualizing high-dimensional samples in two or three dimensions. It converts high-dimensional and low-dimensional affinities into probability distributions and optimizes the map by minimizing their KL-divergence mismatch.
Its greatest teaching value is local: nearby samples should remain useful neighbors. Its biggest interpretation warning is equally important: cluster size, shape, orientation and long-range distances in the 2D picture should not automatically be treated as faithful measurements of the original feature space.
Most Important Insight to Remember
Use t-SNE to explore local neighborhoods, then verify any apparent pattern with additional analysis instead of believing the picture alone.
Continue learning
Review PCA for linear dimensionality reduction, Feature Scaling for distance-sensitive preprocessing, or K-Means if your goal is explicit clustering rather than visualization.