Machine Learning Slides 📂 Introduction · 22 of 25 43 min read

Linear Discriminant Analysis (LDA): Projecting for Maximum Class Separation

Where PCA chases variance, LDA chases separation. This supervised method finds the projection that pushes classes farthest apart while keeping each tightly packed — the Fisher criterion, maximizing between-class over within-class scatter. This tutorial covers the Sw/Sb maths, the C−1 component ceiling, a worked wine example, PCA vs LDA, the assumptions (and QDA when they fail), shrinkage and solvers, and the PCA→LDA Fisherfaces pipeline — all with animated diagrams.

🎯

Linear Discriminant Analysis

The supervised cousin of PCA — instead of chasing raw variance, it finds the projection that pushes the classes farthest apart while keeping each class tightly packed. Reducer and classifier in one.
Class Separation Supervised Fisher Criterion Fisherfaces

Press Next → or use ← → arrow keys

Section 01

The Intuition — The Museum Guard

Separating visitors from thieves
A museum guard wants to tell honest visitors from thieves using two clues: bag weight and number of items. Rather than staring at each number alone, a clever guard asks a sharper question: "Along which single direction, if I lined everyone up on it, would the two groups sit farthest apart — while each group stays tightly bunched?"

That question is LDA. It searches for the projection that maximizes the gap between classes while minimizing the spread within each class — turning a messy multi-feature problem into one clean, separating axis.
💡
PCA's Supervised Cousin

Invented by Ronald Fisher in 1936, LDA uses the class labels PCA ignores. Where PCA keeps the directions of greatest total variance, LDA keeps the directions of greatest class separability — a crucial difference when your end goal is classification.

Section 01 · Two Roles

LDA Wears Two Hats

🗜️
Dimensionality Reducer
Projects high-dimensional data down to at most C−1 axes (C = number of classes) — the directions that best separate the classes.
🏷️
Classifier
Assigns a new point to the nearest class centroid in the projected space, assuming each class is Gaussian with shared covariance.
Fast & Interpretable
Just a matrix multiply plus a nearest-centroid check — a strong, transparent baseline you should always try first.
🎓
Same Maths, Two Uses

Whether you want a compact 2-D view of a 100-feature dataset or a quick, accurate classifier, LDA solves the same optimization — it just either hands you the projected coordinates or the predicted labels.

Section 02 · The Goal

Maximize Between · Minimize Within

μ₁ μ₂ Sᵦ · between-class (maximize) Sᵥᵥ · within-class (minimize) Sᵥᵥ · within-class (minimize)
⚖️
Two Forces, One Ratio

Between-class scatter (Sᵦ) measures how far the class centroids sit from each other — push it up. Within-class scatter (Sᵥᵥ) measures how spread out each class is — push it down. LDA finds the direction that maximizes their ratio.

Section 02 · Diagram

The Right Axis Untangles The Classes

Bad axis → classes overlap LDA axis → clean split
🔀
Same Points, Different Projection

Project the two classes onto the wrong axis and they smear together — no threshold can split them. Project onto the LDA axis and the blues land on one side, the ambers on the other. Finding that axis is the entire job of LDA.

Section 03 · Maths

The Fisher Criterion

The objective (Fisher criterion)
J(w) = wᵀSᵦw / wᵀSᵥᵥw
Find the direction w that maximizes between-class over within-class scatter.
Between-class scatter
Sᵦ = Σ nᵢ (μᵢ − μ)(μᵢ − μ)ᵀ
How far each class mean μᵢ sits from the overall mean μ — bigger is better.
Within-class scatter
Sᵥᵥ = Σ Σ (x − μᵢ)(x − μᵢ)ᵀ
How spread out each class is around its own mean — smaller is better.
Solution: generalized eigen-problem
Sᵥᵥ⁻¹ Sᵦ w = λ w
The top eigenvectors of Sᵥᵥ⁻¹Sᵦ are the optimal discriminant directions.
🧮
Maximizing A Ratio → An Eigen-Problem

Maximizing the Fisher ratio turns, through calculus, into the generalized eigenvalue problem Sᵥᵥ⁻¹Sᵦ w = λw. Each eigenvalue tells you how much class separation its direction captures — exactly analogous to PCA's eigenvalues measuring variance.

Section 03 · Algorithm

LDA In Six Steps

🧭 From Labelled Data To Discriminant Axes
1Compute the class means μ₁…μ_C and the overall mean μ.
2Build the within-class scatter Sᵥᵥ — the pooled spread inside each class.
3Build the between-class scatter Sᵦ — how far the class means are from μ.
4Solve Sᵥᵥ⁻¹Sᵦ w = λw for eigenvalues and eigenvectors.
5Sort by eigenvalue and keep the top k = min(C−1, d) discriminant directions.
6Project the data: Z = X · W.
🔒
The Hard Ceiling: C − 1 Components

