Chapter 35 of 42 · ~25 min read & lab+70 XP
Chapter 35 · Machine Learning

Unsupervised Learning II: Dimensionality Reduction (PCA, SVD, t-SNE & UMAP)

Maximum variance ⇔ minimum reconstruction error, computing PCA via SVD, Scree plots, TruncatedSVD for sparse matrices, and nonlinear t-SNE vs. UMAP manifolds.

What Is It?

Dimensionality reduction (PCA, TruncatedSVD, t-SNE, UMAP) compresses hundreds or thousands of noisy features into a compact set of meaningful coordinates.

Why Is It Required?

High-dimensional data is slow to train, impossible to visualize, and suffers from redundant noise—compression speeds up models and reveals hidden 2D/3D structure.

Everyday Analogy: Shining a flashlight on a 3D sculpture from the exact angle that casts the most informative 2D shadow on the wall.
Why ML Engineers & Data Scientists Actually Need This

Real ML datasets routinely have 1,000+ correlated columns or 1,536-D LLM embeddings — PCA & UMAP compress noise and make invisible spaces visible!

ML / AI Engineer

TruncatedSVD (LSA) compresses sparse TF-IDF matrices without densifying gigabytes of zeros, while UMAP + HDBSCAN is the standard pipeline for visualizing and clustering LLM embedding spaces.

Data Scientist

Knowing when PCA HURTS (e.g., when the direction of maximum feature variance is pure noise orthogonal to your target y!) prevents blind preprocessing mistakes.

Interview & Debug Edge

Classic ML interview question: 'Why MUST you center and scale features before PCA, how is PCA computed via SVD, and why shouldn't you run t-SNE as a preprocessing step for a production classifier?'

Step 0 · Test Your Gut Before Any Math!

You run PCA on an unscaled dataset containing Annual_Income (30,000–30,000–200,000) and Credit_Utilization (0.0–1.0). What will Principal Component 1 (PC1) capture?

What You Will Master in This Chapter
  • Prove why maximizing projected variance equals minimizing orthogonal squared reconstruction error
  • Compute PCA via SVD on standardized data — and fit strictly on X_train inside a Pipeline
  • Select k components using Scree Plots and cumulative explained variance (e.g., 95%)
  • Contrast linear PCA/TruncatedSVD with nonlinear t-SNE and UMAP for high-D embedding visualization
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 3
λᵢSay aloud:“i-th Eigenvalue”
Plain-English Meaning
Exact variance captured along Principal Component i
Everyday Example
Explained ratio = λᵢ / Σλ
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

Imagine photographing a 3D statue from the best possible angle so that its 2D shadow preserves the maximum detail. PCA automatically finds the orthogonal camera angles (PC1, PC2, ...) that preserve the widest spread of data — throwing away flat, redundant noise axes!

1. PCA Geometry: Max Variance ⇔ Min Reconstruction Error

Everyday Story First (Zero Math Yet!)

By the Pythagorean Theorem, for every centered point xi\mathbf{x}_i, ∥xi∥2=(shadow along u)2+(perpendicular error)2\|\mathbf{x}_i\|^2 = (\text{shadow along } u)^2 + (\text{perpendicular error})^2. Since ∥xi∥2\|\mathbf{x}_i\|^2 is constant, maximizing projected variance and minimizing reconstruction error are literally the exact same optimization! Rotate θ\theta below to verify it live.

PCA Geometry: Maximum Projected Variance ⇔ Minimum Orthogonal Reconstruction ErrorPC1 (Max Var λ₁)PC2 (⊥ PC1, λ₂)Step-by-Step PCA via SVD:1. Standardize X (mean 0, std 1)2. Compute SVD: X = U Σ Vᵀ3. Top-k rows of Vᵀ = PCs4. Fit ONLY on X_train!
PCA finds the orthogonal axis PC1 that simultaneously MAXIMIZES projected variance and MINIMIZES perpendicular squared reconstruction error.

Computing PCA Safely via SVD

Instead of explicitly squaring the condition number in the covariance matrix 1n−1X⊤X\frac{1}{n-1}X^\top X, production libraries run SVD on the centered matrix X=UΣV⊤X = U\Sigma V^\top. The columns of VV are the exact eigenvectors, and λi=σi2n−1\lambda_i = \frac{\sigma_i^2}{n-1}!

Animated Mini-Lab • Find Principal Component 1

Rotating Axis θ = 0° — Watch Shadows Spread & Error Drops Shrink!

Captured: 79.2%
Projected Var
2.098
Recon Error
0.550
Sum (Const!)
2.647
0%
θ = 0°

2. Choosing k Components (Scree Plot) & Sparse TruncatedSVD

Everyday Story First (Zero Math Yet!)

How many components kk should you keep? Plot cumulative explained variance ∑i=1kλi∑j=1dλj\frac{\sum_{i=1}^k \lambda_i}{\sum_{j=1}^d \lambda_j} and pick the elbow (typically 90%–95%) — or pass PCA(n_components=0.95) directly in scikit-learn!

