Skip to content
E
Educatum

What is t-SNE (t-distributed Stochastic Neighbor Embedding)

Curated by Educatum AI teamLast updated:
Basic Concepts
Direct Answer

t-SNE (t-distributed Stochastic Neighbor Embedding) is a non-linear dimensionality reduction technique built primarily for visualizing high-dimensional datasets in 2D or 3D. It converts pairwise high-dimensional distances into Gaussian neighbor probabilities and matches them in low dimensions using a heavy-tailed Student-t distribution by minimizing KL divergence, preserving local neighborhoods while avoiding crowding. Because t-SNE optimizes a non-convex objective focused on local structure, cluster sizes and distances between distant clusters should not be interpreted literally.

Study Card: t-SNE (t-distributed Stochastic Neighbor Embedding)

Direct Answer

t-SNE (t-distributed Stochastic Neighbor Embedding) is a non-linear manifold visualization algorithm designed to embed high-dimensional points into 2D or 3D while preserving local neighborhood structure.

First, t-SNE converts Euclidean distances in high-dimensional space into conditional Gaussian probabilities calibrated per point via perplexity, then symmetrizes them:

pj∣i=exp⁡ ⁣(−∥xi−xj∥2/(2σi2))∑k≠iexp⁡ ⁣(−∥xi−xk∥2/(2σi2)),pij=pj∣i+pi∣j2Np_{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)}, \qquad p_{ij} = \frac{p_{j|i} + p_{i|j}}{2N}

Second, in the low-dimensional embedding yi\mathbf{y}_i, t-SNE models similarities using a heavy-tailed Student-t distribution with 1 degree of freedom (Cauchy kernel) so moderately distant neighbors can spread out without collapsing into the center (solving the crowding problem):

qij=(1+∥yi−yj∥2)−1∑k≠l(1+∥yk−yl∥2)−1q_{ij} = \frac{(1 + \|\mathbf{y}_i - \mathbf{y}_j\|^2)^{-1}}{\sum_{k \neq l}(1 + \|\mathbf{y}_k - \mathbf{y}_l\|^2)^{-1}}

Finally, it minimizes the KL divergence DKL(P∥Q)=∑i≠jpijlog⁡pijqijD_{\text{KL}}(P \parallel Q) = \sum_{i \neq j} p_{ij} \log \frac{p_{ij}}{q_{ij}} via gradient descent (O(N2)O(N^2) exact, or O(Nlog⁡N)O(N \log N) with Barnes–Hut approximation).

Key Terms

  • Local Structure Preservation: Prioritizes keeping nearby high-dimensional neighbors close together over preserving global pairwise distances.
  • Perplexity: Hyperparameter (typically 5–505\text{--}50) setting the effective number of local neighbors (2H(Pi)2^{H(P_i)}) via binary search over each point’s Gaussian bandwidth σi\sigma_i.
  • Crowding Problem: Because volume scales exponentially with dimension, a 2D map lacks room to accommodate all moderately distant points from high dimensions without heavy tails.
  • KL Divergence Asymmetry: Because pijlog⁡(pij/qij)p_{ij} \log(p_{ij}/q_{ij}) is large when pijp_{ij} is large and qijq_{ij} is small, t-SNE strongly penalizes tearing apart true neighbors, while tolerating placing distant points arbitrarily far apart.

Example

Consider embedding 64-dimensional handwritten digit images (8x8 pixel intensities) into 2D. Linear PCA projects along directions of maximum global variance, often overlapping several digit classes in the center. t-SNE adapts σi\sigma_i to local density and uses Student-t tails to separate digits 0 through 9 into clear, readable local islands in 2D—making it easy to inspect class separability and mislabeled outliers.

Code Implementation

import matplotlib.pyplot as plt
from sklearn.datasets import load_digits
from sklearn.manifold import TSNE

# Load 64-dimensional digits dataset
digits = load_digits()
X, y = digits.data, digits.target

# Apply t-SNE (modern sklearn uses `max_iter` instead of removed `n_iter`)
tsne = TSNE(
    n_components=2,
    perplexity=30.0,
    learning_rate="auto",
    init="pca",
    max_iter=1000,
    random_state=42,
)
X_embedded = tsne.fit_transform(X)
print(f"Embedded shape: {X_embedded.shape}, KL divergence: {tsne.kl_divergence_:.4f}")

# Plot 2D embedding
plt.figure(figsize=(9, 7))
scatter = plt.scatter(
    X_embedded[:, 0], X_embedded[:, 1], c=y, cmap="tab10", s=18, alpha=0.85
)
plt.colorbar(scatter, label="Digit Label")
plt.title("t-SNE Visualization of Handwritten Digits")
plt.xlabel("t-SNE Component 1")
plt.ylabel("t-SNE Component 2")
plt.grid(True, alpha=0.3)
plt.show()
  • PCA vs. t-SNE: PCA is a fast, linear, deterministic projection preserving global variance and supporting out-of-sample .transform(); t-SNE is non-linear, stochastic, non-parametric (cannot natively project unseen points without parametric extensions or refitting), and built strictly for visualization rather than downstream clustering.
  • UMAP: A faster manifold visualization method based on fuzzy simplicial sets that often preserves more global topology alongside local structure and supports .transform() on new points.
  • Interpretation Pitfalls: Apparent cluster diameters, densities, and distances between well-separated clusters depend heavily on perplexity and optimization hyperparameters and should not be treated as true geometric metrics (and t-SNE embeddings can even form apparent clusters from pure uniform noise at low perplexity).
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.