LDA, QDA and Fisher’s Discriminant

Two clouds of measurements overlap, yet one well chosen direction can pull them apart. Fisher found it in closed form: aim along Σ−1 times the gap between the class means.

Learn how a classifier built from Gaussian blobs draws its boundary, how it is fitted and tamed when data is scarce, and how one projection turns many measurements into one number.

Press Aim at the means, then Fisher’s direction, and watch the two bumps underneath pull apart. Then drag the angle yourself. Then we build, piece by piece, the Gaussian classifier, its fitting, its regularising, and the algebra that gives Fisher’s direction in one line.

You need what a mean and a variance are (the centre and the spread of a list of numbers) and what a matrix does to a vector. We build the rest from zero.

Based on Lecture 8 of Stanford EE269: Signal Processing and Quantization for Machine Learning, taught by Mert Pilanci; the slides are listed on the course slides page. Every idea is re-taught here in our own words and devices; none of the course’s slide images are reproduced.

Aim the projection

90°

Illustrative data: 70 made-up points per class from two Gaussian blobs with the same tilted covariance, seeded so they are the same on every visit. The ratio is the lecture’s Fisher criterion, computed from these points.

Chapter 0

From Clouds to a Decision

See how a classifier that models each class as a Gaussian cloud turns that picture into one rule, and what this lecture does with it

A microphone listens to someone say a word. From the sound we pull two numbers: the first two formants. A formant is a frequency that the mouth and throat amplify, much like the note a bottle sings when you blow across it. The shape of your mouth sets the formants, so “bed” and “bad” land in different places. The first formant of the vowel in “bed” sits near 530 Hz. In “bad” it sits near 660 Hz.

Now a new sound arrives and its first formant is 590 Hz. Which word was it? Your instinct says: look at where each word usually lands, and pick the nearer one. That instinct is a classifier, a rule that turns a measurement into a label. This lecture asks how to build that rule carefully, and what to do when the measurements are many and the examples are few.

Each class is a cloud

Record a few hundred examples of each word and plot them. Each word makes a cloud: dense near its centre, thinner outward. The standard mathematical shape for such a cloud is the Gaussian, a bell in one dimension and a smooth oval hill in two. Two things define it.

The first is the mean μ, the centre of the cloud. The second is the spread. For one feature the spread is the variance σ2, the average squared distance from the centre. For several features at once it becomes a covariance matrix Σ. Its diagonal holds the variance of each feature. Its other entries say how each pair of features moves together: a positive entry means that when one is high, the other tends to be high too. The covariance decides whether the cloud is a round ball or a tilted, stretched oval.

The rule: the most believable class wins

Write gk(x) for the height of class k’s cloud at the point x. It answers: how likely is this measurement if the sound really was word k? Write πk for the prior of class k, how common that word is before we hear anything. If your app hears “bed” four times as often as “bad”, the priors are 0.8 and 0.2.

The height of a cloud alone is not enough. A rare class can look tall at one spot and still be the wrong bet. So we weigh each cloud by its prior and take the largest. The slide writes this as the classifier f.

f(x)
The label the classifier gives to the measurement x.
arg max
“The k that makes this largest.” It returns the winning label, not the winning score.
k = 1, …, K
Try every one of the K classes. Two words means K = 2.
πk
The prior: the share of all cases that belong to class k. The priors add up to 1.
gk(x)
Class k’s Gaussian cloud, the probability density of x when y = k.

The previous Bayes-classifier lesson shows why this weighing makes the fewest mistakes of any rule, when the clouds and priors are known exactly. Here we take that as given and ask how the rule behaves. Try it first on one feature.

Weigh the two clouds

Blue is “bed”, orange is “bad”, each scaled by its prior. Slide the probe along the first formant. Then change how common “bad” is and watch the purple boundary move.

590 Hz
50%

Illustrative: the two centres (530 and 660 Hz) are rounded textbook-style values for these vowels, and the common spread of 70 Hz is made up. The boundary comes from setting the two weighted heights equal.

With equal priors the boundary sits exactly halfway between the centres, at 595 Hz. Make “bad” rare and the boundary slides toward it, so the rare class owns a smaller stretch of the axis. The cloud heights did not change. Only the weights did.

Work one point by hand

Take the probe at 590 Hz with equal priors of 0.5. The spread is 70 Hz. For “bed” the probe sits 60 Hz from the centre, which is 60/70 = 0.86 spreads away. The bell height there falls to e−½ × 0.862 = e−0.37 = 0.69 of its peak. For “bad” the probe sits 70 Hz away, exactly one spread, and the height falls to e−½ = 0.61 of its peak. The two peaks are equal, so “bed” wins, 0.69 against 0.61.

Divide each weighted height by their sum to get shares: 0.69/(0.69 + 0.61) = 53% and 47%. The 53% is the posterior, the chance that the word was “bed” after seeing the measurement. The device prints the same number. The posterior also says how far to trust the answer. At the boundary it is 50%, a coin toss. Far from the boundary it approaches 100%.

Real systems multiply one such factor per feature, and a long product can fall below the smallest number a computer can store. That is one more reason to take logarithms, as the next chapters do. The ranking of the classes stays the same, and a sum of logs is safe.

The Gaussian cloud, read slowly

The slide gives the formula for gk. It looks heavy, but it has three parts, and the middle one matters most.

gk(x)
The height of class k’s cloud at x, for N features and the covariance Σ.
1 / ((2π)N/2|Σ|1/2)
A constant that makes the total volume under the hill equal 1. A wider cloud (larger determinant |Σ|) gets a lower peak.
(x − μk)TΣ−1(x − μk)
The squared distance from the centre, measured in units of the cloud’s own spread, so a step along a stretched direction counts for less. This is the Mahalanobis distance.

Read the exponent as a penalty. The farther x lies from μk, measured in the cloud’s own units, the more the height falls. The constant in front only sets the overall height. The next chapters take the logarithm of this whole expression, because the log turns the product into a sum and never changes which class wins.

What the lecture does next

The recap leaves three questions open, and the lecture answers them in order. First: what shape does the boundary take, a straight plane or something curved, when the clouds have different shapes? Second: the formula needs μk and Σk, but we only have samples, so how do we estimate them, and what breaks when there are many features and few samples? Third: instead of fighting many features, can we squash them into one number first, in the best possible way? That last answer is Fisher’s discriminant, and the hero at the top of this page already plays with it.

  1. Round blobs of equal size: the boundary is a plane, and the prior slides it.
  2. One shared tilted shape: the plane tilts, and is no longer square to the line between the means.
  3. Every class its own shape: the boundary curves into a quadric.
  4. Fitting the clouds from data: sample means and covariances, and how many numbers each model needs.
  5. Regularising: blending toward a diagonal when samples are scarce.
  6. Projecting to one number: the mean and variance of a shadow.
  7. Fisher’s ratio: separation over spread, as one fraction of quadratic forms.
  8. Maximising a quadratic form: eigenvectors as answers.
  9. Two quadratics at once: whitening and the generalised eigenproblem.
  10. Fisher’s answer: a = P−1(μ1 − μ2), and why it matches LDA.
  11. Field guide: numbers, a checklist, the code, and what comes next.
The measurement x sits exactly where two class clouds have the same height. Class 1 is four times as common as class 2. What does the Bayes rule answer?

Chapter 1

Round Blobs: The Boundary Is a Plane

Derive the boundary between two equally round clouds, and watch the prior push it toward the rarer class

Go back to the vowels, now with both formants, so each sound is a point on a flat map: first formant across, second formant up. Suppose each vowel makes a round cloud, and every cloud has the same size. Nothing is stretched, nothing is tilted. In symbols the covariance of every class is the same simple matrix, Σk = σ2I, where I is the identity matrix (ones on the diagonal, zeros elsewhere) and σ2 says how wide the blobs are.

Where on the map does the classifier switch from one vowel to the other? The slides answer with a formula. We derive it, because the derivation shows why the answer is so simple.

Take logs, and most of the formula disappears

