EM for Mixtures of Gaussians

Spikes from two neurons arrive mixed together with no labels. Expectation-Maximization guesses the labels, refits both neurons, and repeats until the two agree.

Learn how to fit a model that has a hidden variable, why each round of guess-and-refit can only improve the fit, and how K-means falls out as the hard-edged special case.

Press Run E-step, then Run M-step, a few times. Watch the colours settle and the ovals move onto the clumps. Then we build, piece by piece, the bound that makes it work.

You need a rough idea of a probability (a number from 0 to 1 for how likely something is) and what an average is. We build the rest from zero.

Based on Lecture 17 (a virtual lecture) of Princeton NEU 560, Statistical Modeling and Analysis of Neural Data (Spring 2024), taught by Jonathan Pillow. The slides PDF is on the course site. The data, devices and numbers on this page are our own and illustrative.

Fit two hidden neurons

Illustrative data: 120 spikes drawn by our own seeded generator from two made-up neurons (spike height across, spike width up). Each spike carries a hidden label that the algorithm never sees. L is the log-likelihood, computed live.

Chapter 0

Why Labels Hide Inside Neural Data

See why a pile of unlabelled spikes cannot be sorted by a ruler, and what kind of model can sort it

Picture a thin wire pushed into a rat’s brain. Near its tip sit two neurons, and both fire. The wire cannot tell them apart. It records one voltage trace, and every time a cell fires, a brief spike shows up in it.

You cut out each spike and measure two things: how tall it is, and how wide. Now you have a cloud of points, one per spike. Some came from neuron A and some from neuron B. Nobody wrote down which. The scientific question is simple to say: which spike belongs to which neuron? This task is called spike sorting, and every later chapter serves it.

The scene matters beyond one wire. Brain-computer interfaces read the activity of many neurons and turn it into a cursor or a limb. Each neuron must be told apart from its neighbours first. If the sorting is wrong, every number built on top of it is wrong too.

Where this lesson sits in the course

This is Lecture 17 of Princeton NEU 560, Statistical Modeling and Analysis of Neural Data, taught by Jonathan Pillow in Spring 2024. The lecture was a virtual one. Its title is “EM for Mixtures of Gaussians, K-means clustering”. It opens with one practice problem: derive the ELBO for a latent variable model, starting from the log-likelihood. We answer that problem in Chapters 1 to 3. Then we run the answer as a loop, build it for clusters, and end with K-means.

That is all the logistics there are. The slides live on the course site. We explain every slide in our own words and our own devices, and we never copy the slide images.

A ruler is not enough

The obvious plan is to draw a line through the cloud. Spikes left of the line go to A. Spikes right of it go to B. The device below lets you try. Slide the cut and watch where it falls.

Cut the cloud with a line

Each dot is one spike. Grey means we do not know its neuron. Slide the cut left and right, then press Show the hidden labels to see which spikes your cut got wrong.

-1.60

Illustrative: 100 spikes from our own seeded generator, two made-up neurons that overlap on purpose. Real spikes are measured, and their true labels are not known.

Try it. No cut is perfect. In the middle the two clumps overlap, and a spike there could have come from either neuron. A ruler forces a yes or a no. Honest sorting needs a different answer: “probably A, but maybe B”.

The idea in plain words

Here is the plan. We assume each neuron makes spikes of a typical height and width, with some spread around them. A clump with a centre and a spread is a Gaussian, the familiar bell shape stretched into an oval in two dimensions. Two neurons give two ovals. The whole cloud is a mixture of Gaussians: each spike picks one oval and lands somewhere inside it.

The pick is the part we cannot see. We call it a latent variable, which just means a quantity that exists in the story but not in the data. It is like the name tag on a spike that fell off. If we knew every tag, fitting the ovals would be easy: average the spikes of A, average the spikes of B. If we knew the ovals, tagging would be easy: give each spike to the oval that explains it best. We know neither. Expectation-Maximization, or EM, solves this chicken-and-egg problem by guessing one, fixing the other, and swapping.

The hero at the top of the page runs exactly that loop. The E-step tags every spike with a soft probability. The M-step refits the ovals to those soft tags. You pressed the two buttons in turn, and the number L only went up. The rest of this lesson explains why it must.

The road

The lecture follows one line of thought, and this lesson follows it too. First comes a bound. Then a loop that climbs it. Then the loop for clusters.

  1. Hidden labels and the sum inside the log: why fitting a model with a latent variable is hard.
  2. Jensen’s inequality and the ELBO: a bound we can build, and answer the practice problem.
  3. Two useful forms of the bound: one shows the E-step, one shows the M-step.
  4. The EM loop: climb by touching and lifting the bound.
  5. Coordinate ascent: the same loop seen as walking along two axes.
  6. The mixture of Gaussians model: the generative story for spike clusters.
  7. The ELBO for the mixture: the bound written for N spikes.
  8. The E-step for the mixture: Bayes’ rule gives the responsibilities.
  9. The M-step for the mixture: weighted means and weighted covariances.
  10. The summary and K-means: the hard-edged limit.
  11. Field Guide: numbers, checklist, code and where next.
Why can a straight cut through the spike cloud not sort the two neurons perfectly?

Chapter 1

Hidden Labels and the Sum Inside the Log

Write the likelihood of a spike when its neuron is unknown, and see why that sum sits where it hurts most

You hold one spike. It is 0.4 units tall on the height axis. You believe two neurons could have made it. Neuron A makes spikes around height −1.5. Neuron B makes spikes around height 1.5. Both have the same spread, 0.8. Neuron B fires half of all spikes, and so does neuron A.

How likely is this spike under your model? The question sounds easy. The answer needs one new idea: you must add up two stories.

Two stories for one spike

Story one: neuron A fired, and it happened to make a spike of height 0.4. Story two: neuron B fired, and it made the same spike. Each story has a probability. We call it a joint probability, because it covers two things at once: the label and the spike. Write z for the label (0 for A, 1 for B) and x for the spike.

Story one has probability 0.5 times the chance that A makes a height of 0.4. That chance is 0.0298 (a Gaussian density at distance 1.9 from A’s centre). So the joint is 0.0149. Story two has probability 0.5 times 0.1938, which is 0.0969.

