A signal that comes out different every time can still follow one rule. Draw many random sine waves and watch their covariance matrix settle into one value down every diagonal.
Learn how to describe a random signal with a mean and a covariance, why stationarity shrinks N² unknowns to N, and how the same Gaussian model gives the classifiers called LDA and QDA.
Press 5,000 draws, then drag the pitch. Each draw is one sine wave with a random size and a random start. Then we build, piece by piece, the mean, the covariance, the autocorrelation, and the two classifiers that use them.
You need the idea of an average (add up, divide by the count) and a little matrix arithmetic (a table of numbers you can multiply). We build the rest from zero.
Based on Lecture 7 (the course deck; this series numbers it 15) of Stanford EE269: Signal Processing for Machine Learning, taught by Mert Pilanci. The explanations, devices and toy numbers are ours; the derivations and formulas follow the deck.
Each draw is x[n] = A sin(nω0 + φ) with A from a bell curve of variance σ² = 1 and φ uniform on [−π, π], the lecture’s example (slide 7). The grid shows the average of x[k]·x[l] over the draws, computed live in your browser. Purple cells are positive, yellow cells are negative. The teal outline marks the lag-3 diagonal.
Chapter 0
See why one recording is only one draw from a whole family of possible signals, and learn the first number that describes the family
Say the word “ah” into a microphone ten times. You get ten waveforms. No two match. The pitch wobbles a little, the loudness changes, and the breath starts at a different instant. Yet you would never confuse any of them with the word “ee”.
Something stays the same across all ten takes. It is not the exact curve. It is the pattern of the curves: how loud they tend to be, how fast they tend to wiggle, how a sample relates to the one just before it. This lecture gives that pattern a precise name and a few numbers to measure it.
The lecture is session 7 of the course deck, given by Mert Pilanci on 30 January 2019. It has two halves. The first half describes random signals with a mean and a covariance. The second half uses those same Gaussian descriptions to build two classifiers, LDA and QDA. We keep the lecture’s order and explain every slide.
A random signal is a signal produced by a process with chance in it. Think of a machine that, each time you press a button, rolls dice and then prints out a waveform. The machine is the random process. One printed waveform is a realization, also called a sample path.
Engineers write the process as x[n]. The square bracket and the letter n mean that time comes in steps: sample 0, sample 1, sample 2. At each step, x[n] is not a fixed number. It is a random variable, a number that is decided by a roll of the dice and so changes from draw to draw.
The set of every waveform the machine could print is the ensemble. When you record your voice once, you see one member of the ensemble. Everything the lecture does is about describing the whole ensemble from a few numbers.
The simplest number is the average. Fix one time step, say n = 30. Ask every waveform in the ensemble for its value at step 30, and average those values. That average is the mean at time n. The lecture writes it as mx[n] and defines it with the symbol E.
Notice the direction of the average. It runs across the ensemble at a fixed time. It does not run along one waveform through time. Those two averages are different things, and mixing them up is the classic mistake in this subject. Try it below.
Sixty draws of a noisy sensor, each a thin blue path. The bold path is draw number one. Drag the time cursor and watch the purple mean curve. The bars on the right show the 60 values at the cursor.
Illustrative sensor. Each path is a smooth random wobble (each sample is 0.9 times the one before, plus fresh noise, scaled to a spread of 1), and in the warm-up process a rising baseline m[n] = 1.5(1 − e−n/25) is added. The paths are seeded, so they repeat on each visit until you press the button.
In the steady hum, the mean curve is flat at zero, but every path wanders far from zero. In the warm-up, the mean curve climbs, and the paths climb with it on average. Either way, no single path equals the mean curve. The mean is a property of the ensemble.
A classifier never sees the ensemble. It sees a few recordings. To say anything about a vowel, a heartbeat or a bearing hum, it must guess the ensemble’s numbers from the draws it has. Chapter 9 shows how.
Before that, we need to know which numbers to ask for. The mean is the first. It says where the signal sits. It says nothing about how a sample at one time relates to a sample at another time. A flat steady hum and a wild static hiss can have the same mean of zero. We need a second number that sees the difference, and that is the covariance of Chapter 1.
Chapter 1
Measure how the value of a signal now predicts the value later, and package every such link in one square table
Look at a slow ocean swell recorded by a buoy, once a second. If the buoy sits high at 12:00:00, it will almost surely sit high at 12:00:01. Now look at the hiss from a radio tuned between stations. A high sample at one instant says nothing about the next.
Both signals can have the same mean and the same typical size. The mean cannot tell them apart. What differs is the link between moments. The swell has a strong link. The hiss has none. The covariance measures that link.
Start with two random numbers, a and b. Each has a mean. Draw them many times. In each draw, check two things: is a above its own mean, and is b above its own mean?
If they are usually above together or below together, they move together. If one is high when the other is low, they move apart. If neither pattern wins, they are unrelated in this straight-line sense. The covariance turns that check into a number: multiply the two gaps from their means, then average the products.
When both gaps are positive, the product is positive. When both are negative, the product is also positive. When the signs differ, the product is negative. So the average is positive for numbers that move together, negative for numbers that move apart, and near zero for unrelated numbers.
Apply that idea to a signal. Pick two time steps, k and l. The random numbers are x[k] and x[l]. The lecture’s slide 3 writes their covariance as Σx[k, l], called the autocovariance. The prefix “auto” means the signal is compared with itself at another time.
When k equals l, the two gaps are the same gap. Their product is a square, so Σx[k, k] is the variance at time k: how widely the signal scatters around its mean there. The diagonal of the table holds the variances.
Take four draws and look at only two time steps. The values are in the table. The means are zero at both steps, so the gaps equal the values.
The variance at step 0 is (1 + 1 + 4 + 4) / 4 = 2.5. The same holds at step 1. The covariance Σ[0, 1] is 2.25, close to the variance. The two steps move almost in lockstep. Dividing by the spread, 2.25 / 2.5 = 0.9, gives a correlation of 0.9: the covariance rescaled so that 1 means a perfect straight-line link.
Now see the same thing on a bigger ensemble. Below, each dot is one draw of a smooth random signal. Its horizontal position is the value at time 0. Its vertical position is the value a few steps later.
Left: 300 draws, each one a dot at (x[0], x[lag]). Right: the true covariance table for six time steps, with the cell for your lag outlined. Raise the memory so each sample leans on the one before. Then raise the lag and watch the cloud round out.
Illustrative smooth signal: each sample is a times the previous one plus fresh noise, scaled so every sample has variance 1. Its exact covariance is then alag, shown in the table. The estimate is the average of x[0]·x[lag] over the 300 seeded draws.
At memory 0.9 and lag 1, the cloud is a thin tilted sausage and the covariance is about 0.9. At lag 5 it fattens to about 0.59. At memory 0, the cloud is a round ball and the covariance is zero. The tilt of the cloud is the covariance.
Record N samples and stack them in a column: x = [x[0], x[1], …, x[N−1]]. The covariance of every pair fits in an N × N table. The entry in row k and column l is Σx[k, l]. This table is the covariance matrix, written Σ. It is symmetric for real signals, because the link from k to l equals the link from l to k.
Slide 4 makes a harmless simplification. If the mean is not zero, subtract it from every sample first. That changes nothing about the links, since covariance already works with gaps from the mean. After centering, mx[n] = 0 and the formula shrinks to Σx[k, l] = E x[k] x*[l], the average of the plain product. We use this form from now on.
The table has N rows and N columns, so it holds N² numbers. For one second of audio at 16,000 samples per second, N is 16,000 and the table has 256 million entries. In 64-bit numbers that is about 2 gigabytes. No recording set will ever pin down 256 million separate links. We need a rule that ties the entries together. That rule is stationarity, the next chapter.
Chapter 2
Learn the one rule that ties the entries of a covariance matrix together, and test it on three signals
A refrigerator hums. Record two seconds at 3:00 and two seconds at 3:05. Play them back to back and you cannot tell where the join is. The loudness, the pitch and the way each sample leans on the next are the same. The hum does not care what time it is.
Now record a band starting a song, from silence to full volume. The first second and the last second are plainly different. The rules of that signal depend on the clock.
Chapter 1 left us with a bill of N² covariance numbers. The saving comes from signals like the fridge. If the rules do not change with the clock, then the link between times 10 and 11 must equal the link between times 500 and 501. One number can serve both.
Slide 5 states the rule. A signal is wide sense stationary, or WSS, if two things hold. First, the mean is the same at every time. Second, the covariance Σx[k, l] depends only on the difference k − l, the distance between the two times. It does not depend on where in time the pair sits.
The word “wide” marks a weak requirement. Strict stationarity demands that every statistic of the process stays fixed over time. Wide sense asks only for the first two: the mean and the covariance. For Gaussian signals the two are the same, because a Gaussian is fully described by its mean and covariance. That is why the lecture can use the weak version.
The slide first sets the mean to zero, as in Chapter 1. Then the second condition reads: the covariance E x[k] x*[l] is a function of k − l alone.
Slide 6 names that function. Because it depends on one number, the gap, we give it one argument. The autocorrelation rx[m] is the average product of the signal with a copy of itself shifted by m steps.
For a signal with zero mean, autocorrelation and autocovariance are the same thing. With a nonzero mean they differ by the mean squared. The lecture uses both words for the zero-mean case, and so do we.
Three facts follow, and each has a plain reading. First, r[0] is the average of x[n] times itself: the power of the signal, which is never negative. Second, r[−m] equals the conjugate of r[m]: looking forward by m is the mirror of looking back by m. Third, |r[m]| is never larger than r[0]. A signal cannot match a shifted copy of itself better than it matches itself. (A proof: the average of a product never exceeds the product of the two root-mean-squares, and both root-mean-squares equal the square root of r[0].)
Take the smooth signal of Chapter 1 with memory 0.8. Its autocorrelation is r[m] = 0.8|m|. So r[0] = 1, r[1] = 0.8, r[2] = 0.64 and r[3] = 0.512. The covariance between times 5 and 6 is r[1] = 0.8. The covariance between times 400 and 401 is also 0.8. One number does the work of every neighbour pair in the recording.
A stationary signal of N samples now needs only N numbers, r[0] to r[N−1], instead of N². Test the rule on real-looking signals below.
Pick a process. The grid is its covariance table estimated from 2,000 draws of 16 samples. The curves show the diagonal entries as the pair slides along in time. A stationary process gives flat curves.
Illustrative processes, each with 16 samples. Hum: memory 0.8 at every step. Fade-in: the same hum multiplied by a gain that rises from 0.4 to 1.6. Smoothing out: the variance stays 1, but the memory rises from 0.1 to 0.95 across the window. The verdict calls a process stationary when the lag-1 entries differ from their average by less than a quarter of it; sampling noise from 2,000 draws is about a twentieth.
The fridge hum passes: both curves are flat, and every diagonal of the grid has one colour. The fade-in fails at once. Its variance curve climbs from about 0.16 to 2.6, so the diagonal is not constant.
The third process is the sly one. Its mean is zero and its variance is 1 at every time, so a quick check passes. Only the lag-1 curve gives it away: the link between neighbours climbs as the signal smooths. You must check the covariance, not just the mean and the variance.
Symptom: the diagonals of your estimated table drift. Measurement: compare the same lag at early and late times, as the curves do. Fix: cut the signal into short frames, short enough that the rules barely change within each frame, and treat each frame as stationary. This is the idea behind the short-time Fourier transform of the STFT lesson. Speech analysis commonly uses frames of 20 to 30 milliseconds for this reason.
Chapter 0 asked when a time average along one recording equals the ensemble mean. The lecture does not name the condition, so this paragraph is our addition. If a signal is stationary and also ergodic, meaning one long recording visits every behaviour the ensemble contains, then averaging along time gives the ensemble numbers. That is what lets you estimate r[m] from a single long recording of the fridge, rather than from thousands of separate fridges.
Chapter 3
Prove that a sine wave with a random size and a random start is stationary, and see what its autocorrelation reveals
A sensor sits near a power line. It picks up a hum at a fixed frequency, the mains. How strong the hum is depends on where the sensor sits, and that changes from placement to placement. When your recording starts, the hum is at some point in its cycle, and that point is different each time.
The pitch is fixed. The strength and the starting point are random. This is the lecture’s example signal on slides 7 to 9, and it is the cleanest case where we can compute the covariance by hand. Follow every step. The result is short and beautiful.
The signal is x[n] = A sin(nω0 + φ). Here n is the sample number. The frequency ω0 is fixed, in radians per sample. The two random pieces are the amplitude A, the size of the wave, and the phase φ, where in its cycle the wave starts.
The lecture picks A from a bell curve with mean 0 and variance σ², written N(0, σ²). The phase φ is uniform over [−π, π]: every starting point in the cycle is equally likely. The two are drawn independently, which lets us average over one at a time.
Slide 7 writes E x[n] = EA[A] · Eφ[sin(nω0 + φ)]. The first factor is the mean of A, which is 0. So the whole product is 0. The second factor is also 0 on its own: a sine averaged over a whole cycle of starting points gives as much below zero as above. Either factor alone kills the mean.
With a zero mean, the covariance is the plain product average. Slide 8 gives it in three lines.
The two A factors multiply into A², which does not involve φ, so it comes out of the phase average. Since A has mean 0, E[A²] is exactly its variance, σ². The covariance is now σ² times a pure phase average.
Slide 9 uses the trigonometric identity 2 sin α sin β = cos(α − β) − cos(α + β). Set α = kω0 + φ and β = lω0 + φ. Subtract them, and φ cancels: α − β = (k − l)ω0. Add them, and φ doubles: α + β = (k + l)ω0 + 2φ.
Take a quick numeric check. Let k + l = 1 and ω0 = π/4. Try four phases: φ = 0, π/2, π and 3π/2. The angles (k + l)ω0 + 2φ are π/4, 5π/4, 9π/4 and 13π/4. The cosines are +0.707, −0.707, +0.707 and −0.707. They average to zero.
The more phases you use, the closer the average sits to zero. Watch it happen.
Each dot is the angle (k + l)ω0 + 2φ for one phase, on a circle. The cosine is the dot’s horizontal position. The purple arrow points at the average of all the dots. Add phases and the arrow shrinks to nothing. Then fix the phase and see it stay.
Fixed at ω0 = π/4 (eight samples per cycle). Random phases come from a seeded generator, so they repeat on every visit. With uniform phases the length of the average arrow falls roughly like one over the square root of the number of draws; it is exactly zero only in the limit.
With a random start, the average arrow shrinks toward the centre, and the cosine average goes to zero. With a fixed start, every dot lands on the same spot and the arrow stays long. The shrinkage is what makes the signal stationary.
Drop the vanished term. Slide 10 states the answer: r[k − l] = (σ²/2) cos((k − l)ω0). It depends only on k − l, so the signal is wide sense stationary.
Put in numbers. Take σ² = 1 and ω0 = π/4, so one cycle lasts eight samples. Then r[0] = 0.5, r[1] = 0.354, r[2] = 0, r[3] = −0.354, r[4] = −0.5, and r[8] = 0.5 again. The autocorrelation is itself a cosine, at the same frequency as the signal. It is the hero’s lag-3 cell: cos(3 × 0.8) × 0.5 = −0.37 at the default pitch.
The random amplitude and the random start are gone from r[m]. Only the frequency is left, written in the rhythm of the cosine. So you can read the pitch off the autocorrelation of any recording, however it was started. The first peak after lag 0 sits at one period. A voice at 200 Hz sampled at 16,000 Hz repeats every 80 samples, so its autocorrelation peaks at lag 80. This is the basis of classic pitch detectors.
Symptom: a recording always begins at the same point of the cycle, for instance because a trigger fires on a rising edge. Measurement: with φ fixed at 0, the second term does not vanish, and Σ[k, l] = σ² sin(kω0) sin(lω0). The variance Σ[k, k] = σ² sin²(kω0) now breathes in time, and it is exactly zero at k = 0. Fix: randomize the start, or treat the process as non-stationary and model the fixed shape directly. The uniform phase is not a detail. It is the assumption doing all the work.
Chapter 4
Watch the stationarity rule turn a covariance table into stripes, and see why stripes that wrap around connect to the Fourier transform
Picture the covariance table as a rug. Row k, column l holds the link between time k and time l. Stationarity says that link depends only on k − l. Now walk down any diagonal of the rug, from top left to bottom right. The row and the column both go up by one, so the gap k − l does not change. Every cell on the diagonal holds the same number.
A table with constant diagonals looks like a rug woven in stripes. This chapter names that pattern, counts how much it saves, and then asks when the stripes wrap around the edge of the table.
Slide 10 writes the covariance matrix of a stationary signal in full. The first column is r[0], r[1], r[2], down to r[N−1]. The first row is the conjugates r*[0], r*[1], and so on. Every other cell is copied along its diagonal. A matrix with constant diagonals is a Toeplitz matrix, named after the mathematician Otto Toeplitz.
For a real signal the conjugates do nothing, so the matrix is symmetric. Here is a concrete case with N = 4 and the values r[0] = 2, r[1] = 1, r[2] = 0.5, r[3] = 0.25.
Four numbers fill sixteen cells. The same four numbers fill every diagonal. That is the whole saving: a stationary signal of N samples needs N numbers, not N². For the 16,000-sample second of audio, a general symmetric covariance has about 128 million separate numbers to find, and a stationary one has 16,000.
The saving also helps the estimate. Each diagonal collects many pairs of samples that all measure the same number, so you can average them. The lag-1 value is the average over 15,999 pairs. Compare that with a general table, where each entry is measured by one pair per draw.
Sometimes the stripes wrap around the edge. Slide 10 gives the condition: r[N − k] = r*[k]. Read it as a statement about lags. A lag of N − k, going far forward, looks the same as a lag of −k, going a little back. The autocorrelation repeats with period N, like a clock where 11 hours ahead equals 1 hour back.
A matrix with that property is circulant: each row is the row above it, shifted one step to the right, with the last entry wrapping round to the front. The slide ties it to the random sinusoid: it holds when ω0 = (2π/N) × an integer.
Check it with the autocorrelation from Chapter 3. With ω0 = 2πj/N, the value cos((N − k)ω0) is cos(2πj − kω0), and that equals cos(kω0). So r[N − k] = r[k], as needed. In words: the window of N samples holds a whole number j of cycles of the hum, so the end of the window joins the start without a seam.
A circulant matrix has a special gift. Its eigenvectors, the directions it only stretches without turning, are always the same: the complex waves ei2πjn/N of the DFT, whatever the matrix is. Its eigenvalues, the stretch factors, are the DFT of the first row. So the DFT of r[m] tells you how much of the signal’s power sits at each frequency. You can read more about the DFT in the DFT lesson.
A worked case: N = 4, σ² = 1, j = 1. Then r[m] = 0.5 cos(mπ/2), so r = (0.5, 0, −0.5, 0).
The eigenvalue at bin j is the sum over m of r[m] e−i2πjm/4. Only m = 0 and m = 2 are nonzero. So the eigenvalue is 0.5 − 0.5(−1)j. That gives 0, 1, 0, 1 for j = 0, 1, 2, 3.
All the power sits at bins 1 and 3, the pair for +1 and −1 cycles per window. The eigenvalues add to 2, which equals N × r[0] = 4 × 0.5. Total power is the same in either view.
Try the build below. Pick a process. The table shows the Toeplitz matrix. The bars show what the DFT of its first row reports.
Choose a process. The grid is the covariance table built from the 8 autocorrelation numbers. The bars give the power at each of the 8 frequency bins, found by the DFT of the first row. The last choice does not fit a whole number of cycles in the window.
Illustrative, N = 8, r[0] = 1. White noise: r[m] = 0 for m > 0. Smooth hum: r[m] = 0.6 to the power of the shorter way round the window, min(m, 8 − m). Sine with j cycles: r[m] = cos(2πjm/8), and j = 2.3 for the last choice. Bars are the sum over m of r[m]cos(2πbm/8), the real DFT of the first row; for a circulant table they are its exact eigenvalues.
White noise gives a table that is all zeros off the diagonal, and flat bars: equal power at every frequency, which is where the name “white” comes from. The smooth hum puts most power at low frequencies. The 2-cycle sine puts all its power on two bins, 2 and 6. The 2.3-cycle sine is not circulant. Its tallest bars still sit at bins 2 and 6, but power spills into bins 1, 7 and even 0. This smearing is the leakage you meet when a window cuts a wave in the middle of a cycle.
Chapter 6 will meet the identity matrix scaled by a number, σ²I. It is the Toeplitz matrix of white noise: r[0] = σ² and every other lag zero. That plain case is where the classifiers begin.
Chapter 5
Turn the Bayes rule into a score you can compute when every class is a Gaussian, and see how a rare class moves the boundary
A vibration sensor sits on a pump bearing. Each minute it reports one number: how strongly the bearing shakes. A healthy bearing reports values around 2. A worn one reports values around 5. Both scatter a little from minute to minute. Today the sensor reads 3.6. Healthy or worn?
The reading is closer to 5 than to 2. But wear is rare: say only one bearing in ten is worn. Does that change your answer? The Bayes rule says yes, and says exactly how much. This chapter builds that rule for signals, using the covariance matrices of Chapters 1 to 4.
The lesson on Bayes classifiers, the lecture before this one, proves it. Here is the short form. For each class k you need two things. The prior πk is how common class k is before you look at any reading. The class density gk(x) says how likely a reading x is when the class is k. The slide writes the density as Px|y=k, read “the probability of x given that the label y is k”.
Multiply the two, πk gk(x). That product is proportional to the probability of class k after you have seen x. Pick the class with the largest product. Slide 11 writes this as f(x) = arg maxk πk gk(x), where “arg max” means “the k that gives the biggest value”. This rule makes the fewest mistakes of any rule, on average, when the densities and priors are right.
To use the rule you need a formula for gk. The lecture assumes each class is Gaussian: its readings scatter around a centre in a bell shape. The signal here is a window of N samples, x = [x1, …, xN]. That is a point in N dimensions, and the bell becomes a smooth hill in N dimensions.
Two matrix symbols appear. μk is the centre (mean) of class k. Σ is its covariance matrix, the table from Chapter 1. When x is a window of a stationary signal, Σ is the Toeplitz matrix of Chapter 4. Here is the bridge from the first half of the lecture to the second: the autocorrelation is the shape of each class’s hill.
The product πk gk is a tiny number in many dimensions, and the exponential is awkward. The logarithm is a steadily rising function, so the class with the largest product also has the largest logarithm. And log turns a product into a sum, and kills the exponential. Slide 12 does this for two classes that share the covariance Σ. Class 1 wins if
The scale factor 1/((2π)N/2|Σ|1/2) is the same for both classes when they share Σ, so it cancelled. Each side is a score: the log prior minus half the squared, spread-adjusted distance to the class centre. The class with the higher score wins.
Slide 13 takes the simplest setting: Σ is the identity matrix I, and both priors are one half. The log priors are equal and cancel. What is left is −½||x − μ1||² > −½||x − μ2||². Class 1 wins when x is nearer to μ1 than to μ2. That is the plain nearest-mean rule from the distance classification lesson.
Use one dimension with spread σ = 1, centres μ1 = 2 (healthy) and μ2 = 5 (worn), priors 0.9 and 0.1. For the reading x = 3.6, the score for healthy is ln 0.9 − ½(1.6)² = −0.105 − 1.28 = −1.385. The score for worn is ln 0.1 − ½(1.4)² = −2.303 − 0.98 = −3.283. Healthy wins, even though 3.6 sits nearer to 5. The prior outweighed the distance.
Where does the call flip? Set the two scores equal. The squared distances differ by (x − 2)² − (x − 5)² = 6x − 21. So ln 9 = ½(6x − 21), which gives x = 4.23.
With equal priors the boundary would sit at 3.5, halfway. The rare class has pushed it 0.73 toward the worn side. Move the sliders to see it.
Each hill is a class density times its prior. The taller hill at your probe point wins. Drag the probe, then lower the prior of healthy and watch the boundary slide.
Illustrative bearing: healthy centred at 2, worn at 5, both with the same spread σ. The curves are πk times the bell curve of class k. Scores are log πk − (x − μk)²/(2σ²), the one-dimensional form of slide 12.
At the default settings the probe sits left of the boundary, so healthy wins. Slide the prior of healthy down to 0.5 and the boundary returns to 3.5. Now the same reading of 3.6 is called worn. Same data, different belief about how common wear is.
Symptom: with a rare class at a prior of 0.1, a classifier almost never reports it. Measurement: count errors per class, not only overall. At the boundary 4.23 above, a worn bearing that reads 4.0 is called healthy. Overall error is as low as it can be, but the misses all fall on the class you care about. Fix: this is a question of costs, not of the rule. Either reweight the classes by their cost, or move the threshold. The Bayes rule itself stays correct for its stated goal, which is fewest total mistakes.
Chapter 6
Derive the linear score for classes with equal round spread, find where the boundary sits, and see when it reduces to the nearest mean
Imagine three kinds of vowel sound, each measured by two numbers, so each recording is a dot on a plane. The dots of each vowel gather in a round cloud around that vowel’s centre. All three clouds are the same size. A new dot lands on the page. Which cloud does it belong to?
Your hand wants to say “the nearest centre”. This chapter shows that the Bayes rule agrees, under one condition, and shows what changes when the condition bends. The condition is the one on slide 14: every class has covariance Σk = σ²I.
The matrix I is the identity: ones on the diagonal, zeros elsewhere. Multiply it by σ² and you get a covariance table that is σ² on the diagonal and zero everywhere else. Read it with Chapter 1: each sample has variance σ², and no two samples are linked. That is white noise, the first process in the Chapter 4 device. So the model says: the signal is a fixed shape μk plus white noise of the same strength for every class.
Start from the log score of Chapter 5. With Σ = σ²I, the inverse is I/σ². The score for class k is log πk − ||x − μk||² / (2σ²). Expand the squared distance into three pieces:
The piece xTx is the same for every class. Dropping it changes no comparison. What remains is slide 14’s discriminant hk(x) = wkTx + wk0.
This is a linear function of x: a dot product plus a constant. In code, with N samples per window and K classes, W is a K × N matrix whose rows are the wk, and b is a vector of K biases. The scores are s = W x + b, one number per class, and the answer is argmax(s). Training means estimating μk and σ². That is the whole classifier, a single layer with no hidden units.
Two classes i and j tie where hi(x) = hj(x). Subtract the two discriminants. The term μiTμi − μjTμj factors into (μi − μj)T(μi + μj). The difference becomes
Set it to zero and write w = μi − μj. The condition is wT[x − ½(μi + μj)] = −σ² log(πi/πj). We want it in the form wT(x − x0) = 0. Because wTw / ||w||² equals 1, shifting by a multiple of w does the job. Slide 15 gives the result.
Slide 16 reads the geometry off it. The boundary is a hyperplane, a flat surface one dimension lower than the space (a line in a plane, a plane in 3-D). It passes through the point x0, and it is perpendicular to w, the line joining the two centres.
When πi = πj, the log is zero and x0 is the midpoint of the two centres. The boundary is the perpendicular bisector of the segment between them. With K equally likely classes, slide 18 says the rule is the minimum distance classifier: choose k* = arg mink ||x − μk||². Your hand was right, under this one condition.
Unequal priors slide the boundary along the line between the centres, toward the rarer class. The shift is σ² log(πi/πj) / ||μi − μj||² of the gap. Noisier data (bigger σ²) or closer centres make the shift larger: when the reading says little, the prior speaks louder.
Take μ1 = (0, 0), μ2 = (4, 0), σ² = 1, π1 = 0.8 and π2 = 0.2. Then ||μ1 − μ2||² = 16 and log(0.8/0.2) = 1.386. The point x0 = (2, 0) − (1/16)(1.386)(−4, 0) = (2.35, 0). The boundary slid 0.35 toward class 2. Raise the noise to σ² = 4 and the shift becomes 4/16 × 1.386 × 4 = 1.39, so x0 = (3.39, 0). Four times the noise, four times the shift.
Three vowel-like classes with fixed centres. The colours show which class wins at each place. Dots are fresh recordings; a red ring marks a dot in the wrong region. Raise the prior of the warm class and watch its region grow into the others.
Illustrative units. Centres at (−2.2, −1.2), (2.2, −1.2) and (0, 2.4). The other two priors split what the warm prior leaves, in equal halves. Each class has 40 dots, drawn around its centre with spread σ in both directions. Regions come straight from the discriminants hk(x).
At π = 0.33 and σ = 1 the three regions are the nearest-mean cells, with straight boundaries meeting in a Y. Push the warm prior to 0.8 and the boundaries slide away from the warm centre, but they stay straight and parallel to where they were. Push σ up and the clouds overlap, so errors appear that no rule can remove: they are inside the overlap.
Symptom: boundaries cut across a stretched cloud and clip its tail. Measurement: compute the covariance of each class and compare it with σ²I. If the eigenvalues differ a lot, the clouds are ovals, not circles. Fix: allow a full shared Σ, the next chapter, or one Σk per class, Chapter 8.
Chapter 7
Measure distance in units of each cloud’s own spread, undo the stretch by whitening, and see why the best line is no longer a bisector
A two-channel sensor records a pump. The two channels pick up the same electrical noise, so when one drifts up the other tends to drift up too. Plot one dot per minute and each class forms a tilted oval, long along the diagonal and thin across it. All classes share the same oval.
A reading lands off to one side. Is it far from the class centre, or is it just out along the long axis, where dots often land? Plain distance cannot tell. A fair ruler has to be longer across the thin direction and shorter along the long one.
Slide 19 lets every class share one covariance matrix Σ, not necessarily round. Start from the same log score as before, now with Σ−1 in the distance. Expand the quadratic. Because Σ−1 is symmetric, the cross terms combine:
The first term has no k in it, so it cancels in every comparison. What remains is again hk(x) = wkTx + wk0, now with
For two classes, slide 20 gives the boundary wT(x − x0) = 0 with w = Σ−1(μi − μj) and x0 = ½(μi + μj) − log(πi/πj) / [(μi − μj)TΣ−1(μi − μj)] · (μi − μj). The derivation is Chapter 6 with Σ−1 inserted. The result is again a hyperplane through x0. Slide 21 adds the key point: it is not necessarily perpendicular to the line between the means. The vector w is the gap between the means, bent by Σ−1.
Two classes with the same tilted oval. The solid line is the Bayes boundary. The dashed line is the plain bisector. Change the tilt ρ (the correlation between the two channels) and compare how many dots each line gets wrong.
Illustrative. Centres at (−1.4, 0) and (1.4, 0), equal priors, shared covariance σ²[[1, ρ], [ρ, 1]] with σ = 1.1. Each class has 80 dots, seeded. At ρ = 0 the two lines coincide. Counts are of the dots drawn, so they vary a little from draw to draw.
At ρ = 0 the two lines are one line. As ρ grows, the oval tilts and the Bayes line leans with it, while the bisector stays upright. The leaning line clips fewer dots. The nearest-mean rule is not wrong in its own terms: it simply answers a different question, about plain distance.
Slide 23 names the fair ruler. The Mahalanobis distance from a centre μ to a point x is given by Δ² = (x − μ)TΣ−1(x − μ). To read it, split Σ into its axes. The slide writes Σ−1 = ∑i (1/λi) uiuiT, where ui are the eigenvectors of Σ (the cloud’s own axes) and λi are the eigenvalues (the variance along each axis). Then, with yi = uiT(x − μ), the slide gives Δ² = ∑i yi² / λi.
In words: project the offset onto each axis, divide by that axis’ spread, and add the squares. A step along a wide axis costs little. A step along a thin axis costs a lot.
Slide 24 shows how to turn this into plain distance. The matrix Σ−1/2 = U Λ−1/2 UT rotates onto the axes, divides each by the square root of its variance, and rotates back. (The slide writes the inverse with a shorthand; the formula in the previous sentence is the standard one.) The Mahalanobis distance is then dM(x, y) = ||Σ−1/2(x − y)||2: plain distance, after the cloud is made round.
That operation is whitening. After it, the covariance of z = Σ−1/2(x − μ) is Σ−1/2 Σ Σ−1/2 = I. This gives the chapter’s punchline. A classifier with a shared Σ does two steps: whiten every reading, then apply the round-cloud rule of Chapter 6 with the whitened centres. LDA is whiten, then nearest mean, plus the prior shift.
Take Σ = [[4, 0], [0, 1]], axes along x and y with variances 4 and 1. The points (2, 0) and (0, 2) are both at plain distance 2 from the origin. For (2, 0), Δ² = 2²/4 = 1, so Δ = 1. For (0, 2), Δ² = 2²/1 = 4, so Δ = 2. The point on the thin axis is twice as far, in honest units.
Now a tilted case, Σ = [[2, 1.2], [1.2, 2]]. Its eigenvalues are 3.2 and 0.8, with axes (1, 1)/√2 and (1, −1)/√2. The point (1, 1) lies on the long axis: Δ² = 2/3.2 = 0.63. The point (1, −1) lies on the short axis: Δ² = 2/0.8 = 2.5. Both are plain distance √2 from the origin.
A tilted cloud of 200 dots with rings at Mahalanobis distance 1 and 2. Drag the whitening slider from 0 to 1 and watch the oval round into a circle. Two probes start at the same plain distance from the centre.
Illustrative cloud with spreads 1.6 and 0.8 along the two channels and tilt ρ between them. Probe A sits two plain units out along the long axis, probe B two units out along the short axis. At whitening amount t the picture is transformed by Σ−t/2, so t = 1 is full whitening and the probe distances are the Mahalanobis distances.
At amount 0, both probes sit on a plain circle of radius 2, but the cloud says they are very different: probe A is inside the dense part and probe B is out in the sparse thin direction. At amount 1, the rings are circles, A has moved in to about 1.2 and B has moved out to about 4.5.
Symptom: whitening explodes some directions and the classifier is erratic. Measurement: look at the smallest eigenvalue of the estimated Σ; the factor 1/λ is huge when λ is near zero. This happens when you have fewer recordings than samples per window. Fix: add a small constant to the diagonal, or use fewer features. Chapter 9 returns to this.
Chapter 8
Let every class keep its own spread, derive the quadratic score, and see a tight class carve out a pocket that no straight line can
A motor has two states. Healthy, it shakes a little, in a tight ball around zero. Faulty, it shakes at random in all directions, in a much wider ball around the same zero. The two states have the same average. Only the size of the shaking differs.
Try to separate them with a straight line. Any line puts some of the tight ball on each side, and a tight ball sits in the middle of the wide one. No line works. A boundary that wraps around the centre does. That wrapping boundary is what QDA gives, and it is the one new idea of slide 25: let each class have its own covariance Σk.
Begin with the log of πk gk(x) from Chapter 5. Now Σk depends on k, so the scale factor 1/|Σk|1/2 no longer cancels. Its log gives the term −½ log|Σk|. Drop only the constant −(N/2) log 2π, which every class shares.
In Chapter 7 the first term, −½ xTΣ−1x, was the same for every class and cancelled. Now Σ−1 carries the index k, so the term stays. It is quadratic in x. Slide 25 collects the pieces as hk(x) = xTWkx + wkTx + wk0.
The class is chosen as before: classify as k when hk(x) > hk′(x) for every other k′. The decision is still an argmax. Only the shape of each score changed.
Take the motor in one dimension. Both classes have mean 0. Healthy has variance 1, faulty has variance 4 (spread 2). Priors are equal. Then W1 = −½, w1 = 0 and w10 = −½ log 1 = 0, so h1(x) = −x²/2. For faulty, W2 = −1/8 and w20 = −½ log 4 = −0.693, so h2(x) = −x²/8 − 0.693.
Set them equal. −x²/2 = −x²/8 − 0.693, so (3/8)x² = 0.693, and x² = 1.85. The boundaries are at x = ±1.36. Between them, healthy has the larger score. Outside, faulty does. Two boundaries, one pocket: no single threshold on x could do that.
Notice the role of the volume penalty. Drop the −0.693 and the scores cross only at x = 0, where both are zero. For every other x, −x²/8 beats −x²/2, so faulty would win nearly everywhere, even at x = 0.1, where a tight healthy bump is far more likely than a wide faulty one. The determinant term is what hands the middle back to the tight class.
Slides 26 and 27 show the zoo, with pictures credited to S. Aksoy. Because hk is a quadratic function, a tie between two classes is a quadratic equation in x. In two dimensions that is a conic section: an ellipse, a parabola, a hyperbola, or a pair of lines. In N dimensions these shapes are called hyperquadrics. The decision region of one class can be the inside of an ellipse, the space between two branches of a hyperbola, or a region bounded by a parabola.
Chapter 7’s LDA is the special case where all the Wk equal each other: the quadratic parts cancel in every tie and only a hyperplane is left. QDA contains LDA, and strictly more.
Class 1 is a round ball. Class 2 is a tilted oval you can stretch and move. The tint shows the QDA regions. The dashed line is the best straight line from LDA. Stretch the oval, then slide its centre onto the first ball’s centre.
Illustrative. Class 1: covariance I, centre (−gap/2, 0). Class 2: spread 1 along one axis and the stretch along the other, tilted 35 degrees, centre (+gap/2, 0). Equal priors, true parameters (no estimation), 100 dots per class. LDA uses the average of the two covariances, as a shared Σ.
With a gap of 1.4 and a stretch of 2.2, the QDA boundary is a smooth curve that hugs the round ball on the side where the oval is wide, and LDA’s straight line makes more mistakes. Slide the gap to 0 and LDA has nothing to work with: its weight vector Σ−1(μ1 − μ2) is zero, so it has no boundary at all. QDA still wraps the tight ball in a closed curve.
Symptom: a linear classifier cannot get above a ceiling on the signal even with plenty of data. Measurement: estimate the covariance of each class and compare them, for example by looking at the eigenvalues side by side. If they differ by a factor of two or more, a shared Σ is wrong. Fix: QDA. The price is more numbers to estimate, counted in Chapter 9.
Chapter 9
Estimate the means and covariances from data, read the lecture’s vowel results, and see why the more flexible classifier can lose
Everything so far assumed we were handed μk and Σk. Nobody hands them over. You have a folder of labelled recordings: forty of class 1, forty of class 2. The centres and the covariance tables must come out of those recordings. The last third of the lecture, slides 28 to 37, does this and then asks what it costs.
Slide 28 starts with one variable. Suppose n readings x1, …, xn are drawn independently from the same bell curve N(μ, σ²). Maximum likelihood says: choose the μ and σ² that make the readings you saw as probable as possible. The probability of the whole set is a product of bell curves. Take its log, as before, to get a sum: −(n/2) log σ² − ∑(xi − μ)² / (2σ²) plus a constant.
Set the slope with respect to μ to zero. The answer is the plain average. Set the slope with respect to σ² to zero. The answer is the average squared gap from that average. The slide writes both:
Try four readings: 2.1, 1.9, 3.0, 2.4. The mean is 2.35. The gaps are −0.25, −0.45, 0.65 and 0.05. Their squares are 0.0625, 0.2025, 0.4225 and 0.0025, which add to 0.69. Dividing by n = 4 gives σ²ML = 0.1725. Dividing by 3 would give 0.23.
Slides 29 and 30 do the same for N-dimensional readings. The mean is again the average, coordinate by coordinate. The covariance replaces the squared gap with an outer product: the column of gaps times its own row, which is an N × N table. Their average is ΣML = (1/n) ∑i (xi − μML)(xi − μML)T.
A tiny case: three readings (2, 1), (4, 3) and (0, 2). The mean is (2, 2). The gaps are (0, −1), (2, 1) and (−2, 0). Their outer products are [[0, 0], [0, 1]], [[4, 2], [2, 1]] and [[4, 0], [0, 0]]. They sum to [[8, 2], [2, 2]]. Divide by 3 for ΣML = [[2.67, 0.67], [0.67, 0.67]].
For a classifier, do this once per class using only that class’s recordings. The prior πk is the fraction of recordings in class k. For LDA, pool the class covariances into one shared Σ, weighted by the priors. A stationary signal offers a shortcut from Chapter 4: estimate only the N autocorrelation values and build the Toeplitz table from them. That is our addition, not the slide’s.
Slides 36 and 37 count. A covariance matrix is symmetric, so it has N(N + 1)/2 free numbers, which the slides write as C(N, 2) + N. LDA fits K means and one shared covariance: KN + C(N, 2) + N numbers. QDA fits K means and K covariances: KN + K(C(N, 2) + N). The extra K − 1 covariances are the whole price of the curve.
The last row is a 32 × 32 picture treated as one vector of 1,024 pixel values, as one example of a picture used as data, like the face pictures on slides 32 and 33 (credited to P. Smaragdis; the deck does not state their size). A picture is a point with a huge N, and the covariance table dominates the count.
Slides 34 and 35, credited to Hastie and co-authors, compare three classifiers on a vowel dataset. The table gives the error rate on the recordings used for fitting (training) and on recordings held back (test). Linear regression scores 0.48 and 0.67. LDA scores 0.32 and 0.56. QDA scores 0.01 and 0.53.
Read it as a story. QDA nearly memorizes its training recordings, with an error of 0.01, yet on new recordings it is only slightly better than LDA, 0.53 against 0.56.
Its training-to-test gap is 0.52, more than twice LDA’s gap of 0.24. In the textbook the slide cites (The Elements of Statistical Learning), this dataset has 11 vowels, 10 measurements per recording and 528 training recordings. That is 48 per vowel. QDA must then fit 11 covariance tables of 55 numbers each from 48 recordings apiece. With the 110 numbers for the means, that is 715 numbers in all.
Try the same story on a fake dataset where you control every knob.
Two classes of N-sample windows from smooth signals. Light bars are the error on the recordings the model was fitted to. Solid bars are the error on fresh recordings. The dashed line is the best any rule can do. Add dimensions, then add data.
Illustrative. Class 1 is a smooth stationary signal with covariance r[m] = 0.5|m| (a Toeplitz matrix) and mean 0. Class 2 has twice that covariance and a mean shifted by 1.5/√N in every sample. Models use the maximum likelihood formulas above, with a tiny ridge (0.001 times the average variance) added to each covariance so inversion never fails. Each result is the average of four seeded rounds, tested on 600 fresh recordings per class per round. Colours here are lesson-local: light bar is training error, solid bar is test error, LDA is purple and QDA is yellow.
At N = 10 and 20 recordings per class, QDA fits 2 × 10 + 2 × 55 = 130 numbers from 40 recordings. At the default seed its training error is about 0.01 and its test error about 0.41. LDA fits 75 numbers: about 0.25 on training and 0.44 on test. The best possible is about 0.20. Neither model is close to it, and QDA’s training score is the most misleading.
Slide the recordings up toward 200. QDA’s test error falls to about 0.21, almost the floor, while LDA stalls near 0.35, because LDA cannot bend. More data pays for more flexibility.
Symptom: the training error is tiny, and the test error is not. Measurement: always report both, as the lecture’s table does. A sample covariance from n recordings has rank at most n − 1, so when n is below N it is singular, and 1/λ blows up in the directions it never saw. Fix: pool the covariances (LDA), shrink each toward a simpler matrix, add a ridge, gather more recordings, or use fewer features. Which one wins depends on the ratio of recordings to parameters, which is why we counted.
Chapter 10
Review the numbers, the checklist and the code, then see where Gaussian classifiers sit in the field
You can now reproduce slides 1 to 37 from memory. The first half described a random signal with a mean and a covariance, and showed that stationarity ties the covariance into a Toeplitz table of N numbers. The second half used Gaussian classes to derive LDA and QDA, measured distance with Mahalanobis, and counted what each costs. A short logistics note: the slides come from the EE269 course page, and this deck was given on 30 January 2019.
A random signal is one draw from an ensemble. Its mean mx[n] and covariance Σx[k, l] describe the ensemble. If the mean is constant and the covariance depends only on k − l, the signal is wide sense stationary, the covariance is the autocorrelation r[k − l], and its table is Toeplitz: N numbers, not N². If each class is Gaussian with a prior, the Bayes rule picks the class with the largest log score. With equal round covariances σ²I the score is linear and the boundary is a hyperplane at x0, the nearest mean when priors are equal.
With a shared Σ the boundary is still a hyperplane, tilted by Σ−1, and whitening turns it back into the round case.
With class covariances Σk the score is quadratic, and the regions are hyperquadrics. You fit it all with maximum likelihood, and QDA pays K times as many covariance numbers as LDA.
| What | Value | Why it matters |
|---|---|---|
| Mean function | mx[n] = E x[n] | Average across the ensemble at one time, never along one path |
| Covariance | Σx[k, l] = E (x[k] − m[k])(x[l] − m[l])* | The link between two moments; N² entries in general |
| Wide sense stationary | constant mean; Σ[k, l] depends on k − l | The clock does not matter; N numbers suffice |
| Autocorrelation | r[k − l] = E x[k] x*[l]; r[0] ≥ |r[m]| | r[0] is the power; peaks reveal periodicity |
| Random sinusoid | r[m] = (σ²/2) cos(mω0) | Random amplitude and uniform phase vanish; only frequency stays |
| Circulant case | r[N − k] = r*[k]; ω0 = 2πj/N | The DFT diagonalizes the table |
| Equal round classes | wk = μk/σ²; x0 = ½(μi + μj) − σ²/||μi − μj||² · log(πi/πj) (μi − μj) | Straight boundary; equal priors give the nearest mean |
| Shared covariance | wk = Σ−1μk; w = Σ−1(μi − μj) | Boundary is tilted away from the bisector |
| Mahalanobis distance | Δ² = (x − μ)TΣ−1(x − μ) = ||Σ−1/2(x − μ)||² | Distance in units of the cloud’s own spread |
| QDA score | Wk = −½Σk−1; −½ log|Σk| in the bias | Curved boundaries; the volume penalty matters |
| Maximum likelihood fit | μ = (1/n) ∑ xi; Σ = (1/n) ∑ (xi − μ)(xi − μ)T | Class averages and class outer-product averages |
| Parameter counts | LDA: KN + N(N + 1)/2; QDA: KN + K N(N + 1)/2 | N = 10, K = 11: 165 versus 715 |
| Vowel error rates (training, test) | regression 0.48, 0.67; LDA 0.32, 0.56; QDA 0.01, 0.53 | QDA memorizes training data; the test gap is wide |
This sketch uses NumPy. X has shape (n_windows, N): one row per window of N samples. y has shape (n_windows,): the class label of each row. It is a sketch, so it leaves out the ridge, and you should add one before you trust the inverse.
pythonimport numpy as np def fit(X, y, shared=False): # X: (n, N), y: (n,) classes = np.unique(y) mu = {k: X[y == k].mean(0) for k in classes} # mu_k: (N,) pi = {k: np.mean(y == k) for k in classes} # prior: fraction of windows S = {} for k in classes: D = X[y == k] - mu[k] # gaps: (n_k, N) S[k] = D.T @ D / len(D) # (1/n) sum of outer products: (N, N) if shared: # LDA: pool with the priors as weights Sp = sum(pi[k] * S[k] for k in classes) S = {k: Sp for k in classes} return classes, mu, pi, S def scores(x, model): # x: (N,) -> one score per class classes, mu, pi, S = model out = [] for k in classes: d = x - mu[k] maha = d @ np.linalg.solve(S[k], d) # Mahalanobis distance squared out.append(np.log(pi[k]) - 0.5 * maha - 0.5 * np.linalg.slogdet(S[k])[1]) return np.array(out) def predict(x, model): return model[0][np.argmax(scores(x, model))] # the Bayes rule: largest score wins def toeplitz_cov(x, N): # one long recording x: (L,) -> (N, N), stationary shortcut r = np.array([np.mean(x[m:] * x[:len(x) - m]) for m in range(N)]) # r[0..N-1] return r[np.abs(np.subtract.outer(range(N), range(N)))] # copy r along each diagonal
With shared=False the sum of a quadratic form and a log determinant is QDA. With shared=True every class has the same matrix, the quadratic parts cancel when you compare classes, and you have LDA. The last function builds a Toeplitz covariance from one recording, using Chapter 4: N numbers instead of N².
The previous lesson set up the Bayes rule. This lesson filled in the Gaussian class model and read off LDA and QDA. In the field, these are the oldest practical generative classifiers, and their one-class cousins appear inside Gaussian mixture models (EM for Gaussian mixtures) and in Kalman filters. The autocorrelation idea returns in linear systems and in the adaptive filters that learn from it. The next lesson in the series is built in parallel today.
Now press Present or Teach and explain, from memory, how a stationary covariance becomes a Toeplitz table, how LDA and QDA scores are derived, and why QDA can overfit. Then go back to the pile of random sine waves, set 5,000 draws, and say why every diagonal holds one value.