The rule compares πkgk(x) across classes. Taking the logarithm of each score does not change which one is largest, since the log only grows. The log of a product is a sum, so each score splits into three pieces: log πk, the constant in front of the Gaussian, and the exponent.

Now use the fact that all covariances are equal. The constant in front depends only on Σ, so it is the same for every class. It cannot change the winner, so we drop it. What remains for class k is

log πk − ‖x − μk‖2 / (2σ2)

The double bars ‖·‖ mean the ordinary length of a vector, and its square is the squared straight-line distance. Read the score in words: the nearest centre wins, with a head start for common classes. Equal priors remove the head start, and the rule becomes plain nearest-mean classification.

Setting two scores equal

The boundary is where two classes i and j tie. Follow it step by step.

  1. Set the scores equal. log πi − ‖x − μi‖2/(2σ2) = log πj − ‖x − μj‖2/(2σ2).
  2. Collect the distances on one side. ‖x − μj‖2 − ‖x − μi‖2 = 2σ2 log(πj/πi).
  3. Expand the squares. Each square holds an xTx. The two copies cancel in the difference. That is the key step: the curved part vanishes and a straight part remains. The left side becomes 2(μi − μj)T(x − ½(μi + μj)).
  4. Solve for the point. With w = μi − μj, the tie is wT(x − x0) = 0, where x0 is the point below.
wT(x − x0) = 0
The set of points whose offset from x0 is square to w. That set is a line in 2 dimensions and a hyperplane (a flat sheet of one dimension less) in N dimensions.
w
The arrow from the centre of class j to the centre of class i. The plane stands square to it.
x0
A point on the plane: the midpoint of the two centres, then shifted by the term on the right.
shift term
Zero when the priors are equal, because log 1 = 0. Otherwise it slides x0 along w toward the rarer class, by a distance that grows with the blob width σ2.

The slide states the geometry in one line: the hyperplane passes through x0 and is orthogonal (square) to w. Try it.

Slide the plane with the prior

Dots are 40 made-up sounds per class. The purple line is the boundary, the hollow ring is the midpoint of the centres, and the filled purple dot is x0. Widen the blobs, then make one class rare. Points that land on the wrong side get a red ring.

0.90
50%

Illustrative: the centres are fixed at (−1.3, −0.3) and (1.3, 0.5) in made-up formant units, the points are standard random draws scaled by σ (seeded), and the boundary is the lecture’s formula. The error count is over these 80 points only.

With equal priors the boundary cuts the line between the centres exactly in half, at a right angle. Raise the orange share and the line slides toward blue: the common class takes more room. Widen the blobs and the slide gets larger, because a wide cloud says less about where a single point came from, so the classifier leans harder on the prior.

A worked example with priors

Put class i at (0, 0) and class j at (4, 0), with width σ = 1. Class i is four times as common: πi = 0.8 and πj = 0.2. Then w = μi − μj = (−4, 0), and ‖w‖2 = 16. The log prior ratio is log(0.8/0.2) = log 4 = 1.386.

The shift term is (σ2/‖w‖2) × 1.386 × w = (1/16)(1.386)(−4, 0) = (−0.347, 0). Subtract it from the midpoint (2, 0), and x0 = (2.347, 0). The plane crosses the line between the centres 0.35 to the right of the midpoint, closer to the rare class j. A rare class must be clearly nearer to a point before it wins that point.

Beyond two dimensions

Nothing in the derivation used the fact that the points live on a flat page. With sixteen frequency bands, x has 16 entries and so does w. The set of points with wT(x − x0) = 0 is a flat sheet with 15 dimensions, a hyperplane. The classifier does one dot product with w, subtracts one number and reads the sign. That costs 16 multiplications and one comparison per sound.

When the prior swallows a class

Here is a failure worth measuring. Say class j is a rare fault, 3% of cases, and the clouds overlap. The classifier starts to label real faults as normal. How do we see it? Look at the score gap at the fault’s own centre. Plug x = μj into the two scores. The gap in favour of the common class i is log(πi/πj) − ‖w‖2/(2σ2).

If that number is positive, the common class wins even at the heart of the rare cloud, so the rare class is never predicted anywhere near its centre. In the device, put the centres 2.7 apart (they are) and set σ = 1.4. Then ‖w‖2/(2σ2) is about 1.9, and a prior ratio above e1.9 ≈ 6.7 (a rare share below about 13%) erases the rare class’s own centre. The fix is not a better boundary formula. It is a different loss: when a miss costs far more than a false alarm, move the threshold on purpose instead of trusting the prior.

Two round classes have equal priors. Class A has its centre at (0, 0) and class B at (4, 0). Where does the decision boundary cross the line between the centres?

Chapter 2

One Shared Shape: The Plane Tilts

Let the clouds be tilted ovals of the same shape, and find out why the best boundary stops standing square to the line between the centres

Bolt two accelerometers to a motor, one measuring side to side and one up and down. A healthy motor and a worn motor both shake the mounting plate, and that shaking lands in both sensors at once. Whenever one reads high, the other tends to read high too. Plot the pairs of readings and each motor makes a tilted oval, long along the diagonal. The two ovals have the same shape, since the same plate shakes the same way, but they sit in different places.

This is the identical covariance case: Σk = Σ for every class. The matrix Σ is no longer a plain σ2I. It may stretch the cloud in one direction and squeeze it in another. The classifier built on this assumption is called linear discriminant analysis, or LDA, because its boundary is still a flat plane.

The same derivation, with Mahalanobis distance

Repeat the steps of the last chapter. Take logs and drop what is common to all classes: the constant, which holds |Σ|, is the same for each class, so it goes. Class k keeps the score

log πk − ½(x − μk)TΣ−1(x − μk)

Set two scores equal and expand. The term xTΣ−1x appears in both and cancels, just as xTx did before. Because Σ−1 is symmetric, what survives is linear in x again. The boundary is a plane, and the slide gives it in the same form as before.

w = Σ−1(μi − μj)
The new normal of the plane. The matrix Σ−1 bends the plain arrow between the centres into a new direction.
x0
A point on the plane: the midpoint of the centres, shifted when the priors differ.
shift size
The prior log ratio divided by the squared Mahalanobis distance between the centres. If Σ = σ2I this is exactly the shift from Chapter 1.

Check it against the last chapter. Put Σ = σ2I. Then Σ−1 = I/σ2, the vector w is the old arrow divided by σ2, and the shift becomes σ2 log(πi/πj)/‖μi − μj‖2. The two formulas agree. The round case is the special case.

Here is a second way to see the same thing. Stretch the whole space by Σ−1/2, the matrix that squeezes the long axis of the oval and widens the thin one. In the new units every oval becomes a round ball of width 1. Chapter 1 then applies as written: the nearest centre wins, measured in the new units. LDA is nearest-mean classification in a space where the noise has been made round. Chapter 9 uses this same squeeze to solve Fisher’s problem.

What Σ−1 does to the arrow

The slide makes one remark: the plane passes through x0 but not necessarily square to the line between the means. Why? Think of Σ−1 as a weight for each direction. A direction where the cloud is wide is noisy, so a step along it tells you little, and Σ−1 turns it down. A direction where the cloud is narrow is clean, so a step along it tells you a lot, and Σ−1 turns it up. The classifier listens most to the clean directions.

Work one example by hand. Let Σ = [[1, 0.8], [0.8, 1]], and let the arrow between the centres be Δ = μi − μj = (2, 0). The determinant of Σ is 1 × 1 − 0.8 × 0.8 = 0.36. The inverse of a 2 by 2 matrix swaps the diagonal, flips the sign of the off-diagonal, and divides by the determinant, so Σ−1 = (1/0.36)[[1, −0.8], [−0.8, 1]]. Then w = Σ−1Δ = (1/0.36)(2, −1.6) = (5.56, −4.44). That arrow points 38.7° below the horizontal, although the centres differ only along the horizontal. The plane tilts by 38.7° away from square.

Why does this help? The oval is long along the diagonal (1, 1) and thin along (1, −1). A boundary that is square to the means ignores that. The tilted plane runs along the long axis of the ovals and cuts across the thin one, where the classes are well apart relative to the noise.

