Machine Learning Slides 📂 Introduction · 21 of 25 37 min read

PCA for Dimensional Reduction: The Maths, Worked by Hand

See exactly how PCA shrinks many features into a few — not just the theory, but the arithmetic. This tutorial walks the seven-step recipe (mean-centre, covariance, det(C−λI)=0, eigenvectors, explained variance, projection) through a complete four-point example you can check on paper, then shows the conservation law that governs it all: Trace(C) = Σλ = total variance. Includes the scree-plot elbow, an eigenvalue interpretation guide, applications, and seven golden rules — with animated diagrams.

🗜️

PCA for Dimensional Reduction

The linear-algebra machine that shrinks many features into a few — worked out by hand, step by step: mean-centre, covariance, eigenvalues, projection. See exactly where the variance goes.
Hand-Worked Maths Eigenvalues Variance = Info Scree Plot

Press Next → or use ← → arrow keys

Section 01

The Best Angle To Cast A Shadow

A 3-D sculpture under torchlight
Hold a sculpture under a torch and it casts a flat 2-D shadow on the wall. Turn the torch and the shadow changes — some angles flatten the sculpture into a meaningless blob, while one angle reveals its true outline, spread out as fully as possible.

PCA finds that angle. It rotates your coordinate system so the first new axis — the first principal component — points along the direction of maximum variance, the projection that keeps the most information when you flatten high dimensions down to a few.
💡
Dimensional Reduction In One Line

PCA replaces your original axes with new ones ranked by how much the data spreads along them — so you can keep the top few and drop the rest, compressing the data while preserving nearly all of its structure.

Section 01 · Principles

Three Ideas That Make PCA Work

📊
Variance = Information
A feature that never varies tells you nothing. PCA prioritizes the axes with the most spread, because that's where the discriminating signal lives.
📐
Orthogonality
Every principal component is perpendicular to all the others, so the new features are uncorrelated — zero redundancy between them.
⛰️
The Scree Plot
Rank the eigenvalues largest-first and the "elbow" shows where signal components end and noise components begin — your cut-off for k.
🧭
Keep The Spread, Drop The Flatness

The high-variance directions are stable, reproducible structure; the near-flat directions are mostly measurement noise. Dimensional reduction is simply choosing to keep the former and discard the latter.

Section 02 · Process

The Seven-Step PCA Recipe

🧮 From Raw Matrix To Reduced Data
1Compute the feature means μ for every column.
2Mean-centre the data: B = X − μ, shifting the cloud's centre to the origin.
3Build the covariance matrix C = BᵀB / (n−1).
4Solve for eigenvalues from det(C − λI) = 0 — the variance of each PC.
5Find the eigenvectors — the normalized principal directions.
6Compute explained-variance % and choose how many components to keep.
7Project the data onto the chosen components: Z = B · W.
🔑
The Heart Of It Is One Eigen-Problem

Steps 4 and 5 are the whole story: the eigenvectors of the covariance matrix are the principal directions, and their eigenvalues are the variance along each. Everything else is setup and projection.

Section 02 · Formulas

The Five Formulas

Mean centering
B = X − μ
Move the data's centroid to the origin so variance is measured from the centre.
Covariance matrix
C = BᵀB / (n − 1)
Captures how every pair of features varies together.
Eigenvalue equation
det(C − λI) = 0
Its roots λ are the variances carried by each principal component.
Explained variance
EVₖ = λₖ / Σ λᵢ
The share of total variance that component k accounts for.
➡️
Then Project: Z = B · W

Stack the top-k eigenvectors into the weight matrix W and multiply the centred data by it. The result Z is your dataset re-expressed in the new, reduced coordinate system — same rows, fewer columns.

Section 03 · Worked Example

Four Points, By Hand — Setup

Take four samples with two features each and run the recipe end to end. First, centre the data on its mean.

