Chapter 34 of 42 · ~16 min read & lab+60 XP
Chapter 34 · Machine Learning

PCA (Principal Component Analysis) Explained: Variance, Eigenvectors & Scree Plots

The intuitive beginner's guide to PCA — rotating data onto maximum-variance axes, reading Explained Variance Ratio (Scree plots), and avoiding PCA pitfalls

What Is It?

Principal Component Analysis (PCA) is an unsupervised linear technique that rotates a high-dimensional dataset onto new orthogonal axes (Principal Components) ordered from highest variance to lowest, letting you keep the top K axes and drop noisy dimensions.

Why Is It Required?

Datasets with 100+ correlated columns are slow to train, suffer from multicollinearity, and are impossible to plot — PCA compresses 95% of the information into a fraction of the dimensions.

Everyday Analogy: Photographing a long surfboard from the side (capturing its full length and shape in 1 axis) rather than head-on (where it looks like a tiny dot).
Why ML Engineers & Data Scientists Actually Need This

PCA is the cornerstone of linear dimensionality reduction, noise filtering, multicollinearity removal, and high-dimensional visualization.

ML / AI Engineer

Compressing 1,536-dim embeddings down to 256 dims with PCA cuts vector database RAM and latency by 6× with minimal recall loss.

Data Scientist

PCA eliminates multicollinearity completely (every Principal Component has VIF = 1!) and lets you visualize 50-feature customer tables in 2D.

Interview & Debug Edge

Favorite question: 'Does PCA use target labels y? Can discarding the lowest-variance principal component EVER hurt a supervised classifier?'

Step 0 · Test Your Gut Before Any Math!

Does PCA ever look at the target label y when choosing which directions to keep?

What You Will Master in This Chapter
  • Trace the exact 4-step PCA recipe: Standardize → Covariance/SVD → Top-K Eigenvectors → Project.
  • Read a Scree Plot and Cumulative Explained Variance curve to choose K (e.g., keeping 95% variance).
  • Explain why Standardizing BEFORE PCA is mandatory whenever features have different units.
  • Know when NOT to use PCA (when you need direct column-name interpretability, or when low-variance directions actually separate the target y!).
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 2
EVRk=λk∑j=1Dλj\text{EVR}_k = \frac{\lambda_k}{\sum_{j=1}^D \lambda_j}Say aloud:“Explained Variance Ratio of component k”
Plain-English Meaning
Fraction of total dataset spread captured by Principal Component k.
Everyday Example
PC1=0.65, PC2=0.25 → first 2 axes retain 90% of total variance!
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

Imagine a slanted cigar-shaped cloud of dots in 3D. Almost all the information lies along the cigar's length (PC1) and width (PC2); the tiny thickness (PC3) is mostly noise. PCA rotates your coordinate system to align with the cigar so you can safely drop PC3!

1. The 4-Step PCA Recipe

  1. Standardize every feature (μ=0,σ=1\mu=0, \sigma=1) strictly on X_train so large-unit columns don't hijack PC1.
  2. Compute SVD (X=UΣV⊤X = U \Sigma V^\top) — numerically faster and more accurate than forming X⊤XX^\top X.
  3. Pick KK using the Cumulative Explained Variance curve (commonly 90%–95%, or K=2K=2 for 2D plots).
  4. Project Z_train = X_train @ V_K and Z_test = X_test @ V_K.
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°
“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.

Loss of interpretability: Each component is a linear blend of ALL original features (PC1 = 0.31·age − 0.52·income + ...), so you can no longer say 'age drove this prediction' directly.

Interactive Visual Lab
Lab Challenge: Drag the number of principal components K to watch reconstruction error drop as variance is recovered.
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: Standardize first, compute PCA via SVD, choose K from the cumulative explained variance curve, and remember PCA is unsupervised (maximizes X variance, not y accuracy).
Production NumPy & PyTorch Code Patterns
import numpy as np

# Exact PCA via SVD From Scratch + Explained Variance Ratio
rng = np.random.default_rng(0)
t = rng.normal(size=100)
X = np.column_stack([2.0 * t + rng.normal(0, 0.2, 100), 1.0 * t + rng.normal(0, 0.2, 100), rng.normal(0, 0.1, 100)])

# 1. Standardize
X_std = (X - X.mean(axis=0)) / X.std(axis=0)
# 2. SVD -> singular values S give eigenvalues S^2 / (N - 1)
U, S, Vt = np.linalg.svd(X_std, full_matrices=False)
evr = (S ** 2) / np.sum(S ** 2)
# 3. Project onto top K=2 principal components
Z = X_std @ Vt[:2].T

print("Explained Variance Ratios:", np.round(evr, 3).tolist())
print(f"Top-2 cumulative variance: {evr[:2].sum():.1%} | Projected shape: {Z.shape}")
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Fitting PCA on the combined train + test set before splitting.
Best Practice: Always fit StandardScaler + PCA inside a Pipeline strictly on X_train!
Chapter Mastery Check (+60 XP)
Score: 0 / 1
1Why MUST you standardize features before running PCA on a table containing age (20–70) and salary (30k–30k–200k)?

Apply What You Learned — Solve Matching Coding Problems