Tilt the shared shape

Both classes share one oval. The purple line is the LDA plane. The dashed grey line is the plane that stands square to the line between the centres. Change the correlation, then turn the direction of the gap.

0.80
0°

Illustrative: both classes have variance 1 in each feature and correlation ρ; the centres are 2 apart. Error rates are exact for Gaussians with equal priors, from the normal distribution function, not counted from the dots. Dots are 45 seeded draws per class.

At ρ = 0.8 and a horizontal gap, the plane tilts by 38.7°, just as the hand calculation said. The squared Mahalanobis distance between the centres is ΔTΣ−1Δ = 2 × 5.56 = 11.1, so the centres are about 3.3 spreads apart, not 2. With equal priors the error of the best rule is Φ(−3.3/2) ≈ 4.8%, where Φ is the standard normal cumulative distribution (the area under a bell up to a point). The square-to-the-means rule measures the gap against a spread of 1 and errs Φ(−1) ≈ 15.9%.

The failure as ovals get thin

Push ρ toward 0.95 and the ovals become needles. The symptom: the weights in w grow huge and swing with every new batch of data. The measurement: the determinant of Σ shrinks toward zero (it is 1 − ρ2 here), and Σ−1 grows as its reciprocal. A tiny error in an estimated Σ then produces a large error in w. Chapters 4 and 5 return to this: the covariance must be estimated, and a poor estimate is dangerous exactly when the features are nearly redundant.

Two classes share the covariance Σ = [[1, 0.8], [0.8, 1]], and their centres differ only in the first feature. Why is the LDA boundary not square to the line between the centres?

Chapter 3

Every Class Its Own Shape: Curved Boundaries

Let each class keep its own covariance, and watch the straight boundary bend into an ellipse, a hyperbola or a parabola

A healthy motor shakes the same way every time. Its readings make a small, tight cloud. A failing motor is erratic: it sometimes shakes a little, sometimes a lot, so its readings spread over a much larger area. Worse, the average reading of the two motors can be almost the same. Only the spread differs.

Try LDA on this problem. It uses w = Σ−1(μ1 − μ2). If the two centres coincide, w is the zero vector, and a plane with no direction cannot separate anything. LDA is blind to a difference in spread. We need a rule that lets every class keep its own covariance Σk. That rule is quadratic discriminant analysis, or QDA.

Keep every term

Go back to the full log score of class k. This time the covariances differ, so nothing may be dropped except the constant (2π)N/2, which is the same for all classes. The determinant stays:

scorek(x) = log πk − ½ log|Σk| − ½(x − μk)TΣk−1(x − μk)

Now expand the last term. A product of the form (x − μ)TA(x − μ) splits into xTAx, minus 2μTAx, plus μTAμ. Collect the pieces by how they depend on x: one part with x twice (quadratic), one part with x once (linear), and one part with no x at all (a constant). That is exactly the slide’s form.

hk(x)
The class k score, written as a quadratic in x. Classify x as class k when hk(x) beats every other h.
Wk
The curvature of class k’s score. It is the inverse covariance with a factor of minus one half, so a tight class has strongly bending scores.
wk
The tilt of the score: the inverse covariance applied to the class centre.
wk0
A constant that collects the centre’s distance, the cloud’s volume (the determinant) and the prior.

Why the boundary bends

The boundary between classes i and j is where hi = hj. Subtract the two quadratics. The result is again a quadratic: xT(Wi − Wj)x + (wi − wj)Tx + (wi0 − wj0) = 0. Compare this to LDA. With a shared Σ, the matrices Wi and Wj are equal, their difference is the zero matrix, the curved term vanishes, and only the straight part is left. That is the whole reason LDA is linear: shared covariance cancels the curvature.

When the covariances differ, the matrix Wi − Wj = ½(Σj−1 − Σi−1) is not zero, and its signs set the shape. The solution set of a quadratic equation in two variables is a conic, and in N dimensions it is a hyperquadric. If the two eigenvalues of the matrix have the same sign, the boundary is an ellipse, a closed curve around one class. If the signs differ, it is a hyperbola, two open branches. If one eigenvalue is zero, it is a parabola, or a pair of parallel lines when the centres coincide. The slide shows a gallery of these shapes in three dimensions: ellipsoids, paraboloids, hyperboloids, cones, and the flat plane as the limit.

Now see it. Class 1 is the tight cloud. Class 2 is wider, and you set how wide along each axis and how far its centre sits from class 1.

Bend the boundary

The shading shows which class QDA picks at each spot. Stretch class 2 along one axis at a time and watch the boundary turn from a closed curve into open branches. Set the gap to zero: the centres coincide and only the spread tells the classes apart.

1.60
1.60
0.00

Illustrative: class 1 is a round cloud of width 0.55 at the origin; class 2 has widths you choose and sits to the right by the gap; priors are equal. The shape name comes from the signs of the eigenvalues of W1 − W2. Dots are seeded draws; the error count is over these 80 dots.

Start with both widths at 1.6 and gap 0. The centres coincide, so LDA would have no direction. QDA draws a circle around the tight class: inside the circle, class 1 is far more likely than class 2, because its cloud is so much taller there. Now shrink the x width while y stays at 1.6. At exactly 0.55, class 2 is as wide as class 1 along x, and the curve flattens into two parallel lines for an instant. Below 0.55 it opens into two branches, a hyperbola, because class 2 is now thinner than class 1 in one direction and wider in the other.

How wide is the circle?

For two round classes with the same centre and widths a < b, set the two scores equal. The determinant terms give −log a2 against −log b2, and the distance terms give −r2/(2a2) against −r2/(2b2), where r is the distance from the shared centre. Solving gives r2 = 2 log(b2/a2) / (1/a2 − 1/b2). With a = 0.55 and b = 1.6 the ratio b2/a2 is 8.46, its log is 2.14, and 1/a2 − 1/b2 = 3.31 − 0.39 = 2.92. So r2 = 4.27/2.92 = 1.47 and r = 1.21. That is the radius of the blue disc in the device at its starting setting. The determinant term is what stops the wide class from winning near the centre: its peak is lower, so near the centre the tight class is taller.

The price of freedom

QDA is more flexible than LDA, and flexibility has a price. The symptom: the curved boundary wraps tightly around a few points of the small class. The measurement: training error looks excellent while error on fresh data is worse. The reason is that QDA needs one covariance matrix per class, and each must be estimated from that class’s own samples. The next chapter counts exactly how many numbers that is. The fix, in Chapter 5, is to blend the covariances toward something simpler.

Two classes have exactly the same centre, but class 2 is much wider than class 1. Which classifier can tell them apart?

Chapter 4

Fitting the Clouds From Data

Estimate each class’s centre and spread from examples, then count how many numbers LDA and QDA must learn

Nobody hands you the true μ and Σ of a class. You hold a folder of recordings. Every formula so far assumed the clouds were known exactly, and in practice they never are. So the first job is to fit the Gaussian: choose the one bell that best describes the examples you have.

“Best” has a precise meaning. The maximum likelihood (ML) estimate is the Gaussian under which your actual examples were most probable. The slides assume the examples are i.i.d., short for independent and identically distributed: each one is drawn separately from the same cloud, and none depends on another.

One feature: the mean and the variance

Start with one number per example, x1 to xn. The log of the chance of seeing all of them is a sum, one term per example: −n/2 · log σ2 − ∑(xi − μ)2/(2σ2), plus a constant. To maximise it, set the slope to zero. The slope in μ is ∑(xi − μ)/σ2. It vanishes when μ is the plain average. Then the slope in σ2 vanishes when σ2 is the average squared distance from that average. These are the slide’s two lines.

μML
The sample mean: add the examples, divide by how many there are.
σ2ML
The average squared distance from the sample mean. It divides by n, not n − 1, so it runs a little small on average.

Many features: the covariance as an average of outer products