We saw the spike but not the story. Either story could be true. So the probability of the spike alone is the sum: 0.0149 + 0.0969 = 0.1118. The act of adding up over the hidden label is called marginalising it out. The result, p(x | θ), is the marginal likelihood of the spike. Here θ stands for all the model’s knobs: the centres, the spreads and the mixing probability.

Add up the two stories

The warm bar is the story “neuron A fired”. The purple bar is “neuron B fired”. Together they make the blue total. Slide the spike height and the mixing probability.

0.40
0.50

Illustrative: one-dimensional spike height, neuron A centred at −1.5, neuron B at 1.5, both with spread 0.8. These numbers are ours, not the lecture’s.

The slide’s first line

Now the slide makes sense. It starts from the quantity we want to make large, the log-likelihood L(θ) = log p(x | θ). Taking a logarithm of a probability turns long products into sums, and it keeps tiny numbers readable. Then it rewrites that quantity as log ∫ p(x, z | θ) dz.

L(θ)
The log-likelihood: how well the knobs θ explain the data we saw. We want the θ that makes it largest.
p(x | θ)
The probability of the observed spikes alone, with the hidden label ignored. This was 0.1118 for our spike.
∫
Add up over every value of the hidden variable. For a label with two values, the integral is simply a sum of two terms.
p(x, z | θ)
The joint probability of the spike and one particular label. The slide calls it the total-data likelihood, also named the complete-data likelihood: the likelihood if the name tag were visible.
dz
The small step in the label we add over. It matters only when the label is a continuous number.

The slide labels the middle term “total-data likelihood” and notes it is also called the complete-data log-likelihood. We use that name for the joint probability of data and label together. Keep it in mind: it is the easy quantity. If a label were visible, the joint would be a single clean product, and its log would split into tidy pieces.

Why the sum inside the log hurts

With the label hidden, the log lands outside a sum: log(0.0149 + 0.0969) = −2.192 (natural log). A logarithm does not split over a sum. The logs of the two terms are −4.209 and −2.334, and their total, −6.54, is nowhere near −2.192. The identity log(a + b) = log a + log b is false.

A real data set has N spikes, so the log-likelihood is a sum over spikes of log(ai + bi). Each ai and bi contains the centres and spreads. Set the slope with respect to a centre to zero and you get a tangle: every spike’s share depends on the very parameters you are solving for. No clean formula comes out.

Compare the case with visible labels. Then each spike contributes one term, log(ai) or log(bi), and the maths splits. Setting the slope to zero just gives the average of the spikes in that cluster. The whole difficulty is the missing tag. The next chapter builds a lower bound that brings the log inside the sum, where it behaves.

Here is a second way to feel the problem. Suppose a single wrong guess about one spike’s centre shifts both stories at once. Neuron A’s term and neuron B’s term both change, and the log must be taken of their new total. No single term can be tuned alone. With 120 spikes, that is 120 such tangles, all sharing the same few knobs. Slide the height in the device above and watch the total move with both bars at once.

Why is it hard to maximise the log-likelihood of a mixture directly?

Chapter 2

Jensen’s Inequality and the ELBO

Build a lower bound on the log-likelihood that has the log inside the sum, and use it to answer the lecture’s practice problem

You cannot lift a heavy box in one go, but you can lift a light box that sits under it. If the light box stays below the heavy one and touches it at one spot, then lifting the light box as high as it goes cannot push you past the heavy one. You also know the heavy one is at least that high.

That is the whole strategy of this lecture. The log-likelihood L is the heavy box. We cannot maximise it directly, because of the sum inside the log. So we build a lighter function F that always sits below L, touches it at a chosen spot, and has no sum inside the log. Raising F raises a floor under L.

The practice problem

The lecture’s second slide sets one exercise: derive the ELBO for a latent variable model with prior P(z | θ) and conditional P(x | z, θ), starting from the log-likelihood. A prior is the probability of the hidden label before you see any spike. A conditional is the probability of a spike given the label. Multiply them and you get the joint of the last chapter. Try the derivation yourself. The next section does it in four moves.

Jensen’s inequality, first as a picture

Take the curve y = log(u). It bends downward. A curve that bends this way is concave. Pick two points on it and join them with a straight chord. The chord lies below the curve in between.

Now pick weights. Say you take 0.5 of a point u1 and 0.5 of a point u2. The average of the two inputs, (u1 + u2)/2, lands on the horizontal axis. Take the log of that average and you are on the curve. Take the log of each input and average the two answers, and you are on the chord. The chord is lower. This is Jensen’s inequality for the log: the log of an average is at least the average of the logs.

For our spike the two inputs are 0.0149 and 0.0969, once we have chosen weights. The trick on the slide is that we are free to choose the weights, and a clever choice makes the bound touch.

The four moves

  1. Start. L(θ) = log ∫ p(x, z | θ) dz.
  2. Multiply and divide by q. Pick any distribution q(z | φ) over the label, with its own knobs φ. Then p(x, z | θ) = q(z | φ) × p(x, z | θ) / q(z | φ). Nothing changed. Now the integral is an average over q of the ratio p/q.
  3. Apply Jensen. The log of an average over q is at least the average over q of the log. The log has moved inside.
  4. Name the result. The right-hand side is the ELBO, short for evidence lower bound. The lecture writes it F(φ, θ) and also calls it the negative free energy.
L(θ)
The log-likelihood, the heavy box. It does not depend on q at all.
∫ q(z | φ)
An average over the hidden label, using weights q that we choose. The lecture calls q the variational distribution: our guess for how the label is spread.
p(x, z | θ) / q(z | φ)
The joint probability divided by our weight for that label. This is the ratio we average.
F(φ, θ)
The ELBO. It depends on our guess φ for the labels and on the model knobs θ. It never exceeds L.

Look at what changed. The log now sits directly on the joint p(x, z), a single clean term for each label. The sum over labels has moved outside. That is the form we can differentiate.

The bound touches at one weight

