Machine Learning Slides 📂 Introduction · 20 of 25 40 min read

Principal Component Analysis (PCA): Reduce Dimensions, Keep the Signal

How do you squeeze 64 features into 30 — or 100 into 2 — and barely lose anything? PCA rotates your data onto new axes that point along its directions of greatest variance, ranks them by eigenvalue, and lets you drop the rest. This tutorial covers the four-step algorithm, the covariance/eigenvector maths, a worked Maths-vs-Physics example, the scree-plot elbow, standardization, sklearn pipelines and leakage, and when to use PCA vs t-SNE, UMAP, or LDA — with animated diagrams.

🔦

Principal Component Analysis

Rotate your data into a new set of axes that point along its directions of greatest variance — then drop the least useful axes and squeeze many features into a few, losing almost nothing.
Dimensionality Reduction Max Variance Scree Plot Visualization

Press Next → or use ← → arrow keys

Section 01

The Intuition — Find The Best Shadow

Shining a torch on a crumpled wire
Hold a bent piece of wire in the air and shine a torch at it — it casts a shadow on the wall. Rotate the torch and the shadow changes: some angles squash the wire into a meaningless blob, while one special angle shows its full shape, spread out as widely as possible.

PCA finds that best torch angle. It looks for the directions along which your data is most spread out, and projects the high-dimensional cloud down onto them — keeping the shape that matters and throwing away the flat, uninformative directions.
💡
One-Line Definition

PCA rotates your data into a new frame whose axes point along the directions of maximum variance, ordered largest-first — so you can drop the last few axes and lose almost no information.

Section 01 · Motivation

Why Reduce Dimensions At All?

🌌
Curse of Dimensionality
In high dimensions, points become sparse. A k-NN needing 10 neighbours in 2-D may need thousands in 100-D for the same density.
Compute Cost
Training often scales as O(d²)–O(d³). Cutting 1000 features to 50 can make training 20–400× faster.
👁️
Visualization
We can only see in 2-D/3-D. Projecting to 2–3 PCs lets you scatter-plot thousands of high-dimensional points.
🆕
PCA Makes New Columns, It Doesn't Pick Old Ones

Feature selection keeps a subset of your original columns. PCA is different: it builds brand-new columns — each a linear combination of all the originals — chosen to capture as much spread as possible in as few axes as possible.

Section 02 · Diagram

Projecting Onto The Principal Axes

feature 1 (e.g. Maths) feature 2 (e.g. Physics) PC1 PC2 points collapse onto PC1
📐
PC1 = Longest Spread · PC2 ⟂ PC1

PC1 points along the direction the cloud stretches most. PC2 is perpendicular to it and captures the next-most spread. Dropping to PC1 alone projects every point onto that line — reducing 2-D to 1-D while keeping the bulk of the variation.

Section 03 · Algorithm

PCA In Four Steps

🧮 From Raw Data To Reduced Data
1Standardize. Subtract the mean and divide by the std of each feature → zero mean, unit variance.
2Covariance matrix. Compute C = XᵀX / (n−1) — a d×d matrix of how features vary together.
3Eigen-decompose. Solve C·v = λ·v. Each eigenvector v is a principal direction; its eigenvalue λ is the variance along it. Sort by λ, largest first.
4Project. Stack the top-k eigenvectors into W (d×k) and compute Z = X·W → the reduced n×k data.
🔑
Eigenvectors Are Directions · Eigenvalues Are Amounts

The whole method reduces to one linear-algebra fact: the eigenvectors of the covariance matrix point along the axes of greatest spread, and their eigenvalues measure exactly how much variance each one captures. Sort, keep the top few, project.

Section 03 · Diagram

The PCA Pipeline, End To End

Raw Data n × d Standardize μ=0 · σ=1 Covariance C = XᵀX/(n−1) Eigen-decompose C·v = λ·v · sort by λ Select top k W = d × k Z = X·W n × k ✓ a d-dimensional dataset becomes a compact k-dimensional one — same rows, far fewer columns
🔗
Every Step Has A Job

Standardize so no feature dominates by scale, build the covariance to see how features move together, eigen-decompose to find the principal directions, keep the top k, and project. Out comes a dataset with the same rows but a handful of powerful new columns.

Section 04 · Maths

PCA In Four Formulas