With N features, each example is a vector. The mean is still the average vector. The covariance is the average of an outer product: take the deviation of each example from the mean, a column of N numbers, and multiply it by its own transpose. That gives an N by N table. Entry (r, c) is the product of the deviations in feature r and feature c. Averaging the tables over all examples gives ΣML = (1/n) ∑(xi − μML)(xi − μML)T.

Work a tiny case. Four examples: (1, 2), (3, 2), (3, 4), (5, 4). The mean is (3, 3). The deviations are (−2, −1), (0, −1), (0, 1), (2, 1).

The first feature squared gives 4 + 0 + 0 + 4 = 8, and 8/4 = 2. The cross products give 2 + 0 + 0 + 2 = 4, and 4/4 = 1. The second feature squared gives 1 + 1 + 1 + 1 = 4, and 4/4 = 1. So ΣML = [[2, 1], [1, 1]]. The positive 1 off the diagonal records that the two features rise together.

The lecture divides by n. Many textbooks divide by n − 1 instead. Maximum likelihood gives the first, because it asks which Gaussian makes the data most probable. The second is the unbiased choice: it removes the small tendency of the n version to run low. For the four points above, dividing by n − 1 = 3 gives [[2.67, 1.33], [1.33, 1.33]], a third larger. With hundreds of points the two agree to within a fraction of a percent. With four points they differ a lot, which is a sign that four points are too few.

In a classifier each class gets its own mean from its own examples, and the prior πk is the share of the training set that belongs to class k. For LDA there is one shared Σ: subtract each example’s own class mean first, then average the outer products over all examples together.

Fit a cloud from a sample

The dashed ring is the true cloud. The yellow ring is the fit from the dots you have. Start with a handful of points, then add more. Press New sample to draw the same number again and see how much the fit moves.

12

Illustrative: the true cloud has centre (0.4, 0.2) and covariance [[1.5, 0.9], [0.9, 1.0]]. Points are seeded draws, a different seed on every press. The fit divides by n, as the lecture does.

At two points the fitted oval collapses to a line, because two points can only define one direction of spread. At twelve it already has the right tilt but the wrong size. By a few hundred it sits almost on top of the truth. Press the button repeatedly at small n and watch the yellow ring jump: every fitted number is itself a random number, and fewer examples make it noisier.

Priors are easy to fit. Count how many training examples fall in each class and divide by the total. With 300 “bed” sounds and 100 “bad” sounds the priors are 0.75 and 0.25. Be careful here. If your training set was balanced by hand but the world is not, these counts are the wrong priors for deployment.

Counting the numbers LDA and QDA must learn

A symmetric N by N table has N numbers on the diagonal and N(N−1)/2 distinct numbers above it, the slide’s “(N choose 2)”. In total N(N+1)/2. LDA learns K centres of N numbers each and one shared table, so it learns KN + N(N−1)/2 + N numbers. QDA learns K tables, so it learns KN + K(N(N−1)/2 + N).

For N = 2 and K = 2, LDA learns 4 + 3 = 7 numbers and QDA learns 4 + 6 = 10. That is nothing.

Now take images. A 28 by 28 picture has N = 784 pixels. One table holds 784 × 785/2 = 307,720 numbers. With K = 10 digit classes, LDA learns 315,560 numbers. QDA learns 3,085,040. The famous handwritten-digit training set has 60,000 images.

Count the numbers

The bars use a log scale: each tick is ten times the last. Pick the number of features, classes and samples per class. Compare the two yellow bars to the blue bar of training samples.

100
2
300

The counts are the lecture’s formulas. The feature list reaches 784, the pixel count of a 28 by 28 image. Samples per class are your choice: the scene is illustrative.

When the table cannot be inverted

Here is the failure behind the counts. Suppose a class has fewer examples than features: say 300 images of a digit, each with 784 pixels. The deviations from the mean span at most 299 directions, so the sample covariance has rank 299 or lower and zero spread in all the rest. It is singular: it has no inverse, and the Gaussian formula needs Σ−1 and log|Σ|. The symptom is a crash, or enormous weights from a nearly singular inverse. The measurement: compare the rank of the fitted table to N. The fix is the next chapter.

You have K = 5 classes with N = 50 features each. How many numbers does QDA learn?

Chapter 5

Regularising: Trading Freedom for Stability

Blend a noisy covariance toward its diagonal, and find out how much freedom a small data set can afford

Picture a spectrum analyser that reports the energy in 30 narrow frequency bands for each short slice of a sound. You have 20 slices of each of two kinds of sound. The bands next to each other are strongly linked, because a hum spreads across neighbours. To fit LDA you need a 30 by 30 covariance table, which is 465 distinct numbers, and you have 40 slices to learn them from. The fit will not be good. It will be worse than not good: it will be confidently wrong.

The last chapter showed the cause. A sample covariance with too little data is noisy, and its inverse amplifies that noise most in the directions where the estimate is smallest. We need a way to give up some freedom on purpose.

A plain idea: trust the variances, doubt the links

An N by N covariance table has two kinds of entries. The N entries on the diagonal are variances, one per feature. Each is estimated from all n examples. The N(N−1)/2 entries off the diagonal record how pairs of features move together. There are far more of those, and each is a product of two noisy deviations. The links are the noisiest part of the table.

So the slide proposes a blend between two estimates. The first is the full maximum likelihood table ΣML. The second is its diagonal, written diag(ΣML): the same variances, with every link set to zero. A single number α between 0 and 1 sets the mix.

Σ̂
The regularised covariance that LDA will invert and use in place of the raw estimate.
(1 − α) diag(ΣML)
The cautious part: the variances only, features treated as unrelated.
α ΣML
The trusting part: the full fitted table, links included. At α = 1 you get plain LDA back.

Look at what the blend does entry by entry. On the diagonal, the two parts have the same value, so the diagonal is untouched. Off the diagonal, the first part is zero, so each link is multiplied by α. The recipe is simply: shrink every link toward zero by the factor α. At α = 0 the links vanish entirely. The slide names this endpoint diagonal linear discriminant analysis. It treats the features as independent, which is the idea behind naive Bayes.

The diagonal case has a pleasing meaning for the classifier. The inverse of a diagonal table is just the reciprocals of its entries. So the score for a class becomes a sum over features of (xf − μf)2 divided by that feature’s variance. Each frequency band is judged alone, in units of its own noise, and the verdicts are added up. Nothing about neighbouring bands enters.

A worked example of why this helps

Take the table from the last chapter, ΣML = [[2, 1], [1, 1]]. Its two eigenvalues, the spreads along its two main axes, are (3 + √5)/2 ≈ 2.62 and (3 − √5)/2 ≈ 0.38. The ratio of the largest to the smallest, the condition number, is about 6.9. The inverse stretches by 1/0.38, so any error in the small direction is multiplied by 2.6.

Now set α = 0.5. The links shrink from 1 to 0.5, and Σ̂ = [[2, 0.5], [0.5, 1]]. Its eigenvalues are (3 ± √2)/2, about 2.21 and 0.79. The condition number falls to 2.8. The inverse no longer amplifies noise so hard. The price: the table now understates how strongly the two features are really linked.

The trade, in plain words

Statisticians call this the bias and variance trade. Shrinking adds bias: a systematic error, since the true links are not smaller. But it removes variance: the wobble of the estimate from one data set to the next. When data is scarce the wobble costs more than the bias, so a little shrinking wins. When data is plentiful the wobble is small, and shrinking only adds error. The best α moves with the amount of data.

The slide shows exactly this on a real task: the chart, credited to Hastie and colleagues, plots the misclassification rate of regularised discriminant analysis on a vowel-recognition data set against α. The training error keeps falling as the model gains freedom. The error on held-out test data does not follow it. A model that is judged only on its training data will always prefer more freedom, which is why you must measure on data it has not seen. Try the same effect yourself.

Dial the shrinkage

The browser trains regularised LDA 30 times on fresh made-up data and plots the average error. The dashed line is error on the training points. The purple line is error on 600 fresh points. Move α, then change how many samples each class has.

0.50
20

Illustrative simulation, not the lecture’s vowel data: 30 features with neighbour correlation 0.5, two Gaussian classes whose centres differ by a small amount in every feature, equal priors, a tiny ridge of 10−6 so that a singular table can still be inverted. Averages over 30 seeded trials.