For our spike, the label has two values, so q is one number: q, the weight on B. The ELBO is F(q) = q log(b / q) + (1 − q) log(a / (1 − q)), where a = 0.0149 and b = 0.0969. Slide q below and watch F.

Slide the weight q

The blue line is the log-likelihood L of the spike, fixed. The pink curve is the bound F as you change q. Slide q, or press the button to jump to the best weight.

0.50

Illustrative: the two joint terms are those of the spike at height 0.4 in Chapter 1 (a = 0.0149, b = 0.0969). Natural logarithms throughout.

At q = 0.5 the bound is −2.579, and L is −2.192, a gap of 0.387. Move q and the pink curve rises to a single peak at q = 0.867, where it equals L. That peak weight is not an accident: 0.867 is b / (a + b), the probability that neuron B made the spike, once you have seen it. The next chapter shows why. Weights that match the true story close the gap.

What the bound promises

Two facts make EM work. First, F never exceeds L, for any q and any θ. Second, for each θ there is a q that makes F equal to L. So pushing F upward can never overshoot L, and choosing q well makes F as high as L can be. A chain of such moves climbs L itself.

What does Jensen’s inequality give us here?

Chapter 3

Two Useful Forms of the Bound

Rewrite the ELBO two ways and see that one shows how to pick q while the other shows how to pick θ

A recipe card can list the same dish two ways. One list is ordered by what you buy at the shop. Another is ordered by when you add each item to the pan. The dish is the same. The order tells you which job you are doing.

The ELBO has the same property. The lecture writes it in two forms. The first form tells you how to choose the guess q. The second tells you how to choose the model knobs θ. Together they are the two halves of EM.

Form one: the log-likelihood minus a gap

Start from the definition of F. The joint can be split in the other order: first the spike, then the label given the spike. That is p(x, z | θ) = p(x | θ) × p(z | x, θ). The second factor, p(z | x, θ), is the posterior over the label: how likely each neuron is once you have seen the spike. We used it in Chapter 2 when q came to 0.867.

Put that split inside F. The factor p(x | θ) does not depend on z, so it comes out of the integral as log p(x | θ). What stays behind is the average over q of log of p(z | x, θ) over q(z | φ). That average is a famous quantity with a minus sign.

F(φ, θ)
The bound from Chapter 2.
log p(x | θ)
The log-likelihood L. It does not depend on q, which is why the bound can never pass it by more than the gap.
KL( q ‖ p )
The Kullback-Leibler divergence: a number that measures how far the guess q is from the true posterior. It is never negative, and it is zero only when the two match. Our information theory lesson builds it from zero.

The lecture marks this as the E-step form. Since the gap is never negative, F is at most L. That is a second proof of the bound, with no Jensen needed. And F equals L exactly when the gap is zero, which means q equals the posterior. So the best guess for the label is the posterior, and the lecture’s E-step sets q(z | φ) = p(z | x, θ).

Check it on our spike with q = 0.5. The posterior says B with 0.867 and A with 0.133. The gap is 0.5 × log(0.5/0.867) + 0.5 × log(0.5/0.133) = 0.387. That is the same 0.387 we measured in Chapter 2 between F and L.

Form two: expected joint plus entropy

Now split the log differently. The log of a ratio is a difference of logs: log p(x, z | θ) minus log q(z | φ). So F is the sum of two averages over q. The first average is the expected value of the joint’s log. The second, with its minus sign, is the entropy of q, written H[q]. Entropy measures how spread out a distribution is. A q that puts all its weight on one label has entropy zero. A q that splits evenly has the highest entropy.

F(φ, θ)
The same bound again.
∫ q log p(x, z | θ)
The expected complete-data log-likelihood: the log of the joint, averaged over our guess for the labels. The slide labels it “expected total-data log-likelihood”.
H[ q ]
The entropy of q. It does not contain θ at all.

This is the M-step form. Only the first term holds θ. The entropy is a constant while we change θ. So to raise F by moving θ, we raise the expected joint and ignore the rest. The lecture’s M-step says: update θ by maximising ∫ q(z | φ) log p(x, z | θ) dz. Our entropy lesson covers H.

Check the same spike at q = 0.5. The expected joint is 0.5 × log(0.0969) + 0.5 × log(0.0149) = −3.272. The entropy of an even split is log 2 = 0.693. The sum is −2.579, the same F again, up to rounding.

One bound, two bookkeepings

Choose a form, then slide q. In the first form F sits a gap below L. In the second form two bars add up to F.

0.50

Illustrative: the spike of Chapter 1 again (a = 0.0149, b = 0.0969). Both forms give the same F, computed live two different ways.

Why the split matters

Each form answers one question. Which q makes the bound tightest for a fixed θ? Form one says: the posterior, because it zeroes the gap. Which θ makes the bound highest for a fixed q? Form two says: the one that maximises the expected joint. Neither question needs the sum inside the log. Each is a clean problem on its own.

In which form of F can you see that the best q is the posterior p(z | x, θ)?

Chapter 4

The EM Loop: Touch the Bound, Then Lift It

Alternate the two forms to climb the log-likelihood, and see why each round can never make it worse

You stand on a foggy hillside and want the top. You cannot see far. But you carry a small folding stool shaped like a bowl turned upside down. You set it down so it touches the hill exactly where you stand, and so it stays below the hill everywhere else. You can see the whole top of the stool. You walk to its peak.

The ground beneath that peak is at least as high as the stool there. And the stool’s peak is higher than where you began, because the stool touched the hill at your feet. So you have climbed. Fold the stool, set a new one down where you now stand, and repeat. This is EM.

The two steps, in the lecture’s words

The stool is the bound F from the last two chapters. The lecture writes the loop in two lines, one per form.

  1. E-step: update φ. Set q(z | φk) = p(z | x, θk−1). This is form one: it zeroes the gap, so the bound touches L at the current θ.
  2. M-step: update θ. Set θk to the θ that maximises ∫ q(z | φk) log p(x, z | θ) dz. This is form two: it climbs the bound with q held fixed.