Because Sᵦ is built from only C class means, it has rank at most C−1 — so LDA can produce at most C−1 discriminant axes, no matter how many input features you have. A 3-class problem yields at most 2; a 2-class problem, just 1.

Section 04 · Worked Example

Two Wines, By Hand

Four wine samples, two features (Alcohol %, Malic Acid), two classes — Barolo vs Barbera. What single direction best tells them apart?

Class means
μ₁ = [14.0, 1.8]
μ₂ = [12.15, 3.3]
Barolo is higher alcohol / lower acid; Barbera the reverse.
Within-class scatter
Sᵥᵥ = [[0.205, −0.14],
[−0.14, 0.1]]
Small — each wine's samples cluster tightly.
Between-class scatter
Sᵦ ≈ [[3.42, −2.77],
[−2.77, 2.25]]
Large — the two class means are far apart.
Optimal direction
w ∝ [−0.61, −0.79]
The normalized discriminant axis that best splits the two wines.
🍷
One Axis Separates Them Cleanly

With a large Sᵦ and a small Sᵥᵥ, the Fisher ratio is high along w. Projecting all four samples onto that single direction lines the Barolos up on one side and the Barberas on the other — two features reduced to one perfectly separating score.

Section 05 · Diagram

PCA Chases Variance · LDA Chases Separation

PC1 (max variance) classes stay mixed LD1 (max separation) splits blue vs amber ✓
⚠️
The Biggest-Variance Direction Can Ignore The Labels

Here the greatest spread runs along the diagonal both classes share — so PCA's top axis barely separates them. LDA instead looks across the classes and finds the direction that pulls blue and amber apart. When your goal is classification, variance is the wrong compass.

Section 05 · Comparison

PCA vs LDA — Side By Side

PropertyPCALDA
TypeUnsupervisedSupervised
ObjectiveMaximize total varianceMaximize class separability
Uses labels?NoYes
Max componentsmin(n−1, d)C − 1
Gaussian assumptionNoYes (per class)
Best forViz · noise removal · unlabeledClassification preprocessing
🤝
Complementary, Not Competing

The pros use both: run PCA first to strip noise and fix singularity when features outnumber samples, then run LDA on the cleaned-up data to extract the discriminant axes. That two-stage pipeline is exactly what powers Fisherfaces.

Section 06 · Assumptions

The Fine Print — Four Assumptions

AssumptionWhat It MeansIf Violated
Gaussian classesEach class is multivariate normalTransform features (log, Box-Cox)
Equal covarianceClasses share one covariance shapeSwitch to QDA
Independent samplesNo time-series / repeated measuresUse mixed / multilevel models
Non-singular SᵥᵥNeeds n > d to invert SᵥᵥPCA first, or shrinkage
🩹
Robust To Mild Violations

LDA tolerates gentle departures from normality, so don't panic over slightly skewed features. The two that really bite are unequal covariances (fix with QDA) and the singularity problem when d ≥ n (fix with PCA-first or shrinkage).

Section 06 · LDA vs QDA

When Equal-Covariance Fails → QDA

AspectLDAQDA
Decision boundaryLinear hyperplaneQuadratic (curved) surface
CovarianceOne shared ΣOne Σ per class
BiasHigher (if Σ differ)Lower
VarianceLower (fewer params)Higher (more params)
Needs more data?NoYes
Dimensionality reductionYes (C−1 axes)No
🌗
Bias–Variance In One Choice

LDA fits one shared covariance — fewer parameters, lower variance, but biased when the classes truly differ in shape. QDA fits a covariance per class — flexible curved boundaries, but hungry for data. If a Box's M test flags unequal covariances and you have the samples, QDA usually wins.

Section 07 · Small Samples

Regularized LDA & Choosing A Solver

🩺
Shrinkage Rescues Small-Sample LDA

When samples are scarce, Sᵥᵥ is estimated badly. Regularized LDA blends it toward a simple diagonal target — Sᵥᵥ(λ) = (1−λ)·Sᵥᵥ + λ·(tr Sᵥᵥ/d)·I — where λ=0 is standard LDA and λ=1 is fully shrunk. scikit-learn picks λ for you with shrinkage='auto' (Ledoit-Wolf).

SolverShrinkage?predict_proba?Best Use
svd (default)NoYesStandard LDA, n > d
lsqrYesNoHigh-dim, small sample
eigenYesYesProbabilities + regularization
Section 08 · Code

LDA As Reducer And As Classifier

from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline

# ── as a dimensionality reducer ──
X_scaled = StandardScaler().fit_transform(X)
lda = LinearDiscriminantAnalysis(n_components=2)
X_lda = lda.fit_transform(X_scaled, y)   # needs labels y!
print(lda.explained_variance_ratio_)     # Wine: [0.688, 0.312]

# ── as a classifier (baseline) ──
pipe = Pipeline([('sc', StandardScaler()),
                 ('lda', LinearDiscriminantAnalysis())])
pipe.fit(X_train, y_train)
pipe.predict(X_test)                      # Wine CV acc ≈ 98.9%
🏅
Always Try LDA As A Baseline

On roughly-Gaussian tabular data LDA is astonishingly strong for how little it costs — a matrix multiply and a nearest-centroid check. On the Wine dataset it hits ~98.9% cross-validated accuracy out of the box. Beat that before reaching for anything heavier.

Section 09 · Fisherfaces

PCA → LDA — The Fisherfaces Pipeline

Face images 4096 pixels 400 samples PCA · Eigenfaces 4096 → 150 dims denoise + fix singularity LDA · Fisherfaces 150 → 39 dims 40 classes − 1 Recognize face 93.2% accuracy vs 78.5% PCA-only
📸
Why Two Stages Beat One

You can't run LDA on 4096 features with only 400 faces — Sᵥᵥ is singular. PCA first squeezes the images to 150 denoised dimensions, then LDA extracts the 39 most discriminative directions. The combo lifts accuracy from 78.5% → 93.2% — a +14.7% jump from adding the LDA stage.

Section 09 · Applications

Where LDA Shines

🙂
Face Recognition
The PCA→LDA "Fisherfaces" pipeline is a classic for hundreds of identity classes — biometrics and access control.
🩺
Medical Diagnosis
On the Breast-Cancer dataset LDA reaches ~96% accuracy and 0.995 AUC, surfacing clinically-meaningful features.
🌸
Multi-Class Tabular
On Iris, a single LDA axis captures 99.1% of between-class variance — three species split on one line.
🔬
Interpretable By Design

LDA's discriminant coefficients double as feature importances. On breast-cancer data the top drivers — worst concave points, worst perimeter, mean concave points — line up with known malignancy markers, so the model's reasoning is easy to defend.

Section 10 · Fit

When To Use LDA — And When Not To

✅ Reach For LDA When…❌ Avoid LDA When…
Multi-class tabular data with roughly-Gaussian featuresFeatures are binary, count, or heavily skewed
You want to reduce to C−1 dims before SVM / kNN / NNClasses are very imbalanced (set priors, or use another model)
Face / biometric recognition (PCA → LDA)Boundaries are non-linear (spiral, ring, XOR)
You need a fast, interpretable baseline classifierData is unlabeled — use PCA instead
🌀
Linear Boundaries Only

LDA draws straight decision boundaries. For genuinely curved class structure, reach for kernel LDA, an SVM with an RBF kernel, or a neural network. And for heavily non-Gaussian features, tree models, Naive Bayes, or logistic regression usually serve better.

Section 11 · Golden Rules

Seven Rules For Using LDA Well

🏅 LDA, Distilled
1Always standardize first. LDA computes covariances — feature scale matters. Use StandardScaler in a Pipeline.
2Remember the C−1 ceiling. A 5-class problem gives at most 4 axes — apply PCA first if you need more.
3Use shrinkage='auto' when n < 10d. Ledoit-Wolf fixes an unreliable Sᵥᵥ at minimal cost.
4Check class balance; set priors if imbalanced, so the majority class doesn't dominate the projection.
5Use LDA as a classifier too — call predict(). It's a fast, strong baseline.
6Run PCA before LDA when d ≥ n/10 to handle singularity, cut noise, and speed things up.
7Inspect explained_variance_ratio_. If LD1 > 95%, a 1-D histogram coloured by class is a superb visualization.
Wrap-Up

You Now Understand LDA End-To-End

Sᵦ/SᵥᵥFisher ratio
C−1Max components
Sᵥᵥ⁻¹SᵦEigen-problem
σ=1Standardize first
PCA→LDAFisherfaces
QDAIf Σ differ
🎯
The Through-Line

LDA uses the labels PCA ignores to find the projection that maximizes between-class separation over within-class spread — the Fisher criterion. It reduces to at most C−1 axes, classifies by nearest centroid, and pairs beautifully with PCA for high-dimensional problems like face recognition.

📚
Where To Go Next

Try LDA on Iris, Wine and Breast-Cancer, compare it against QDA when covariances differ, build a Fisherfaces pipeline on the Olivetti faces, and reach for kernel LDA when the boundary curves.

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