Covariance matrix
C = XᵀX / (n − 1)
Symmetric d×d — diagonals are variances, off-diagonals are feature covariances.
Eigen equation
C · v = λ · v
v = principal direction (eigenvector), λ = variance captured along it (eigenvalue).
Explained variance ratio
EVRₖ = λₖ / Σ λᵢ
The fraction of total variance that component k accounts for.
Projection
Z = X · Wₖ
Wₖ holds the top-k eigenvectors; Z is the reduced n×k representation.
🧭
Orthogonal By Construction

Because C is symmetric, its eigenvectors are mutually perpendicular — so the new PC axes are uncorrelated. That's why PCA also wipes out multicollinearity: the components have, by design, zero correlation with each other.

Section 04 · Worked Example

Two Features → One "Ability" Axis

Five students, each with a Maths and a Physics score. The two are highly correlated — strong students tend to do well in both. What does PCA find?

Covariance matrix
[[148.5, 165.5], [165.5, 186.3]]
Large off-diagonals → Maths and Physics move together strongly.
Eigenvalues
λ₁ ≈ 332.8 · λ₂ ≈ 1.95
One direction holds almost all the spread; the other is nearly flat.
PC1 eigenvector
v₁ ≈ [0.664, 0.747]
Points diagonally — a blend of both subjects, i.e. "academic ability."
Variance explained by PC1
332.8 / (332.8 + 1.95) ≈ 99.4%
One component captures nearly everything — 2-D collapses cleanly to 1-D.
🎓
Two Correlated Scores, One Real Signal

Because Maths and Physics rise and fall together, their real information is essentially one-dimensional — an underlying "ability." PCA discovers that automatically: PC1 explains 99.4% of the variance, so keeping just PC1 loses almost nothing.

Section 05 · Diagram

Choosing k — The Scree Plot

principal component → explained variance 95% cumulative elbow → keep 3 PC1 PC2 PC3 PC4
⛰️
The Mountain-Ridge Rule

Rank the components by height like a mountain ridge: the first few are towering peaks, then there's a sharp drop to gentle foothills. The elbow — where the bars flatten and the cumulative line crosses ~95% — tells you how many components to keep.

Section 05 · Selecting k

Three Ways To Pick The Number Of Components

🎯
Variance Threshold
PCA(n_components=0.95)
Ask sklearn to keep exactly enough components for 95% cumulative variance. The most common, no-fuss choice.
🤖
MLE Auto-Select
n_components='mle'
Maximum-likelihood estimation picks k automatically from statistical principles — hands-off.
📈
Scree Elbow
visual inspection
Plot explained variance and keep components up to the elbow, where the curve visibly flattens.
🔍
Never Choose k Blindly

Always inspect the explained_variance_ratio_ before committing. Keeping too few components throws away signal; keeping too many defeats the purpose. Let the retained-variance number justify your choice of k.

Section 06 · Scaling

Standardization Is Non-Negotiable

⚠️
Big-Scale Features Hijack The Components

PCA chases variance — and variance is measured in the feature's own units. If salary ranges 0–100,000 and age ranges 0–100, salary's raw variance dwarfs age's, so PC1 would point almost entirely along salary regardless of which feature actually carries the signal. Standardizing to zero mean and unit variance puts every feature on equal footing first.

Always fit a StandardScaler before PCA
Subtract each feature's mean and divide by its standard deviation, so every column contributes variance on the same scale. Only then does PCA find directions that reflect the data's structure rather than an accident of measurement units. This single step is the most common PCA mistake to get wrong.
Section 07 · Code

PCA With scikit-learn

from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler

X_scaled = StandardScaler().fit_transform(X)   # step 1 — always scale first

pca = PCA(n_components=2)             # or 0.95 for a variance target
X_2d = pca.fit_transform(X_scaled)

print(pca.explained_variance_ratio_)      # variance per component
print(pca.components_)                    # eigenvectors = loadings
# Iris 4→2:  PC1 72.96%  ·  PC2 22.85%  →  95.81% retained
🌸
Reading The Loadings

components_ holds the loadings — how much each original feature contributes to each PC. On Iris, PC1 loads heavily on petal length (+0.58), petal width (+0.57) and sepal length (+0.52), so PC1 reads as an overall "flower size" axis. Loadings are how you interpret what a component means.