The letter E stands for expectation, because the first step computes the expected label for each spike. The letter M stands for maximisation, because the second step maximises. The lecture then shows the loop on a picture: a bumpy blue curve L over θ, an initial guess θ0, a red bound curve touching L there, a jump to the red peak at θ1, a new bound, and so on until the red curve touches L at the peak, called θML for maximum likelihood.

Set the stool, walk to its top

The blue curve is the log-likelihood L as one centre μ moves. The pink curve is the bound. Choose a start, then press Run E-step and Run M-step in turn.

Illustrative: 12 made-up spike heights, neuron A fixed at −2 with spread 0.8, mixing probability fixed at 0.5, and only neuron B’s centre μ free. The E-step and M-step are the real formulas of Chapters 8 and 9, run live.

Worked example, number by number

Start the toy at μ = −0.5. There L is −53.16. The E-step computes a posterior for each of the 12 spikes: how much it looks like neuron B at that centre. The M-step moves μ to the weighted average of the spikes, using those posteriors as weights.

Round one lands at μ = 1.382, and L jumps to −24.70. Round two gives 1.911 and −23.10. Round three gives 1.946 and −23.095. After that the centre barely moves. The steps shrink, because the bound and the curve have nearly the same slope at the top. The device lets you check each of these numbers.

Why it can never go down

The proof is three short facts in a row. Write θold for where you stand before a round and θnew for where the M-step lands.

  1. After the E-step the bound touches: L(θold) = F(φ, θold).
  2. The M-step maximises F over θ, so F(φ, θnew) ≥ F(φ, θold).
  3. The bound is always below L: F(φ, θnew) ≤ L(θnew).

Chain them: L(θold) ≤ L(θnew). The log-likelihood never falls. The hero showed this: the number L only rose.

Where the loop stops, and what that means

The loop stops when the stool’s peak is the point you stand on. There the bound and the curve touch and have the same slope, so L has a flat spot: a peak. The lecture calls this alternation, repeated until convergence, the route to θML.

One honest warning. EM guarantees the log-likelihood never falls. It does not promise the highest peak. If L has several bumps, the start decides which one you reach. Our toy has a single peak, so every start in the device ends at the same place. Real data often have more. The standard fix is to run EM from several random starts and keep the best.

Two practical notes close the loop. First, you need a first guess for θ. Any guess works for the proof, since the log-likelihood rises from wherever you start. A poor guess costs extra rounds, not correctness. Second, you need a rule to stop. A common choice is to stop when L gains less than a small number, such as 0.001, in one round. In the hero, the far-off guess starts at L = −914.5 and one round already lifts it to −364.9. The first rounds give the biggest gains, and later rounds polish.

After an E-step, the bound touches the log-likelihood at the current θ. Why does the next M-step then guarantee the likelihood does not fall?

Chapter 5

Coordinate Ascent on the Free Energy

See EM as a walk that moves along one knob at a time, and learn why strongly linked knobs make it zigzag

Picture a city laid out as a grid of streets. You want to reach the highest point in town, a hill park. You have one rule: you may walk only along a street, either due north or due east, never diagonally. You pick one direction, walk to the highest spot on that street, then switch direction and do the same.

If the hill is a round dome, two or three turns bring you to the top. If the hill is a long ridge that runs diagonally across the grid, you spend your day taking many short steps back and forth. This picture is the lecture’s “alternative view” of EM.

Two sets of knobs, one landscape

The bound F(φ, θ) has two kinds of knobs. The φ knobs describe our guess q for the labels. The θ knobs are the model itself: centres, spreads, mixing probability. Each pair of settings gives one value of F. So F is a landscape over two axes, and we want its peak.

The lecture draws that landscape as contour lines, like a topographic map: θ runs across, φ runs up, and the nested ovals mark equal heights of F. The EM steps become moves on this map.

The lecture steps through six slides of this. Start at θ0 on the bottom axis. A vertical red line rises to φ1. A horizontal red line goes to θ1. Then up again to φ2, across to θ2, and each pair of moves lands closer to the centre of the ovals. This kind of method is called coordinate ascent: improve one coordinate at a time, in turn. Each move can only raise F, because each move picks the best value along its line, and staying put is always one of the choices.

The curve where the bound touches

The last slide of the series adds a blue curve. It is the set of points where F touches L, the log-likelihood. By form one of Chapter 3, F equals L exactly when φ is the posterior for the current θ. For every θ there is one such φ. Plot them all and you get a one-dimensional curve through the map, which the slide labels “1D manifold where free energy and log-likelihood touch”.

Every vertical E-step ends on that curve. Along it, F and L have the same height, so the height of the curve at each θ is just L. The highest point of the curve is θML, the answer we want. EM zigzags toward it.

Walk the grid streets

The ovals are equal-height lines of a stand-in bowl for F. The blue line is where the bound touches L. Press Move φ (the E-step), then Move θ (the M-step). Then tilt the bowl.

0.80

Illustrative: a bowl F = −(u² − 2ρuv + v²) / (2(1 − ρ²)), where u and v measure θ and φ from the peak and ρ is the link. Real EM has many knobs, so this is a two-knob picture. The best φ for a given θ is v = ρu, and the best θ for a given φ is u = ρv.

Why strong links mean slow progress

Set the slider to 0. The ovals are circles. The E-step lands straight on the blue line and the M-step on the peak: two moves, done. Now slide the link up to 0.95. The ovals stretch into a long diagonal ridge. Each move still goes to the best point on its street, but the best point on a street is barely closer to the top of a long ridge.

The numbers show the pattern. Once you are on the first street, each full sweep (one E-step and one M-step) multiplies your distance from the peak by ρ². With ρ = 0.8 that factor is 0.64, so ten more sweeps shrink the distance to about 1.2% of what it was. With ρ = 0.95 the factor is 0.9025, so ten more sweeps still leave about 36%. The read-out gives the exact figure for your move count.

In EM terms, a strong link means the best labels depend heavily on the model, and the best model depends heavily on the labels. Each step corrects only a little of the other. This is why EM can crawl near the end, even though every step is guaranteed to help. It is also why practitioners often stop when the gain per round falls below a small threshold.