The four samples
(1,2) · (3,4) · (5,4) · (3,6)
Two features, four rows — small enough to solve on paper.
Feature means
x̄₁ = 3 · x̄₂ = 4
Average of each column — the centroid of the cloud.
Centred matrix B = X − μ
[−2,−2] · [0,0] · [2,0] · [0,2]
Every point shifted so the centre sits at the origin.
Covariance matrix C
[[8/3, 4/3], [4/3, 8/3]]
Equal diagonals, positive off-diagonal — the features move together.
✏️
Now Solve The Eigen-Problem

With C in hand, the next step is det(C − λI) = 0 — two eigenvalues, two eigenvectors. The diagram on the next slide shows exactly what those directions look like.

Section 03 · Diagram

The Geometry — And The 1-D Projection

feature 1 feature 2 PC1 · 75% PC2 · 25% S1(1,2) S2(3,4) S3(5,4) S4(3,6) μ(3,4) −2.83 0 +1.41 ×2
📉
2-D → 1-D: Z = [−2.83, 0, +1.41, +1.41]

PC1 runs along the 45° diagonal (eigenvector [0.707, 0.707]). Projecting the four centred points onto it gives a single coordinate each — the whole dataset compressed to one number per sample, keeping 75% of the variance.

Section 03 · Results

The Numbers That Fall Out

Eigenvalues
λ₁ = 4.0 · λ₂ = 4/3 ≈ 1.33
PC1 carries 4.0, PC2 carries 1.33 — one direction dominates.
Explained variance
75% · 25%
4.0 / (4.0 + 1.33) = 75% for PC1; the rest for PC2.
Eigenvectors (normalized)
e₁ = [0.707, 0.707]
e₂ = [0.707, −0.707]
PC1 at 45°, PC2 exactly perpendicular to it.
Projection onto PC1
Z = [−2.83, 0, +1.41, +1.41]
One coordinate per sample — the reduced 1-D dataset.
Hand-Maths Matches scikit-learn Exactly

Run the same four points through PCA(n_components=1) and you get the identical projection to machine precision. Working it by hand once removes all the mystery — sklearn is just doing this eigen-decomposition for you, fast.

Section 04 · Meaning

Eigenvectors Ask "Where?" · Eigenvalues Ask "How Much?"

🧭
Eigenvector → WHERE
A direction in feature space. Its entries are the loadings — the recipe of original features that make up the component, showing which ones dominate.
📏
Eigenvalue → HOW MUCH
The variance of the data once projected onto that eigenvector. It ranks components and tells you how many to keep.
🔗
Together
Each (direction, amount) pair is one principal component. Sort by eigenvalue, keep the biggest, and you've reduced dimensions with proof of what you kept.
🧮
λ Is Variance — Provably, Not By Definition

That an eigenvalue equals the variance of the data projected onto its eigenvector isn't an arbitrary label — it falls straight out of the eigenvector equation C·e = λ·e. The maths guarantees the ranking is meaningful.

Section 04 · Conservation

Variance Is Redistributed, Never Created

Total variance = Trace(C) = 16/3 Σ eigenvalues = total variance (conserved) splits exactly into the two components ↓ PC1 · λ₁ = 4.0 75% kept 25% lost PC2 · λ₂ = 1.33 → discarded
⚖️
Trace(C) = Σλ = Total Variance

The eigenvalues always sum to the trace of the covariance matrix — the total variance of the original features. PCA doesn't add or destroy information, it redistributes it onto the new axes. Whatever variance a discarded component held is exactly the information you lose.

Section 05 · Choosing k

The Scree Plot & The Elbow

principal component → eigenvalue λ 95% cumulative elbow → keep 3 PC1 PC2 PC3 PC4
📈
Where Signal Ends And Noise Begins

Plot the eigenvalues in descending order. The tall bars before the elbow are stable, reproducible signal; the flat tail is noise. Cut at the elbow — or wherever the cumulative curve crosses your variance target (commonly 95%).

Section 05 · Reading Results

What The Eigenvalues Are Telling You

What You SeeWhat It Means
First eigenvalue ≫ others (10×)Data is effectively 1-D — check for a confounding variable
Eigenvalues nearly equalDirections are numerically unstable & unreliable
High loadings on just 2 featuresThose features explain most spread — a simpler model may match
Last few eigenvalues ≈ 0Safe to discard — unless hunting outliers/anomalies
🛡️
Big-λ Directions Are Stable — Small-λ Ones Aren't

