Skip to content
E
Educatum

t-SNE VS PCA

Curated by Educatum AI teamLast updated:
Basic Concepts
Direct Answer

PCA is a deterministic linear dimensionality reduction method that preserves global variance and learns an explicit projection matrix for transforming unseen test data in ML pipelines. t-SNE is a stochastic, non-linear visualization technique that preserves local neighborhood similarities in 2D or 3D, but it is non-parametric (cannot directly transform new points) and does not reliably preserve global cluster distances or sizes.

Study Card: t-SNE vs. PCA

Direct Answer

PCA and t-SNE serve fundamentally different goals in dimensionality reduction:

  • PCA (Principal Component Analysis) is a deterministic, linear, parametric projection maximizing global variance along orthogonal principal components (Z=XcWkZ = X_c W_k). It preserves large-scale global structure, supports fast out-of-sample .transform() on test sets, and is widely used for feature compression, denoising, and preprocessing before downstream ML models.
  • t-SNE (t-Distributed Stochastic Neighbor Embedding) is a stochastic, non-linear, non-parametric manifold embedding designed specifically for 2D/3D visualization. It converts pairwise distances into neighborhood probabilities (Gaussian in high-D, heavy-tailed Student-tt in low-D to avoid the crowding problem) and minimizes asymmetric KL divergence KL(P∥Q)\text{KL}(P \| Q), strongly preserving local neighborhoods.

Key interview caveats for t-SNE:

  1. No out-of-sample projection: Standard t-SNE optimizes embedding coordinates directly for the given dataset and cannot call .transform() on new test points.
  2. Inter-cluster distances & cluster sizes are unreliable: Because perplexity adapts local bandwidths per point and KL penalizes breaking close neighbors far more than separating distant ones, relative gaps between clusters and cluster areas in a t-SNE plot should not be over-interpreted.
  3. Scaling: Naive t-SNE scales O(n2)O(n^2) (Barnes-Hut approximation scales O(nlog⁡n)O(n \log n) in 2D/3D), so practitioners frequently run PCA first (e.g., reducing thousands of dimensions down to ~50) before applying t-SNE.

Key Terms

  • t-SNE: Non-linear neighborhood-preserving embedding minimizing KL(P∥Q)\text{KL}(P \| Q) between high-dimensional Gaussian similarities and low-dimensional Student-tt similarities.
  • PCA: Linear orthogonal projection preserving maximal global variance.
  • Local Structure: Pairwise proximity relationships among immediate neighbors on a curved manifold.
  • Global Structure: Macroscopic geometry, total variance, and relative separation between distant groups.
  • Perplexity: t-SNE hyperparameter controlling the effective number of local neighbors around each point (typically 5–50).

Example

On the 64-dimensional handwritten digits dataset (0–9), a 2D PCA plot captures global variance directions but overlaps several digit classes in the middle because digits occupy curved non-linear manifolds. Running t-SNE preserves local stroke similarities and cleanly separates the 10 digit clusters in 2D for visual exploration—whereas PCA remains the right choice when feeding compressed features (say, 30 components explaining 95% variance) into a downstream classifier with a train/test split.

Code Implementation

import matplotlib.pyplot as plt
import numpy as np
from sklearn.manifold import TSNE
from sklearn.decomposition import PCA
from sklearn.datasets import load_digits

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

# Apply t-SNE (non-linear 2D visualization; use max_iter in scikit-learn >= 1.5)
tsne = TSNE(n_components=2, perplexity=30, random_state=0, max_iter=1000, n_jobs=-1)
X_tsne = tsne.fit_transform(X)

# Apply PCA (linear projection)
pca = PCA(n_components=2)
X_pca = pca.fit_transform(X)

# Plot t-SNE vs. PCA side-by-side
cmap = plt.get_cmap('tab10', 10)
plt.figure(figsize=(12, 6))

plt.subplot(1, 2, 1)
plt.scatter(X_tsne[:, 0], X_tsne[:, 1], c=y, cmap=cmap)
plt.colorbar(ticks=range(10))
plt.clim(-0.5, 9.5)
plt.title("t-SNE (Local Structure)")

plt.subplot(1, 2, 2)
plt.scatter(X_pca[:, 0], X_pca[:, 1], c=y, cmap=cmap)
plt.colorbar(ticks=range(10))
plt.clim(-0.5, 9.5)
plt.title("PCA (Global Variance)")

plt.tight_layout()
plt.show()

# Visualize cumulative explained variance for PCA across more components
pca_full = PCA(n_components=20).fit(X)
cumulative_var_ratio = np.cumsum(pca_full.explained_variance_ratio_)

plt.figure(figsize=(8, 5))
plt.plot(range(1, len(cumulative_var_ratio) + 1), cumulative_var_ratio, marker='o', linestyle='--')
plt.title("Cumulative Explained Variance Ratio by Principal Components")
plt.xlabel("Number of Principal Components")
plt.ylabel("Cumulative Explained Variance Ratio")
plt.grid(True)
plt.show()
  • Manifold Learning & UMAP: UMAP offers another non-linear visualization method that generally scales faster than t-SNE, preserves somewhat more global structure, and supports transforming out-of-sample points.
  • MDS (Multidimensional Scaling): Focuses on preserving pairwise global distances directly rather than local neighborhood probabilities.
  • PCA Preprocessing Before t-SNE: Reducing ultra-high-dimensional data (e.g., gene expression or text embeddings) to ~50 PCs first suppresses noise and accelerates pairwise distance computation in t-SNE.
  • Crowding Problem: Explains why t-SNE uses a heavy-tailed Student-tt kernel with 1 degree of freedom in 2D/3D instead of a Gaussian, leaving enough room for moderately distant points without collapsing clusters together.
  • Hyperparameter Sensitivity: Different perplexity values and random seeds change t-SNE layouts dramatically; avoid drawing quantitative conclusions about cluster density or inter-cluster spacing from t-SNE plots alone.
View all →

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