With 20 samples per class, plain LDA at α = 1 trains almost perfectly but does worse on fresh data than a blend near 0.7 or 0.8. Diagonal LDA at α = 0 is stable but misses the links, so it also errs more. The best setting sits in between. Slide the samples down to 14: now the pooled table has rank at most 26 against 30 features, so it is singular, and the test error at α = 1 jumps.

The failure and the fix, in order

The symptom: high accuracy on the training set, a clear drop on new recordings. The measurement: hold out part of the data, and compute the error as α moves from 0 to 1, as the device does. The fix: pick the α where held-out error is lowest. This choice is called tuning a hyperparameter, a setting you choose by testing rather than by fitting.

In the blend Σ̂ = (1 − α) diag(ΣML) + αΣML, what happens to the entries of the table when α = 0.25?

Chapter 6

One Number From Many: The Shadow of a Cloud

Collapse many features into one score with a direction a, and find the mean and variance of that score

A vibration sensor reports the energy in 16 frequency bands, once every tenth of a second. Sixteen numbers per reading is a lot to watch. Suppose you could weigh the bands, adding a lot of the bands where a worn bearing is loud and subtracting the bands where a healthy one is loud, and get a single score. One number is easy to plot, easy to threshold and easy to store. The only question is which weights to use.

This is a projection. Pick a direction a, a list of 16 weights. The score of a reading x is the dot product y = aTx: multiply each band by its weight and add. If a has length 1, y is the shadow of x on the line along a, how far along that line the point lies. If a is a template, y measures how much the reading resembles the template. Signal processing calls this a matched filter.

Why one number can be enough

The slide notes a pattern from the earlier chapters. In LDA with equal covariances the boundary is wT(x − x0) = 0 with w = Σ−1(μi − μj). So the classifier asks only one question about x: is wTx above the number wTx0 or below it? It classifies based on wTx, which is a single real number. Whatever N the data has, two such classes can be told apart by one projection. The other N − 1 directions carry no extra information for the decision.

That suggests turning the question around. LDA found its direction as a by-product of a Gaussian model. What if we choose the direction first, by asking directly which one-number score separates the classes best? That is Fisher’s idea, and it needs no Gaussian assumption to be stated. It only needs two summaries of each class: where it is centred and how it is spread.

The mean of a shadow

Write the true class means as μk = E[x | x comes from class k], where E[·] means “the average over everything in that class”. Write the class covariances Σk = E[(x − μk)(x − μk)T | class k]. The slide’s picture, two ovals and their centres m1 and m2, shows the sample version: average the examples of a class to get its centre.

Project every example. The projected mean of class k is βk = E[y | class k].

Averaging is linear: a sum of weighted terms averages to the same weighted sum of averages. So βk = aTμk. The mean of the shadows is the shadow of the mean. Take the tiny set from the last chapter and the direction a = (1, 0). The shadows are the first coordinates, 1, 3, 3, 5. Their mean is 3, which is the first coordinate of the centre (3, 3).

The variance of a shadow

The spread of the scores is σk2 = E[(y − βk)2 | class k]. Derive it in three short steps. First, y − βk = aTx − aTμk = aT(x − μk). Second, a number equals its own transpose, so the square is (aT(x − μk))(aT(x − μk)) = aT(x − μk)(x − μk)Ta. Third, average over the class. The vector a is a fixed constant, so the average passes through to the middle and leaves the covariance.

βk
The average score of class k: the projection of the class centre onto a.
σk2
The variance of the scores of class k. The covariance table Σk is sandwiched between two copies of a, which sums up how much the cloud spreads along a.

Check it with the same numbers. For Σ = [[2, 1], [1, 1]] and a = (1, 0), aTΣa picks out the top-left entry, 2. For a = (0, 1) it picks the bottom-right entry, 1. For a = (1, 1) it adds all four entries: 2 + 1 + 1 + 1 = 5. The shadow on the diagonal is much wider because the cloud is long along the diagonal.

Cast the shadows

Each class has its own shape. Turn the line. The two bell curves below are the shadows, drawn from βk = aTμk and σk2 = aTΣka. The small ticks are the real projected points.

60°

Illustrative: two made-up classes with different covariances and 150 seeded points each. The bell curves use the formulas; the read-out also states the variance measured from the points, which differs a little from the formula because 150 points are a noisy sample.

The read-out states each variance twice, once from aTΣka and once from the projected points, and they agree up to the noise of 150 points. No simulation was needed to know the width of the shadow: the covariance table already contains the answer for every direction at once.

A bad direction, and why variance is not the goal

A tempting shortcut is to keep the direction with the most spread, since it keeps the most information. That is what principal component analysis does. The symptom of using it for classification: two classes pile onto the same stretch of the line. The measurement: the two bell curves overlap almost completely, even though the line is long. The fix is to ask for a direction that separates the classes, not one that spreads the data. That asks for a ratio, which is next.

A class has covariance Σ = [[2, 1], [1, 1]]. You project onto the unit direction a = (0, 1). What is the variance of the projected scores?

Chapter 7

Fisher’s Ratio: Separation Over Spread

Turn “the classes are far apart and tight” into one number, and write it as a fraction of two quadratic forms

You now know what the shadow of each class looks like: a bell with a mean βk and a variance σk2. Two bells are easy to tell apart when their centres are far apart and their bodies are narrow. They are hard to tell apart when the centres are close, or when the bodies are wide enough to overlap. Both things matter. We want one number that rises with the first and falls with the second.

Radio engineers already have such a number: the signal-to-noise ratio. The signal is the gap between the two means. The noise is the spread of the scores around each mean. Fisher’s idea is to treat the classes the same way, and to pick the direction a that makes this ratio as large as possible.

The criterion

Build it piece by piece. The gap is β1 − β2. Its sign depends on which class we call first, and the sign does not matter for separation, so we square it. The noise is the total spread: add the variances, σ12 + σ22. The ratio is the slide’s objective.

maxa
Search over all directions a for the one that makes the fraction largest.
(β1 − β2)2
The squared gap between the two class means after projection. The signal.
σ12 + σ22
The total spread of the two shadows. The noise.

Why a ratio, and not just the gap? Because the gap alone has no maximum. Double the length of a and every score doubles, so the gap doubles, and so on without end. The ratio does not care: doubling a multiplies the top by four and the bottom by four, and the fraction stays put. The ratio depends on the direction of a and not on its length. That is exactly what we want to search over.

Into matrices

Now use the last chapter’s results. Replace βk by aTμk and σk2 by aTΣka. The top becomes (aT(μ1 − μ2))2. A square of a number is the number times itself, and a number equals its own transpose, so this is aT(μ1 − μ2)(μ1 − μ2)Ta. The bottom is aTΣ1a + aTΣ2a = aT(Σ1 + Σ2)a. Both parts have the same form: a, then a matrix, then a.

aTQa / aTPa
A quadratic form is aTMa for a symmetric matrix M: it turns a direction into one number. Fisher’s criterion is a ratio of two of them.
Q
The between-class matrix: the gap vector times itself. It has rank 1, so it knows only one direction, the line between the centres.
P
The within-class matrix: both covariances added. It describes the noise in every direction at once.

Work the whole thing on six points. Class 1 has the points (1, 4), (2, 6), (3, 5). Class 2 has (5, 1), (6, 3), (7, 2). The centres are m1 = (2, 5) and m2 = (6, 2), so the gap vector is (−4, 3). The deviations of class 1 from its centre are (−1, −1), (0, 1), (1, 0). Summing their outer products gives [[2, 1], [1, 2]]. Class 2 has the same deviations and the same table. Here we add up the products without dividing by n; dividing would scale every number by the same factor and not change which direction wins. So P = [[4, 2], [2, 4]], and Q = [[16, −12], [−12, 9]].