A word about what this picture leaves out. Real EM has many knobs, not two. The φ side alone has one weight per spike, and the θ side has the 11 numbers of the model. So the map is a slice through a very high-dimensional landscape. The two-knob version keeps the one idea that carries over: each move picks the best value along one set of knobs and can never go downhill.

In the lecture’s contour picture, what is an E-step?

Chapter 6

The Mixture of Gaussians Model

Tell the story of how spikes are made, with a hidden coin flip and two ovals, and name every number in it

A probability model is a recipe for making data. Imagine a machine that makes fake spikes. It does two things for every spike. First it flips a weighted coin to choose which neuron fires. Then it reaches into that neuron’s bag and pulls out a height and a width. Run the machine many times and you get a cloud that looks like real data.

Fitting a model means working this recipe backwards. You see the cloud, and you ask which settings of the machine would have made it. First, though, you must write the recipe down exactly.

The recipe in two lines

The lecture calls the coin flip the latent variable z. It takes the value 1 with probability p, and the value 0 with probability 1 − p. The number p is the mixture probability: the share of spikes that belong to cluster 1.

Given z, the spike x is a pair of numbers (height, width). It is drawn from a Gaussian. If z is 1, the Gaussian has mean μ1 and covariance C1. If z is 0, it has mean μ0 and covariance C0. A mean is the centre of the clump. A covariance is a small table of three numbers that says how wide the clump is in each direction and how tilted: it draws the oval.

p(z)
The prior over the hidden label: the coin. The slide calls z the cluster identity.
p(x | z)
The spike given its label. The slide marks x as a data point in n-dimensional space. For us, n is 2.
N(x; μ, C)
A Gaussian density: the bell shape in n dimensions, centred at μ with shape C.

The slide gathers all the knobs into one box and calls it θ. It holds the mixture probability p, the two means, and the two covariances. In our two-dimensional spike space that is 1 + 2 × 2 + 2 × 3 = 11 numbers. Fitting the model means finding those 11 numbers.

The data flow

The next picture in the lecture shows the same story as a cartoon. Two clusters sit on top, with a down arrow to a scatter of crosses below. The label z is on top, the data x below, and the arrow runs from z to x. The arrow is the machine: label in, spike out.

The slide after it removes the colours, so the crosses are all alike, and puts a question mark on the arrow running back up. That is our problem. The dataset is {xi} for i = 1 to N, a table with N rows and 2 columns. There is also a hidden column zi of N zeros and ones that we never see.

The goal, in the lecture’s own words, is to find the maximum likelihood estimate: the θ that maximises log p({xi} | θ). This is the same L from Chapter 1, now for N spikes at once. Since the spikes are independent draws, the likelihood of the table is a product over spikes, and its log is a sum of N per-spike terms. Each term is the log of the two-story sum from Chapter 1.

Run the spike machine

Draw spikes from the model. Each dot looks grey, as real data would. Press Show the hidden labels to see which neuron made each one. Change the separation or the coin and the cloud restarts.

0.50
0.80

Illustrative: our own generator with two fixed ovals, neuron A with covariance [0.6, 0.35; 0.35, 0.5] and neuron B with [0.5, −0.3; −0.3, 0.6]. The separation slider scales how far apart the centres sit.

Play with it. When the separation is large, the two ovals barely touch, and the hidden labels are almost visible from the grey cloud alone. When it is small, the clumps merge, and the grey cloud looks like a single oval. Then no method can recover the labels well. The model is only as useful as the data allow.

Why this story is a good one

Two reasons. First, each step of the recipe is simple: a coin and a Gaussian. Second, if the labels were known, fitting would be trivial. Each clump’s mean and covariance would be the average and spread of its own spikes, and p would be the fraction labelled 1. The hard part is only that the labels are hidden. EM supplies guesses for them, as Chapters 8 and 9 show. Our site’s EM and Gaussian mixture lesson teaches the same model from another angle.

How many numbers does θ hold for two clusters of two-dimensional spikes with a full covariance each?

Chapter 7

The ELBO for a Mixture, Spike by Spike

Write the bound for N spikes and see that every spike gets its own pair of weights, stored in a table with N rows and 2 columns

A teacher marks a stack of N exams. Each exam is marked on its own, and the class total is the sum. The class average does not hide the fact that every paper got its own number. The ELBO for a data set works the same way: one small bound per spike, added up.

The lecture’s slide 21 does this in three lines. We take them one at a time and then watch the table they produce.

From the general bound to our model

The first line is the general form from Chapter 2: ELBO = ∫ q(z | φ) log [ p(x, z | θ) / q(z | φ) ] dz. The second line applies it to our model. The log-likelihood of the whole data set is the sum over spikes of log p(xi | θ), because the spikes are independent draws. Each term is bounded below by that spike’s own ELBO. Add the bounds and you have a lower bound on the whole sum.

The third line expands one spike’s bound. The label zi has only two values, so the integral over z becomes a sum of two terms:

ELBO(xi | θ)
The bound for spike number i alone.
∑ over zi
Add the two stories for this spike: neuron 0 fired, neuron 1 fired.
q(zi | φi)
Our weight on each story for spike i. Each spike has its own φi. These are the responsibilities: how much each cluster is responsible for the spike.
p(xi, zi | θ) / q
The joint probability of the spike and the story, divided by our weight. For story 1 the joint is p × N(xi; μ1, C1). For story 0 it is (1 − p) × N(xi; μ0, C0).

The last lines of the slide write the two terms out in full. The lecture names the weights φi0 = q(zi = 0 | φi) and φi1 = q(zi = 1 | φi). They are two numbers between 0 and 1 that add to 1. The total bound is the sum over i of φi0 log [ p(xi, zi = 0 | θ) / φi0 ] + φi1 log [ p(xi, zi = 1 | θ) / φi1 ].

The table of responsibilities

Slide 22 draws the knobs φ as a matrix with N rows and 2 columns. Row i holds (φi0, φi1). Every row sums to 1. For our 120 spikes, that is 240 numbers, though only 120 are free, because the second in each row is one minus the first. These are the E-step’s outputs, and they are what the hero colours the dots with.

Now we choose θ to be the true setting of the machine and look at six spikes. Pick three ways of filling the table and see how the bound responds.