Section 07 · Pipelines

Put PCA Inside A Pipeline

from sklearn.pipeline import Pipeline
from sklearn.svm import SVC

pipe = Pipeline([
    ('scaler', StandardScaler()),
    ('pca',    PCA(n_components=0.95)),   # keep 95% variance
    ('svm',    SVC())
])
pipe.fit(X_train, y_train)   # scaler + PCA refit on each CV fold — no leakage
🚱
Data Leakage Is The Silent Killer

If you fit PCA on the whole dataset before splitting, information from the test fold leaks into training and your cross-validation scores become optimistic lies. Wrapping the scaler and PCA in a Pipeline means they're refit on the training portion of each fold only — leakage-free by construction. For huge data, swap in IncrementalPCA(batch_size=…) for constant memory.

Section 08 · Case Study

64 Pixels → 30 Components

The handwritten-digits dataset has 64 pixel features per image. Compress it to just 30 principal components and train a logistic-regression classifier:

64→30Features kept
93.35%Variance retained
95.28%Accuracy with PCA
96.11%Accuracy without PCA
🗜️
Halve The Features, Lose 0.8% Accuracy

Dropping from 64 to 30 features — under half the original — costs only about 0.8% accuracy while nearly halving the model's input size. That's the PCA bargain: big compression, tiny information loss, faster and simpler downstream models.

Section 09 · Fit

When PCA Helps — And When It Hurts

✅ Reach For PCA When…❌ Avoid PCA When…
You want to visualize high-D data in 2-D/3-DYou need interpretable, business-meaningful features
You need to denoise (reconstruct via Z·Wᵀ)The structure is non-linear / curved manifolds
You must remove multicollinearity (orthogonal PCs)n ≪ d — covariance is unreliable, noise gets amplified
You want faster training on many correlated featuresYou're using it to "fix" imbalance or missing values
🧩
Variance ≠ Importance

PCA keeps the directions of greatest spread — which aren't always the directions most useful for your label. For a supervised task where class separation matters more than raw variance, a supervised method like LDA may serve better. Always confirm the downstream metric actually improves.

Section 10 · Comparison

PCA vs Other Reduction Methods

MethodTypePreservesBest For
PCALinearGlobal variancePreprocessing · denoising · viz
Kernel PCANon-linearNon-linear varianceCurved manifolds (slow, O(n²))
t-SNENon-linearLocal neighbourhoodsCluster visualization only
UMAPNon-linearLocal + globalLarge data · topology
AutoencoderNon-linearLearned latentImages · audio · complex data
LDALinear (supervised)Class separationClassification preprocessing
🧭
The Rule Of Thumb

Start with PCA — it's fast, interpretable through its loadings, and drops cleanly into a leakage-free pipeline. If clusters still aren't visible after PCA, switch to UMAP (or t-SNE) for visualization, and reach for autoencoders when the data is genuinely non-linear.

Section 11 · Golden Rules

Seven Rules For Using PCA Well

🏅 PCA, Distilled
1Always standardize first. Otherwise large-scale features hijack the components.
2Always put PCA inside a Pipeline so it refits per fold — no test-set leakage.
3Inspect explained-variance ratios. Never pick k blindly — check the retained variance.
4Use PCA as preprocessing, not the goal. Verify the downstream metric actually improves.
5Don't use PCA to fix imbalance or missing values. Handle those before PCA.
6Use IncrementalPCA for big data — constant memory regardless of dataset size.
7Components aren't features. Treat loading interpretations as heuristics, not hard facts.
Wrap-Up

You Now Understand PCA End-To-End

C·v=λvEigen-decomposition
λVariance per PC
95%Common variance target
Orthogonal components
σ=1Standardize first
Z=XWProject & reduce
🎯
The Through-Line

PCA rotates data onto the axes of greatest variance, ranks them by eigenvalue, and lets you keep only the top few — compressing many features into a compact, uncorrelated handful. Standardize first, keep it in a pipeline, and check the variance you retain.

📚
Where To Go Next

Try PCA on the Iris and Digits datasets, read the loadings to interpret each component, then compare UMAP and t-SNE for visualization and LDA for supervised reduction. Explore Kernel PCA when your data curves.

🔦 End of tutorial · Press to review, or click Restart