Now score three directions. For a = (1, 0): the top is 16 and the bottom is 4, so J = 4. For a = (0, 1): the top is 9 and the bottom is 4, so J = 2.25. For the unit vector along the gap, a = (−0.8, 0.6): the top is 25 and the bottom is 0.64 × 4 + 2 × (−0.8)(0.6) × 2 + 0.36 × 4 = 2.08, so J = 12.02. Here the direction between the means is far better than either axis. The best direction, which we will find in Chapter 10, scores 12.33. For this data the gap direction is almost perfect, because both clouds have the same mild tilt.

Read J across all angles

Choose a data set. The top shows the two classes. The bottom plots J for every angle from 0 to 180 degrees. The grey mark is the direction between the means. The green mark is the best direction. Drag the angle to see J for the line you choose.

45°

Illustrative: three made-up pairs of classes with a shared covariance, so J(a) = (aTΔ)2 / (2 aTΣa). The best direction is found with the formula of Chapter 10; here you only compare.

With round clouds, J is highest along the gap, and the grey and green marks coincide. With the tilted ovals, the grey mark is far below the peak: the means line scores 2.0, and the best angle reaches 5.6. With heavy overlap, even the best direction scores little. No direction can rescue classes that truly overlap; Fisher’s ratio tells you how much separation is available.

The failure the ratio fixes

Symptom: you choose the direction between the means, because the means are the obvious summary, and the two classes still overlap on the line. Measurement: compute J for that direction and for the best one. If the second is much larger, the noise has a shape you ignored. Fix: let the denominator steer, which is what the ratio does. A good direction does two jobs at once. It leans toward the gap, and it avoids the directions where the noise is large.

Why is Fisher’s criterion a ratio of the squared gap to the total variance, instead of just the gap?

Chapter 8

Maximising a Quadratic Form

Solve the easy version of the search, aTQa over aTa, and see why the answer is always an eigenvector

Fisher’s search looks hard: pick the direction a that maximises a ratio of two quadratic forms, over every direction in N dimensions. Before attacking it, solve a simpler cousin where the bottom is the plainest possible quantity, aTa, the squared length of a. The slide opens the problem exactly this way.

Think of a matrix Q as a machine that stretches the plane. Feed it a direction a and it returns a new vector Qa, usually longer and turned. The number aTQa is the dot product of the input with the output: it asks how much of the output points the way the input did. Dividing by aTa removes the length of a, so the ratio asks one clean question: how strongly does Q stretch a, along a itself? We want the direction where the answer is largest.

Directions that are only stretched

Some directions are special. Feed one to Q and the output points the same way, only longer or shorter: Qu = λu. The direction u is an eigenvector of Q, and the stretch factor λ is its eigenvalue. A symmetric matrix (equal to its own transpose, as every covariance and every Q here is) has a full set of these directions, and they stand square to one another.

Collect them: the unit eigenvectors as columns of a matrix U, and the eigenvalues on the diagonal of Λ. Then Q = UΛUT, the eigenvalue decomposition. Because the columns of U are unit length and mutually square, UTU = I: U just rotates, and does not stretch. For a fuller treatment see the eigenvalues lesson.

The change of basis that does the work

The slide now writes a in the eigenvector axes instead of the original axes: b = UTa, so that a = Ub. Plug this in and follow it line by line.

  1. Start. aTQa / aTa, with Q = UΛUT.
  2. Substitute a = Ub. The top becomes (Ub)TUΛUT(Ub) = bTUTUΛUTUb.
  3. Cancel the rotations. UTU = I appears twice, leaving bTΛb on top and bTUTUb = bTb on the bottom.
  4. Read the result. The ratio is bTΛb / bTb = (λ1b12 + λ2b22 + …) / (b12 + b22 + …).

That last line is a weighted average of the eigenvalues. The weight of λk is bk2, divided by the total. A weighted average can never exceed its largest member, and it reaches the largest only if all the weight sits there. So the maximum is the biggest eigenvalue, λ1, and it is reached by putting b = (1, 0, …, 0): all weight on the first axis. The slide writes this as b = δ[n − k*], a single spike at the index k* of the largest eigenvalue. Translate back with a = Ub: the winner is the eigenvector u1.

aTQa / aTa
The stretch of Q along a itself, with the length of a divided out. Also called the Rayleigh quotient.
λ1
The largest eigenvalue of Q. No direction can be stretched by more than this.
u1
The maximal eigenvector: the direction that Q stretches most. It is the optimal a.
Qu1 = λ1u1
The defining property: Q leaves u1 pointing the same way and only scales it.

Take Q = [[3, 1], [1, 3]]. Its eigenvectors are (1, 1)/√2 with λ = 4 (check: Q(1, 1) = (4, 4)) and (1, −1)/√2 with λ = 2 (check: Q(1, −1) = (2, −2)). Try a = (1, 0), along the first axis. Then aTQa = 3. In the eigen axes, b = UTa = (0.707, 0.707): half the weight on each eigenvalue, and the average of 4 and 2 is 3. Now turn a to the diagonal u1. All the weight lands on λ = 4. The value rises from 3 to 4.

Find the most stretched direction

The dashed circle is every unit direction a. The ellipse is where Q sends them. The teal arrow is your a. The purple arrow is Qa. Below, the value aTQa is plotted against the angle of a. Turn a, then reshape Q.

0°
4.0
2.0
45°

Illustrative: Q is built as UΛUT from the two eigenvalues and the turn you set. The defaults are the worked example above, Q = [[3, 1], [1, 3]]. The weights are cos² and sin² of the angle between a and the first eigenvector.

At the defaults, the curve is a smooth wave between 2 and 4, with its peak at 45°, the diagonal. Slide a to 0° and read 3.0, the average from the worked example. Make λ1 and λ2 equal and the wave goes flat: a round stretch has no favourite direction, and every a ties.

What this buys for Fisher, and what it does not

Fisher’s matrix Q = (μ1 − μ2)(μ1 − μ2)T has rank 1. Its only non-zero eigenvalue is the squared length of the gap, and its eigenvector is the gap direction. So if the bottom were aTa, the answer would be the direction between the means, which is exactly the round-cloud case of Chapter 1. But the real bottom is aTPa, and aTPa is not aTa unless P is a multiple of the identity.

The symptom of applying this chapter’s answer to a tilted problem is the one you saw in the hero: the direction between the means scores poorly. The measurement: compare J along that direction with the best. The fix is to deal with the second matrix, which is next.

For a symmetric matrix Q with eigenvalues 5, 2 and 1, what is the largest value that aTQa / aTa can take, and where is it reached?

Chapter 9

Two Quadratics at Once: Whiten, Then Rotate

Reduce a ratio of two quadratic forms to the easy case by squeezing the space until the bottom matrix is the identity

The easy case had aTa on the bottom. Fisher’s real bottom is aTPa, where P is the total noise matrix. Directions where P is large count as noisy, and directions where P is small count as clean. So the bottom is not the plain length of a. It is a noise-weighted length.

Here is the trick. If we could change coordinates so that the noise-weighted length became an ordinary length, we would be back in the easy case. Changing coordinates is just choosing a new set of axes and new units along each. The slides prove that such a change always exists. Let us see it.

The theorem

The slide states simultaneous diagonalization. Let P and Q be real symmetric N by N matrices, with P positive definite: aTPa is greater than zero for every non-zero a. In words, there is no direction with zero noise. Then a matrix V exists with two properties at once.

VTPV = I
In the new coordinates, the noise matrix is the identity: noise is the same in every direction.
VTQV = Λ
In the same coordinates, Q is diagonal: it has only a stretch along each axis, with no mixing.
Qvi = λiPvi
The generalised eigenvalue equation. The columns vi of V and the numbers λi solve it. For P = I it is the ordinary eigenproblem.

The proof, as a recipe