The eigenvectors of large eigenvalues barely move when new data arrives — they encode real, reproducible structure. Small-eigenvalue directions swing wildly with tiny perturbations. That's a second reason, beyond compression, to keep only the high-variance components: robustness.

Section 06 · Applications

What Dimensional Reduction Buys You

ApplicationWhy PCA HelpsWhen To Use
VisualizationCollapse to 2-D/3-D for scatter plotsAlways 2–3 PCs for plotting
Noise filteringDrop low-eigenvalue componentsStrip measurement noise
Multicollinearity fixBuild uncorrelated featuresBefore OLS / regression (PCR)
Training speed-up500 features → 50 PCsAccelerate SVM / kNN
Feature extractionSurface latent patternsDiscover hidden structure
🚫
When To Skip PCA

Tree models (Random Forest, XGBoost) already handle high dimensions natively — PCA rarely helps them. Skip it too when the structure is non-linear (reach for kernel PCA, t-SNE or UMAP) or when you need interpretable features (use feature selection instead).

Section 07 · Code

By Hand, Then Verified With sklearn

import numpy as np
from sklearn.decomposition import PCA

X = np.array([[1,2], [3,4], [5,4], [3,6]], dtype=float)

# ── manual steps ──
mu = X.mean(axis=0)              # [3. 4.]
B  = X - mu                       # mean-centre
C  = np.cov(B, rowvar=False)      # covariance matrix
vals, vecs = np.linalg.eigh(C)    # eigenvalues + eigenvectors

# ── sklearn verification ──
Z = PCA(n_components=1).fit_transform(X)
print(Z.ravel())   # ≈ [-2.83, 0, 1.41, 1.41] — matches the hand maths
🔎
A Sanity Check You Can Always Run

Confirm sum(eigenvalues) == trace(C) — total variance is conserved. If it doesn't hold, you've made an arithmetic slip somewhere. It's the fastest way to catch a broken PCA by hand.

Section 08 · Comparison

PCA vs Other Reduction Methods

PropertyPCAt-SNEUMAPLDA
LinearityLinearNon-linearNon-linearLinear
SupervisionUnsupervisedUnsupervisedUnsupervisedSupervised
PreservesGlobal varianceLocal clustersLocal + globalClass separability
ML-pipeline safe?YesNo (stochastic)SometimesYes
Best forPreprocessing2-D/3-D vizExplorationClassification prep
🧭
Pick By The Job

Use PCA as your default preprocessing and denoising step — it's linear, fast, and pipeline-safe. Switch to t-SNE / UMAP purely for visual cluster exploration, and to LDA when the goal is maximizing class separation before a classifier.

Section 09 · Golden Rules

Seven Non-Negotiables

🏅 PCA Dimensional Reduction, Distilled
1Always standardize when feature scales differ — use StandardScaler first.
2Fit PCA on training data only — never let the test set leak in.
3Verify Σλ = Trace(C). Total variance must be conserved.
4Choose k with a scree plot or cumulative-variance curve — not an arbitrary number.
5Accept that PCA breaks interpretability — each PC blends all original features.
6Remember PCA is linear-only — curved manifolds need kernel PCA or UMAP.
7Use TruncatedSVD for millions of rows — it's far more efficient at scale.
Wrap-Up

You've Seen PCA All The Way Down

B=X−μMean-centre
det=0Solve eigenvalues
75/25Variance split
Σλ=TrConservation law
Z=BWProject & reduce
elbowChoose k
🎯
The Through-Line

Dimensional reduction with PCA is one clean idea: mean-centre, find the covariance's eigenvectors, keep the directions of greatest variance, and project. The eigenvalues tell you exactly how much you keep and how much you lose — total variance is conserved, never conjured.

📚
Where To Go Next

Re-run the four-point example yourself, then scale up to Iris and the digits dataset. Compare TruncatedSVD on large sparse data, and explore kernel PCA and UMAP when your data refuses to be linear.

🗜️ End of tutorial · Press to review, or click Restart