Fill the table, read the bound

Each row is one spike. The two columns are the weights on neuron A and neuron B. Choose how to fill the table, and watch the last row, the total bound.

Illustrative: six spikes from our seeded generator, with the model set to the true values (p = 0.5, centres at (−1.5, −0.5) and (1.5, 0.5), the two covariances of Chapter 6). The log-likelihood L of these six spikes is computed with the same code.

The posterior row gives the highest total, and its total equals L to three digits: −16.972. The even split is far lower, at −51.468. The hard pick is close, at −17.058, because these six spikes sit far from the overlap and a hard pick is nearly right for them. It is still lower. A spike in the overlap would cost more, since a hard pick puts all its weight on one story even when the other is almost as likely. That is the same lesson as Chapter 2, now for a table.

The bound also shows where the E-step’s work goes. Each row of the table needs the two joint terms for its spike: two Gaussian densities and a product with p or 1 − p. That is a fixed amount of arithmetic per spike, so a pass over N spikes costs N times that amount. The table has no memory between rows. A spike’s weights depend only on its own position and on θ, never on the other spikes’ weights.

How big is the table of responsibilities for 120 spikes and 2 clusters, and what must each row do?

Chapter 8

The E-step: Responsibilities from Bayes’ Rule

Turn the rule “set q to the posterior” into one short formula, and compute it for every spike in a single pass

A spike lands at height 0.4, in the gap between two neurons. A friend asks, “Which neuron fired it?” You do not say “B”. You say, “Probably B, about 87 percent.” You reached that number by comparing how well each neuron explains the spike, with a nudge for how often each fires. That comparison is the whole E-step.

In Chapter 3 we learned the rule: the best q is the posterior, p(z | x, θ). Now we make it concrete for the mixture.

Bayes’ rule, in words first

Bayes’ rule turns a forward story into a backward answer. The forward story says: given the neuron, here is how likely this spike is. The backward question asks: given the spike, how likely is each neuron? The rule says that the backward answer is proportional to the forward story times the prior. Then you divide by the total so the answers add up to 1.

The slide writes it for spike i and story 0 or 1. The numerators are the two joint terms from Chapter 1. The denominator is their sum, the marginal likelihood we met there.

φi1
The responsibility of cluster 1 for spike i: the new weight, the answer. The partner φi0 = 1 − φi1 is the same with (1 − p) N0 on top.
p N1(xi)
The joint of the spike and the story “B fired”. N1 is short for the Gaussian density with mean μ1 and covariance C1, read at xi.
(1 − p) N0 + p N1
Both stories added: the marginal likelihood of the spike. Dividing by it makes the two weights add to 1.

Run our spike through it. The joint for A is 0.0149 and for B is 0.0969. The sum is 0.1118. So φi1 = 0.0969 / 0.1118 = 0.867, and φi0 = 0.133. The same 0.867 that made the bound touch in Chapter 2.

Ask who fired the spike

Top: each neuron’s weighted density, warm for A and purple for B. The vertical line is your spike. Bottom: the responsibility of B at every height. Slide the spike, then the coin and the separation.

0.40
0.50
1.5

Illustrative: one-dimensional spike height; neuron A centred at minus the separation, neuron B at plus the separation, both with spread 0.8. The default settings are the spike of Chapter 1.

Why the S-shape

The bottom curve is an S. Far left, neuron A explains everything, so φi1 is near 0. Far right it is near 1. In the middle it passes through 0.5 where the two weighted densities cross. Move the coin p up and the S slides left, because B now gets a head start. Move the separation up and the S becomes steeper, because the neurons are easier to tell apart.

The S has a name: the logistic curve. The formula can be rewritten as 1 / (1 + exp(−g)), where g is the log of the ratio of the two joints. Chapter 10 uses this form to reach K-means.

The data flow and the one trap

For the full data set the shapes are simple. In: the N × 2 table of spikes, and θ (the 11 numbers). Out: the N × 2 table φ from Chapter 7, with each row adding to 1. The loop over spikes has no coupling between rows, so a computer can handle all N at once. That is the meaning of the lecture’s “for all i”.

Here is the trap. Take a spike 40 standard widths from both ovals, perhaps from a glitch in the recording. Each Gaussian density there is about e−800, smaller than the smallest number a 64-bit computer can store, which is near e−745. Both densities become exactly 0. The formula gives 0 / 0, which is not a number, and one bad spike poisons the whole table. The fix is to work with logs. Subtract the larger log joint from both, then exponentiate. This is the log-sum-exp trick, and it is what our eStep code does: it computes a logistic of the log-ratio and never divides two zeros.

It helps to check the formula at the extremes. If p is near 1, neuron B almost always fires, so even a spike that sits nearer A gets a large weight on B. If p is near 0, the reverse holds. If the two densities are equal at the spike, the density terms cancel and φi1 is exactly p. These checks make a good habit: before you trust a number, ask what it should be in a case you can do in your head.

A spike is equally well explained by both neurons, and the coin says B fires 80% of the time. Roughly what does the E-step give for φi1?

Chapter 9

The M-step: Weighted Means and Weighted Covariances

Maximise the expected joint with the weights fixed, and see that the answer is an ordinary average, weighted by responsibility

A town votes on where to put a new bus stop. Everyone votes, but a few residents are away and gave only half a vote each. To find the best spot, you do not ignore them, and you do not count them fully. You take a weighted average of the addresses, with weight 0.5 for them and 1 for the rest.

The M-step is that weighted average. The weights are the responsibilities from the E-step. This chapter shows where that comes from, and why it needs no search at all.

The target

From Chapter 3, the M-step maximises the expected joint, the first term in form two. Slide 24 expands it for our model, and every line is one small move. Start with the sum over spikes of φi0 log p(xi, zi = 0 | θ) + φi1 log p(xi, zi = 1 | θ). Split each joint into prior times Gaussian. Then the logs turn the products into sums.