The slide proves it by building V in two moves. Follow them as a recipe.

  1. Whiten P. Write the eigenvalue decomposition P = UPΛPUPT. Set V′ = UPΛP−1/2. The rotation UP lines the axes up with the noise directions. The factor ΛP−1/2 divides each axis by the square root of its noise, so each noisy axis is shrunk and each clean axis is stretched. Check: V′TPV′ = ΛP−1/2UPTUPΛPUPTUPΛP−1/2 = ΛP−1/2ΛPΛP−1/2 = I. This move is called whitening, after white noise, which has equal power in every direction.
  2. Diagonalise Q in the new coordinates. The matrix Q′ = V′TQV′ is still symmetric, so it has its own decomposition Q′ = U′Λ′U′T.
  3. Combine. Set V = V′U′. Then VTPV = U′T(V′TPV′)U′ = U′TU′ = I, because a rotation leaves the identity alone. And VTQV = U′TQ′U′ = Λ′. Both properties hold.
  4. Read off the equation. From VTPV = I we get VT = V−1P−1, and a short rearrangement of VTQV = Λ then gives QV = PVΛ: column by column, Qvi = λiPvi.

Squeeze the space

The picture is the space of directions a. The ellipse is every a with noise aTPa = 1. The purple lines are directions that give the same gap aTΔ; the highest line that still touches the ellipse marks the winner. Drag Whitening from 0 to 1 and watch the ellipse become a circle.

0.00
0.80

Illustrative: P = 2×[[1, ρ], [ρ, 1]] and the gap Δ = (2, 0). Whitening amount t draws the space after the map Pt/2, so t = 1 is the full whitening of the recipe. The tangent point is the maximiser of the ratio, and it is a = P−1Δ scaled.

At 0 the ellipse is thin and tilted, and the winning touch point is not where the gap arrow points. Move the slider to 1. The ellipse is a circle. The parallel lines are square to a new normal, and the highest line touches the circle exactly along that normal: the easy case, where the winner points straight along the stretch. Now undo the squeeze to read the answer back in the original coordinates. That is a = V b, and it gives the direction P−1Δ, the one the device marks in the first picture.

The last steps: with a = Vb, the ratio becomes bTVTQVb / bTVTPVb = bTΛb / bTb. This is the previous chapter’s ratio. Its maximum is the largest generalised eigenvalue λ1, reached at b = (1, 0, …), so a = v1: the maximal generalised eigenvector.

Walk the proof with numbers

The next device runs the recipe on real matrices. It builds V step by step for P = 2×[[1, ρ], [ρ, 1]] and Q = ΔΔT, and checks both properties at the end.

Build V step by step

Press Next step to move through the recipe. Change ρ to rerun it with a new noise matrix.

0.80

Illustrative 2 by 2 case: P = 2×[[1, ρ], [ρ, 1]] has eigenvectors (1, 1)/√2 and (1, −1)/√2. The matrices are computed live in your browser and rounded to three digits.

Here are the numbers for ρ = 0.8. P = [[2, 1.6], [1.6, 2]] has eigenvalues 3.6 along (1, 1)/√2 and 0.4 along (1, −1)/√2. Whitening divides the first axis by √3.6 = 1.90 and the second by √0.4 = 0.63. The result is V′ = [[0.373, 1.118], [0.373, −1.118]]. Check the first column: P(0.373, 0.373) = (1.342, 1.342), and the dot product with (0.373, 0.373) is 1.00, as required. Then Q′ = V′TQV′ = [[0.556, 1.667], [1.667, 5.000]]. It has rank one, so its eigenvalues are 5.556 and 0. The top one is the answer, and mapping its eigenvector back through V′ gives v1 = (1.179, −0.943), pointing 38.7° below the horizontal. That is exactly the direction of the previous chapters’ tilted plane.

Why must P be positive definite? A covariance sum is positive definite as long as no direction has exactly zero spread, because aTPa is the total variance of the shadow along a, and a variance is never negative. It reaches zero only for a direction along which every example of both classes lies on the same value, which real noisy data does not do, unless there are fewer examples than features.

What can go wrong

The theorem needs P positive definite. The symptom of breaking this: a division by zero, because ΛP−1/2 has a zero eigenvalue under the root. The measurement: the smallest eigenvalue of P is zero, or tiny. That happens exactly when a class has fewer examples than features, the singular covariance of Chapter 4. A direction with zero noise makes the ratio infinite, and the formula will chase noise. The fix is the shrinkage of Chapter 5, applied to P before you invert it.

In the recipe, why do we set V′ = UPΛP−1/2 first?

Chapter 10

Fisher’s Answer: a = P−1(μ1 − μ2)

Use the fact that Q has rank one to solve the generalised eigenproblem by hand, and see that it lands on LDA’s direction

Everything is in place. Chapter 7 wrote Fisher’s problem as the largest value of aTQa / aTPa. Chapter 9 showed that its answer solves the generalised eigenvalue equation Qa = λPa, with λ the best value of the ratio. The slide now notes that P is invertible, so we can multiply both sides by P−1: P−1Qa = λa. That is an ordinary eigenproblem for the matrix P−1Q. We could hand it to a library. Because Q has a very special form, we can solve it by hand.

Why the answer falls out

Recall Q = ΔΔT, with Δ = μ1 − μ2. Put it into the equation. The slide writes the result in one line.

P−1
The inverse of the total within-class noise matrix.
(μ1 − μ2)
The gap vector, a column of N numbers.
(μ1 − μ2)Ta
A row times a column: one single number, the gap seen through a.
λa
The unknown direction a, scaled. We need a to come back as itself, only stretched.

Look at the left side. The product (μ1 − μ2)Ta is just a number, call it s. So the left side is P−1Δ times s. That is a fixed vector times a scalar. The right side says the same thing equals λa. So a must be a multiple of the fixed vector P−1Δ. The slide states the conclusion:

a = constant × P−1(μ1 − μ2), normalised: a := P−1(μ1 − μ2) / ‖P−1(μ1 − μ2)‖2

The constant does not matter, since the ratio ignores the length of a. We divide by the length to get a unit vector. One more check gives the value of λ. Plug a = P−1Δ back in. The left side becomes P−1Δ(ΔTP−1Δ), so λ = ΔTP−1Δ. That number is the best possible value of Fisher’s ratio. It is the squared Mahalanobis distance between the class centres, measured with the noise matrix P.

A hand calculation, start to end

Take the six points of Chapter 7. P = [[4, 2], [2, 4]] and Δ = (−4, 3). The determinant of P is 16 − 4 = 12, so P−1 = (1/12)[[4, −2], [−2, 4]]. Multiply by Δ: first row, 4(−4) + (−2)(3) = −22. Second row, (−2)(−4) + 4(3) = 20. So P−1Δ = (−22, 20)/12 = (−1.83, 1.67), with length 2.48. The unit direction is a = (−0.740, 0.673). The best value is λ = ΔTP−1Δ = (−4)(−1.83) + 3(1.67) = 12.33. In Chapter 7 the direct gap direction scored 12.02. Fisher’s answer does slightly better, and the formula proves that nothing can beat 12.33.

The surprise: it is LDA’s direction

Now compare with Chapter 2. LDA, with a shared covariance Σ, has the normal w = Σ−1(μi − μj). Fisher’s P is Σ1 + Σ2. When the two classes share Σ, P = 2Σ, so P−1Δ = ½Σ−1Δ. The factor of one half only scales the vector. Fisher’s direction and LDA’s normal point the same way. Two different roads, one model that assumes Gaussian clouds and one that only asks for the best signal-to-noise ratio, arrive at the same line. Go back to the worked example of Chapter 2: Σ = [[1, 0.8], [0.8, 1]] and Δ = (2, 0). The unit direction is (0.781, −0.625), at −38.7°. The best ratio is 2 × 2.78 = 5.56, which is half the squared Mahalanobis distance 11.1 that we measured there.

What each road adds: Fisher’s answer is only a direction. To classify you still need a cut-off along the line: LDA gives it, from the priors, as the point wTx0; with no priors, the midpoint of the two projected means is a fair default. When the covariances differ, Fisher’s P = Σ1 + Σ2 still gives a single best direction. It is a compromise, and it cannot bend like QDA.

Fisher and LDA, side by side

Move the two class centres with the sliders, or drag the filled dots with a mouse. The teal line is Fisher’s direction P−1Δ. The purple line is the LDA plane, which stands square to Fisher’s direction. Below, the same points as seen along the teal line.