Scree Plot: Picking k Components for 95% Cumulative Explained Variance95% TargetPC1PC2PC3PC4PC5Keep PC1–PC3 →95% variance, 40% smaller!
Scree Plot: plot cumulative explained variance Σλᵢ / Σλ to pick the fewest components k capturing 95% of signal while dropping noise.

Critical Production Rules for PCA

  • Zero Leakage: Fit StandardScaler + PCA ONLY on X_train, then call .transform(X_val).
  • Sparse Matrices: Standard PCA subtracts the mean, turning a 99%-zero TF-IDF matrix dense and blowing up RAM! Use TruncatedSVD (no mean-centering) for sparse text/click matrices.
  • Unsupervised Warning: PCA ignores the target yy! Sometimes a low-variance component holds the exact fraud signal — always check if PCA actually improves CV score.

3. Nonlinear Manifold Learning: t-SNE vs. UMAP

Everyday Story First (Zero Math Yet!)

If your data lies on a rolled-up 3D Swiss Roll or complex 1,536-D sentence embedding manifold, linear PCA crushes different clusters on top of each other. t-SNE and UMAP unfold nonlinear manifolds into crisp 2D/3D maps!

Linear Projection (PCA) vs. Nonlinear Manifold Learning (t-SNE & UMAP)PCA / SVD• Linear global projection• Has .transform() for new data• Fast & deterministic• Best for preprocessingt-SNE• Minimizes KL(P || Q)• Preserves local clusters• Slow O(N log N); no transform• Global distances meaningless!UMAP• Riemannian fuzzy graph• Faster than t-SNE on 1M pts• Preserves local + global• Supports .transform()!
PCA is linear and preserves global variance; t-SNE & UMAP unfold nonlinear manifolds for 2D visualization — UMAP is faster and preserves global layout better.

t-SNE vs. UMAP Rules of Thumb

  • t-SNE: Matches high-D Gaussian similarities to low-D heavy-tailed Student-tt similarities via KL divergence. Warning: cluster sizes and distances between far clusters in t-SNE are NOT meaningful, and t-SNE has no .transform() for new points!
  • UMAP: Grounded in topological fuzzy graphs — runs 10×–50× faster than t-SNE, preserves more global layout, and supports .transform(X_new)!
“Wait, I'm Confused...” · Teacher Office Hours Q&A

The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.

Each Principal Component is a linear combination of ALL original features (e.g., 0.42·Income − 0.31·Age + 0.55·Spend). If stakeholders need human-readable feature attributions, use Lasso (Ch 6) or tree + SHAP (Ch 19) instead of PCA!

Interactive Visual Lab
Lab Challenge: In the PCA Scree Lab below, slide k from 1 up to 10 until you cross 95% Cumulative Explained Variance — notice how few components you actually need!
Flagship Deep Lab • Scree Plot & Low-Rank Compression

Choose Top-k Principal Components (Out of d = 10 Features)

83.0% Variance Kept
P1
P2
P3
P4
P5
P6
P7
P8
P9
P10
Intuition Takeaway: PCA via SVD finds orthogonal max-variance axes (always standardize & fit on train only!), TruncatedSVD handles sparse matrices, and UMAP/t-SNE unfold nonlinear manifolds for visualization.
Where This Powers Real ML, Deep Learning & Generative AI

Denoising & Multicollinearity Removal

Decorrelating collinear sensor/financial signals before linear models or KNN.

LLM Embedding Visualization

UMAP projects 1,536-D OpenAI/Gemini embeddings into interactive 2D topic maps.

Production NumPy & PyTorch Code Patterns
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression

pca_pipe = Pipeline([
    ("scaler", StandardScaler()),
    ("pca", PCA(n_components=0.95, random_state=42)),  # auto-picks k for 95% variance!
    ("clf", LogisticRegression()),
])
pca_pipe.fit(X_train, y_train)
print("Components kept:", pca_pipe.named_steps["pca"].n_components_)
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Forgetting StandardScaler() before PCA.
Best Practice: High-magnitude features dominate raw variance and hijack PC1; always scale first.
Trap #2: Running t-SNE on train+test to feed into a production classifier.
Best Practice: t-SNE is transductive (no out-of-sample .transform()) and distorts global geometry; use PCA or UMAP for pipelines and reserve t-SNE for 2D visualization!
Trap #3: Assuming PCA always improves supervised accuracy.
Best Practice: PCA is unsupervised — if the target correlates with a small-variance direction, dropping tail PCs hurts accuracy!
Chapter Mastery Check (+70 XP)
Score: 0 / 5
1What two objectives are mathematically equivalent in Principal Component Analysis?
2Why is fitting PCA on the entire dataset BEFORE splitting into train and test a mistake?
3Which caveat applies when reading a 2D t-SNE scatter plot?
4How are PCA eigenvalues λᵢ related to the singular values σᵢ of the centered matrix X?
5Which nonlinear manifold method is faster on large datasets and supports .transform() on new unseen points?

Apply What You Learned — Solve Matching Coding Problems