The result has three separate pieces, each holding only some of the knobs:

  1. Cluster 0: the sum over spikes of φi0 log N(xi; μ0, C0). It holds only μ0 and C0.
  2. Cluster 1: the sum of φi1 log N(xi; μ1, C1). It holds only μ1 and C1.
  3. The coin: the sum of φi0 log(1 − p) + φi1 log p. It holds only p.

Because the pieces share no knobs, we maximise each on its own. The slide ends in three arrows pointing at three answers. The other slide terms in the lecture, the entropy and the constants, do not hold θ, so they drop out.

Where each answer comes from

For the mean, set the slope of piece 1 to zero. The slope of φi1 log N(xi; μ1, C1) with respect to μ1 is φi1 C1−1 (xi − μ1). Add over spikes, set to zero, and multiply both sides by C1. What is left is Σ φi1 (xi − μ1) = 0. Solve for μ1 and you get the weighted average. The covariance works the same way, with φi1 weighting each spike’s squared distance from the new mean.

For the coin, set the slope of Σ (φi0 log(1 − p) + φi1 log p) to zero. That gives Σ φi1 / p = Σ φi0 / (1 − p). Solve it and p is the average of φi1 over all N spikes, because each pair of weights adds to 1.

μ̂1
The new centre of cluster 1: every spike’s position, weighted by its responsibility, divided by the total weight. Cluster 0 uses φi0 instead.
Ĉ1
The new covariance: the weighted average of each spike’s squared offset from the new centre. It sets the size and tilt of the oval.
p̂
The new mixing probability: the average responsibility of cluster 1. Half the total weight on B means p̂ = 0.5.

This is why EM is fast per round. No search is needed. Each M-step is one pass over the spikes, adding up weighted sums. And if the weights were 0 and 1, the formulas would give plain averages of each group, exactly what we would do with known labels.

Average with weights

Same 120 spikes, four sets of weights. The crosses and ovals show what the M-step produces from each. Dot colour shows the weights you fed in.

Illustrative data from our seeded generator. The M-step is the code you will see in the Field Guide, with a ridge of 0.001 added to each covariance diagonal.

Try the even split first. Every spike counts half for each cluster, so both clusters get the same centre, the centre of the whole cloud, and the same oval. The M-step has learned nothing about two clumps because the weights said nothing. The first real E-step breaks the tie, and each round after sharpens it.

When it goes wrong: a cluster that collapses

Symptom: the log-likelihood shoots up and an oval shrinks to a dot. Cause: a cluster whose weight lands on a single spike. Its covariance becomes zero, and a Gaussian with zero spread gives infinite density at that one point. Measurement: watch the smallest spread of each oval, and the total weight Σ φi1. Fix: add a small ridge to the diagonal of every covariance, as our code does, or restart that cluster elsewhere.

A spike has φi1 = 0.25. How does it enter the new centre of cluster 1?

Chapter 10

The Summary, and K-means as the Hard Limit

Gather the whole algorithm into one box, then shrink the ovals to points and watch soft labels harden into K-means

Before the last idea, here is the whole algorithm on one card, as the lecture’s summary slide has it. There are the knobs θ: the mixture probability p, the two means, the two covariances. Then two steps, repeated.

  1. E-step, compute recognition probabilities. For all i, set φi0 = (1 − p) N0(xi) / [ (1 − p) N0(xi) + p N1(xi) ], and φi1 likewise with p N1 on top.
  2. M-step, compute weighted means, covariances and the average p(z = 1). Set each mean to the φ-weighted average of the spikes, each covariance to the φ-weighted spread, and p to the average of φi1.

The lecture calls the weights the recognition distribution: the model’s way of recognising which story made each spike. That is all of EM for a mixture of Gaussians. The code in the Field Guide is these two steps in about 25 lines.

The soft version and the hard version

The responsibilities so far are soft: a spike can be 87% neuron B and 13% neuron A. The lecture’s final slide asks what happens if we insist on hard labels: each spike belongs to one cluster, fully, or the other.

The answer is a famous algorithm. K-means clustering repeats two steps. Give each spike to the nearest cluster centre. Then move each centre to the average of the spikes it won. The lecture’s slide states the link in one line: K-means is EM for the mixture-of-Gaussians model assuming “infinitesimal covariance”. That means both covariances equal ε times the identity, C0 = C1 = ε I, in the limit as ε shrinks to 0. Every oval becomes a perfect circle of the same size, and then the circles shrink.

Following the algebra

Put C = ε I into the E-step. Both Gaussians have the same size, so the constants cancel. Only the distances between the spike and each centre remain. The slide shows the result:

p(z = 1 | x)
The responsibility of cluster 1 for the spike x, the E-step output.
(1 − p) / p
The prior odds against cluster 1. It matters little once ε is small.
1 / 2ε
A sharpness knob. As ε shrinks, this number grows without limit.
‖x − μ1‖² − ‖x − μ0‖²
The squared distance to centre 1 minus the squared distance to centre 0. It is negative when centre 1 is nearer.

Now read the formula. If centre 1 is nearer, the distance difference is negative, the exponent goes to minus infinity as ε shrinks, and the whole expression tends to 1. If centre 0 is nearer, the exponent goes to plus infinity and the expression tends to 0. So the weight is 1 or 0: the lecture writes it as a two-line rule and says, in red, hard assignment to clusters based on Euclidean distance. With hard weights, the M-step’s weighted average becomes the plain average of the spikes in each cluster. That is exactly K-means.

Shrink the ovals to points

Both clusters are circles of size ε, with fixed centres and p = 0.5. Dot colour is the responsibility. Slide ε down and watch the blurry middle vanish.

2.00

Illustrative: our 120 seeded spikes, centres fixed at (−1.5, −0.5) and (1.5, 0.5). The circle drawn is two standard deviations wide. K-means gives every spike a hard label, so it always has 0 uncertain spikes.

Two details are worth seeing in the device. First, with p = 0.5 the hard label (above or below 0.5) never changes as ε moves. It always matches the nearest centre. Only the confidence changes. Second, the count of uncertain spikes falls toward 0 as the circles shrink, and K-means is the end of that road.

Soft or hard, which should you use?