0°
2.00
0.80

Illustrative: both classes share the covariance [[1, ρ], [ρ, 1]] and have equal priors; the threshold is the midpoint of the projected means. The ratio and angles come from the formulas of this chapter; the error count is over the 100 seeded dots shown, and the exact error is the normal-curve value Φ(−d/2).

At the defaults the read-out reports one angle for both methods: they are the same line. Raise ρ and the angle moves; the Fisher line and the LDA plane move together because they are tied by one formula. Shrink the gap, and the ratio collapses, because the signal shrinks while the noise stays.

When this goes wrong

Symptom: the direction swings wildly between two training sets, and held-out accuracy is poor. Measurement: the smallest eigenvalue of P is close to zero, so P−1 multiplies noise by a large factor. This is the same cure as before. Add the shrinkage of Chapter 5 to P before inverting. The lecture’s derivation is for two classes; with K classes the between-class matrix has rank at most K − 1, so there are at most K − 1 useful directions.

Why must the Fisher direction be a multiple of P−1(μ1 − μ2)?

Chapter 11

The Whole Lecture on One Page

Keep the numbers, the checklist and the core code, and see where this lecture sits in the field

The one-paragraph summary

Model each class as a Gaussian cloud and weigh it by its prior, and the best classifier is the largest score. If the clouds are round and equal, its boundary is a plane square to the gap between the centres, slid by the priors. If they share a tilted shape Σ, the plane tilts to w = Σ−1(μi − μj). If each class has its own shape, the boundary curves into a quadric. The centres and covariances come from the data by maximum likelihood, and the count of numbers grows with the square of the features, so scarce data calls for shrinking the covariance toward its diagonal. Fisher asked for the best single projection instead: the direction a that maximises the squared gap of the projected means over the sum of their projected variances. That ratio of quadratic forms is solved by whitening and an eigenvector, and because the gap matrix has rank one the answer is a = P−1(μ1 − μ2), the same direction as LDA.

The numbers that matter

QuantityFormulaNumber from this lesson
Boundary, round blobsw = μi − μj; x0 = ½(μi + μj) − (σ2/‖w‖2) log(πi/πj) wshift 0 at equal priors; rare class erased at centre when log(πi/πj) > ‖w‖2/(2σ2)
Boundary, shared shapew = Σ−1(μi − μj)tilt 38.7° for Σ = [[1, 0.8], [0.8, 1]] and gap (2, 0)
Boundary, own shapes (QDA)hk = xTWkx + wkTx + wk0, Wk = −½Σk−1ellipse, parabola or hyperbola by the signs of Wi − Wj
Maximum likelihood fitμ = mean; Σ = (1/n) ∑(x − μ)(x − μ)T(1,2), (3,2), (3,4), (5,4) give Σ = [[2, 1], [1, 1]]
Numbers LDA learnsKN + N(N+1)/25,250 for N = 100, K = 2; 315,560 for N = 784, K = 10
Numbers QDA learnsKN + K N(N+1)/210,300 for N = 100, K = 2; 3,085,040 for N = 784, K = 10
Regularised covarianceΣ̂ = (1 − α) diag(ΣML) + αΣMLcondition number 6.9 falls to 2.8 at α = 0.5
Shadow of a classβ = aTμ; σ2 = aTΣaa = (1, 1) gives variance 5 for [[2, 1], [1, 1]]
Fisher ratioJ(a) = aTQa / aTPa; Q = ΔΔT, P = Σ1 + Σ2six points: 4.00, 2.25, 12.02 along the gap
Fisher direction and best valuea ∝ P−1Δ; J* = ΔTP−1Δa = (−0.740, 0.673), J* = 12.33
Error of the best rule, equal priorsΦ(−d/2), d2 = ΔTΣ−1Δ4.8% against 15.9% for the square-to-the-gap rule

A checklist for using it

  1. Count first. Compare K × N²/2 with the number of samples. If a class has fewer samples than features, its covariance is singular.
  2. Fit means, priors and one pooled covariance. Start with LDA, because it learns the fewest numbers.
  3. Shrink. Blend the covariance toward its diagonal, and pick α by the error on held-out data.
  4. Look for curved structure. Move to QDA only if class spreads clearly differ and each class has enough samples.
  5. Project when one number is enough. Compute a = P−1(μ1 − μ2), then set a threshold along the line.
  6. Check the ratio. Compare J along the gap and along a. A large difference means the noise has a shape you needed to account for.

The core as code

The whole lecture fits in a few lines of NumPy. The shapes are in the comments: X is (n, N), y is (n,), mu is (K, N), and S is (N, N).

pythonimport numpy as np

def fit_gaussians(X, y):                        # Ch 4: maximum likelihood fit
    classes = np.unique(y)
    mu  = np.array([X[y == k].mean(0) for k in classes])          # (K, N) class centres
    pri = np.array([(y == k).mean() for k in classes])            # (K,) priors, sum to 1
    R = np.vstack([X[y == k] - mu[i] for i, k in enumerate(classes)])  # deviations from OWN class mean
    S = R.T @ R / len(X)                                            # (N, N) pooled covariance, divide by n
    return classes, mu, pri, S

def shrink(S, alpha):                               # Ch 5: alpha = 1 plain, alpha = 0 diagonal LDA
    return (1 - alpha) * np.diag(np.diag(S)) + alpha * S

def lda_predict(X, classes, mu, pri, S):              # Ch 2: linear score per class
    W = mu @ np.linalg.inv(S)                                   # (K, N), row k is mu_k^T S^-1
    b = -0.5 * np.sum(W * mu, axis=1) + np.log(pri)         # (K,) constants
    return classes[np.argmax(X @ W.T + b, axis=1)]           # (n,) labels

def fisher_direction(X1, X2, alpha=1.0):               # Ch 10: a = P^-1 (mu1 - mu2)
    m1, m2 = X1.mean(0), X2.mean(0)
    P = (X1 - m1).T @ (X1 - m1) + (X2 - m2).T @ (X2 - m2)       # (N, N) within-class scatter
    d = m1 - m2                                                 # (N,) the gap
    v = np.linalg.solve(shrink(P, alpha), d)                    # P^-1 d without forming the inverse
    return v / np.linalg.norm(v), d @ v                         # unit direction a, best ratio J*

a, J = fisher_direction(X1, X2, alpha=0.9)
score = X @ a                                                   # (n,) one number per example
t = a @ (X1.mean(0) + X2.mean(0)) / 2                     # threshold at the midpoint of the projected means
label = np.where(score > t, 1, 2)

Note two small design choices. The code solves a linear system instead of inverting P, which is faster and more stable. And it shrinks P before solving, which is the single line that keeps the whole method alive on small data sets.

Where this sits

Gaussian classes and Bayes’ rule belong to the Bayes-classifier lesson; the Gaussian itself is in the multivariate Gaussian lesson. Treating the features as independent is naive Bayes, the α = 0 end of this lecture’s dial. Choosing the direction of most variance, instead of the direction of best separation, is PCA, and the eigenvector machinery behind both is in the eigenvalues lesson and the SVD lesson. A later session of this course turns to support vector machines, which also draw a straight boundary but choose it by a margin instead of by a Gaussian model.

Keep going

The takeaway. A classifier needs three things: a model of each class, enough data to fit it, and a way to turn it into a decision. Gaussian clouds give the model and a boundary that is a plane when the shapes are shared. Counting the numbers tells you when the data runs out, and shrinkage buys stability. Fisher’s ratio asks a sharper question, which single direction separates best, and the answer is one matrix equation: a = P−1(μ1 − μ2).

Now press Present or Teach and explain it from memory: why the quadratic term cancels in LDA but not in QDA, how many numbers each model learns, what the diagonal blend does to a covariance, and how a rank-one Q turns a generalised eigenproblem into a single line. Then go back to the hero and aim the line at Fisher’s direction once more, knowing what makes it best.

EE269 Lecture 8 (session 16): LDA, QDA and Fisher’s Discriminant
Course by Mert Pilanci, Stanford: the course site · the slides page · Next session · Back to Gleams