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.
Dimensionality reduction (PCA, TruncatedSVD, t-SNE, UMAP) compresses hundreds or thousands of noisy features into a compact set of meaningful coordinates.
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.
Real ML datasets routinely have 1,000+ correlated columns or 1,536-D LLM embeddings — PCA & UMAP compress noise and make invisible spaces visible!
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.
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.
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?'
You run PCA on an unscaled dataset containing Annual_Income (200,000) and Credit_Utilization (0.0–1.0). What will Principal Component 1 (PC1) capture?
- 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
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
By the Pythagorean Theorem, for every centered point , . Since is constant, maximizing projected variance and minimizing reconstruction error are literally the exact same optimization! Rotate below to verify it live.
Computing PCA Safely via SVD
Instead of explicitly squaring the condition number in the covariance matrix , production libraries run SVD on the centered matrix . The columns of are the exact eigenvectors, and !
Rotating Axis θ = 0° — Watch Shadows Spread & Error Drops Shrink!
2. Choosing k Components (Scree Plot) & Sparse TruncatedSVD
How many components should you keep? Plot cumulative explained variance and pick the elbow (typically 90%–95%) — or pass PCA(n_components=0.95) directly in scikit-learn!
Critical Production Rules for PCA
- Zero Leakage: Fit
StandardScaler+PCAONLY onX_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 ! 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
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!
t-SNE vs. UMAP Rules of Thumb
- t-SNE: Matches high-D Gaussian similarities to low-D heavy-tailed Student- 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)!
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!
Choose Top-k Principal Components (Out of d = 10 Features)
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.
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_)
StandardScaler() before PCA..transform()) and distorts global geometry; use PCA or UMAP for pipelines and reserve t-SNE for 2D visualization!.transform() on new unseen points?