K-means is simpler and a little faster. It cannot say “maybe”, and it assumes round clusters of equal size. EM with full covariances can follow tilted, stretched clumps and can report doubt. On our seeded spikes, with the clumps well apart, the two give nearly the same answer: K-means labels 116 of 120 spikes with the true neuron and EM labels 115. The gap between methods grows when the clumps are tilted, differ in size, or overlap, but there is no clear winner on every data set. The practical rule: use EM when you want uncertainty or a model you can sample from, and K-means when you want a fast first look.

What happens to the E-step weights of a mixture as both covariances shrink to ε I with ε going to 0?

Chapter 11

Field Guide

Keep the numbers, the checklist and the core code, and find where the same loop appears next

Here is the lesson in one paragraph. A model with a hidden label has a log-likelihood with a sum inside the log. Jensen’s inequality gives a bound, the ELBO, with the log inside. Written one way, the bound shows that the best guess for the labels is the posterior (the E-step). Written another way, it shows that the best model for fixed labels maximises an expected joint (the M-step). Alternating the two never lowers the likelihood. For a mixture of Gaussians the E-step is Bayes’ rule and the M-step is a weighted average. Shrink the ovals to points and you have K-means.

The numbers to keep

QuantityValueWhere
Joint for A, joint for B, total, for the spike at height 0.40.0149, 0.0969, 0.1118Chapter 1
Log of the total, and the sum of the two logs−2.192 against −6.54Chapter 1
Bound at q = 0.5, and the best weight−2.579 (gap 0.387), best q = 0.867Chapters 2 and 3
One-knob toy: μ and L over three rounds from −0.5−0.5 to 1.382 to 1.911 to 1.946; L −53.16 to −24.70 to −23.10 to −23.095Chapter 4
Numbers in θ for two 2-D clusters11 (1 + 4 + 6)Chapter 6
Responsibility table for 120 spikes120 × 2, each row adds to 1Chapter 7
Bound for six spikes: posterior, hard pick, even split−16.972, −17.058, −51.468 (L = −16.972)Chapter 7
Hero data: L at the centred guess, after one round, at the end−406.0, −366.2, −328.65Hero
Hero data: L at the far-off guess, then after one round−914.5, −364.9Hero
Correct labels on the hero data, K-means and EM116 and 115 of 120Chapter 10

All numbers come from our own toy data and seeded generator, so they are illustrative. The lecture itself gives formulas, not numbers.

The terms to keep

TermMeaning
Latent variable zThe hidden label of each spike. It exists in the model, not in the data.
Log-likelihood L(θ)How well the knobs explain the data, with the label summed out.
ELBO or free energy F(φ, θ)A lower bound on L, built with Jensen’s inequality.
Recognition distribution qOur guess for the labels, with one weight pair per spike.
E-stepSet q to the posterior. The bound touches L.
M-stepMaximise the expected joint over θ. Weighted means, covariances and the average p.
K-meansEM for equal round covariances in the limit of zero size: hard labels, nearest centre.

The checklist

The core as code

The whole algorithm for two clusters of 2-D spikes, with the shapes in the comments. The hero ran a JavaScript version of exactly these two steps.

pythonimport numpy as np

def log_gauss(X, mu, C):                      # X (N, 2), mu (2,), C (2, 2)
    d = X - mu
    _, logdet = np.linalg.slogdet(C)
    q = np.einsum('ni,ij,nj->n', d, np.linalg.inv(C), d)
    return -0.5 * (q + logdet + X.shape[1] * np.log(2 * np.pi))   # (N,)

def e_step(X, p, mu, C):                      # mu (2, 2), C (2, 2, 2)
    a = np.log(1 - p) + log_gauss(X, mu[0], C[0])   # (N,) story: A fired
    b = np.log(p) + log_gauss(X, mu[1], C[1])       # (N,) story: B fired
    total = np.logaddexp(a, b)                 # (N,) log p(x_i | theta), no underflow
    return np.exp(b - total), total.sum()        # phi_i1 (N,), and L

def m_step(X, phi1, ridge=1e-3):
    phi = np.stack([1 - phi1, phi1], axis=1)  # (N, 2) responsibilities
    n = phi.sum(axis=0)                          # (2,) total weight per cluster
    mu = (phi.T @ X) / n[:, None]               # (2, 2) weighted means
    C = np.empty((2, 2, 2))
    for k in range(2):
        d = X - mu[k]
        C[k] = (phi[:, k, None] * d).T @ d / n[k] + ridge * np.eye(2)   # weighted covariance
    return n[1] / len(X), mu, C                # new p, means, covariances

def em(X, p, mu, C, rounds=40):
    for _ in range(rounds):
        phi1, L = e_step(X, p, mu, C)           # L never falls from round to round
        p, mu, C = m_step(X, phi1)
    return p, mu, C

Where this loop shows up next

The pattern of guess, refit and repeat is much wider than clusters. The same bound trains hidden Markov models, where the E-step is the forward-backward pass (see our HMM lesson). It fits linear dynamical systems, where the E-step is a smoother (see the Kalman filter and RTS smoothing). It also fits factor models closely related to PCA. Many of these need expectations that have no closed form, and then sampling steps such as Monte Carlo and importance sampling stand in for the E-step. For the other half of this course’s toolkit, see the lessons on generalized linear models and PCA in NEU 560. For a second look at the same model, read EM for Gaussian mixtures.

The takeaway. When labels are hidden, do not fight the sum inside the log. Build a bound that touches it, lift the bound, and repeat. For clusters, the lift is a weighted average, and the loop never makes the fit worse.

Credit and sources

This lesson follows Lecture 17 of Princeton NEU 560, Statistical Modeling and Analysis of Neural Data (Spring 2024), taught by Jonathan Pillow. The lecture’s own slides are on the course site. The explanations, devices, data and numbers here are our own, and every toy number is labelled illustrative.

Now press Present or Teach and explain one round out loud, from memory: why the sum sits in the log, how Jensen’s inequality builds the bound, what the E-step and M-step each change, and why shrinking the ovals gives K-means. Then go back to the hero and run it with new eyes.

NEU 560 Lecture 17: EM for Mixtures of Gaussians
The course site · Lecture slides · Back to Gleams