Sort the spikes of two hidden neurons without being told which is which. Expectation maximization guesses the labels, refits the model, and repeats. Each round can only raise the likelihood.
Learn how to fit a model when part of the story is hidden: the mixture of Gaussians, the guess called the E-step, the refit called the M-step, and why the loop always climbs.
Press E-step to colour each spike by how likely it came from each neuron. Press M-step to move the ellipses to fit those colours. Alternate a few times, or press Run EM. Then we build every piece from zero: the hidden label, the guess, the log of a sum that blocks a direct fit, and the bound that EM climbs.
You need a rough idea of a probability (a number from 0 to 1 for how likely something is) and the bell curve (the Gaussian). We build the rest from zero.
Based on Lecture 16 of Princeton NEU 560: Statistical Modeling and Analysis of Neural Data (Spring 2024), taught by Jonathan Pillow. Lecture slides. Every idea is re-taught here in our own words and devices; none of the course’s images are used.
Toy data, labelled illustrative: 140 made-up spikes from two made-up neurons, each spike described by two waveform features (for example peak height and trough depth), seeded so they are the same on every visit. The E-step and M-step are the exact mixture-of-Gaussians updates the lecture ends on (Chapter 8), with full covariance matrices, computed live in your browser.
Chapter 0
See why fitting a model is easy when you know each spike’s neuron and hard when you do not
Picture a thin wire pushed into the cortex of a monkey. It sits close to two neurons. Each time either neuron fires, the wire records a spike: a blip of voltage that lasts about one millisecond.
The wire does not say who fired. But two neurons near one wire make spikes of slightly different shape. One spike is taller. Another is wider. So you boil each spike down to two numbers, its features: say the peak height and the trough depth. Now every spike is one dot on a flat plot.
Hold 140 such dots in your mind. They fall into two loose clouds. Your job is to find the clouds and to say which neuron made each dot. Neuroscientists call this spike sorting, and our spike sorting lesson builds the whole pipeline around it. This lecture teaches the algorithm at its heart.
Suppose a helper had written the neuron’s name beside each dot. Then the job is plain bookkeeping. Take all the dots labelled A. Their average is the centre of cloud A. How far they scatter around that centre says how wide the cloud is. The share of dots labelled A says how often neuron A fires compared with B.
That is a complete model, and it is only a few numbers. For two clouds in two features, it is 11 numbers. There is one mixing share, since the other share follows. There are two means, with two coordinates each. There are two covariance matrices, with three numbers each. A covariance matrix is a table that records how wide a cloud is in each direction and how the two features lean together.
In real data nobody wrote the labels. A quantity that the model needs but nobody measured is called a latent variable. “Latent” means hidden. Here it is the neuron’s identity for each spike, and the lecture names it z.
Now you are stuck in a loop. To find the clouds, you need the labels. To find the labels, you need the clouds. Each one needs the other first. Expectation maximization, or EM, breaks the loop with a simple trick. Guess the clouds. Use the guess to label the dots softly. Use the labels to refit the clouds. Repeat until nothing changes.
Try the problem in one dimension first. The device below shows only the peak height. The grey bars count spikes. When the neurons differ a lot, the bars make two clear humps, and you can almost label the spikes by eye. Shrink the gap and watch the humps merge.
200 spikes, binned by peak height. Drag the gap between the two neurons’ typical heights. Then press Reveal the hidden label to colour each spike by its true neuron.
Illustrative: 200 made-up spikes, 40% from neuron A and 60% from neuron B, each with a spread of 1 unit around its own typical height. The label of every spike stays the same as you drag; only the gap moves. The hump count is measured on the exact smooth curve, not on the bars.
With a wide gap, the label is almost visible in the data. With a small gap, the two neurons hide inside one hump. A person can no longer see where one ends and the other begins. A good algorithm must still do well, because it can use the shape of the whole crowd, not only the gaps between humps. That is what EM does.
The first slides carry housekeeping. There is no in-person class on Thursday, April 4. There is no quiz on Tuesday, April 9. The one-paragraph project idea is now due on Monday, April 8. Then the lecture opens on its real subject, EM for mixtures of Gaussians.
The lecture moves in four steps. It writes down the model that makes the data (Chapter 1). It runs that model backwards to guess the labels (Chapter 2). It shows why fitting the parameters directly is hard (Chapter 3). Then it derives EM and shows two pictures of why it works (Chapters 4 to 7), and ends with the mixture of Gaussians in action (Chapter 8). The method is more general than spike sorting. The same loop fits hidden Markov models (see the HMM lesson) and many latent-variable models of neural populations (see latent variable models).
Chapter 1
Build the model that makes the data: pick a hidden label, then draw a point from that label’s bell curve
You are about to write the program that makes the spikes. Not the program that sorts them: the one that makes them. It sounds backwards. But the lecture’s whole plan rests on it. If you know how the data came to be, you can reason about the parts you cannot see.
Take the electrode again. Each spike comes from neuron A or neuron B. Say A fires 40% of the time and B fires 60% of the time. To make one spike, flip a weighted coin. It lands on A with probability 0.4. That outcome is the hidden label.
Now ask the chosen neuron for its spike. Each neuron has a typical shape and a typical wobble around it. In two features, that wobble is a round or tilted cloud. The standard model for such a cloud is the Gaussian: the bell curve, here in two dimensions. A Gaussian has a centre, its mean, and a width and tilt, its covariance. Draw one point from the chosen neuron’s Gaussian. That point is the spike.
A mixture of Gaussians is exactly that two-step recipe. The lecture draws it as two rows. The top row holds the latent z, the cluster identity. The bottom row holds the data x, the dots in n-dimensional space. An arrow runs from z down to x, and the lecture labels it sampling.
The lecture gathers every number the recipe needs into one bundle called θ (theta), the parameters: the mixing probability p, the two means μ1 and μ0, and the two covariances C1 and C0. It uses the label z = 1 for the first cluster and z = 0 for the second. Here z = 1 is neuron A and z = 0 is neuron B.
The recipe then has two probability rules. The first is the coin. The second is the bell curve, chosen by the coin. The lecture writes them as small case tables.
Multiply the two to get the chance of seeing both a label and a dot: p(x, z) = p(z) p(x | z). This is called the joint probability. Here is a number. Take the neuron-A cloud with covariance C1 = [0.25, 0.12; 0.12, 0.30], whose determinant is 0.0606. At its own centre the Gaussian has height 1 / (2π × √0.0606) = 0.646. Multiply by the coin’s 0.4 and the joint at that centre is 0.259.
The data alone, without the label, follow the marginal: add the joint over both labels, p(x) = p(x, z = 1) + p(x, z = 0). The word marginal just means “sum out the thing you did not observe”. Chapter 3 shows why that sum causes trouble. For now, play the recipe forwards.
The bar on top is the coin. Drag it to change how often neuron A is chosen, then press Draw 1 spike or Draw 20. Turn on Hide the labels to see what the electrode sees.
Toy model, illustrative numbers: neuron A has mean (1.2, 0.9) and neuron B has mean (−1.0, −0.7), each with a tilted covariance. The coin and the Gaussians are real random draws in your browser. The ellipses mark two standard deviations of each bell curve.
Notice what the recipe gives you for free. Every dot comes with a true label, in the data the machine makes. In real recordings, only the dots survive. The label is thrown away at the moment the neuron fires. EM has to win it back.
Written as code, the recipe is two lines. The data X is a table of N rows and 2 columns, one row per spike. The labels z are a list of N zeros and ones. The model fills z first with N coin flips. Then, row by row, it fills X from the Gaussian that the flip chose.
pythonz = rng.random(N) < p # shape (N,): True means neuron A X = np.where(z[:, None], rng.multivariate_normal(mu1, C1, N), # shape (N, 2) rng.multivariate_normal(mu0, C0, N)) # shape (N, 2) # keep X, throw z away: that is what an electrode gives you
A failure shows up early. With few spikes, the share of A can stray far from p. Draw five spikes with p = 0.4 and three from A is quite normal. The typical error of a share measured over n draws is √(p (1 − p) / n). At n = 20 that is √(0.24 / 20) = 0.11, or eleven points of share. At n = 140 it falls to 0.04. So a model fitted on a few spikes gives a loose estimate of p, and more data is the only fix.
Chapter 2
Turn a measured point into the probability that each neuron fired it, using Bayes’ rule
A single spike lands on your screen at peak height 2.0. Which neuron fired it? You cannot know for sure. But you can say how likely each neuron was. Maybe 66% for A and 34% for B. That pair of numbers is the best answer the data can give, and this chapter shows how to compute it.
The lecture titles this step how to do inference (recognition)? It adds a condition in brackets: assuming we know θ. This is a big assumption, and Chapter 3 will take it away. For now, suppose someone handed you the means, the covariances and the mixing share. How would you label a dot?
Recall the recipe from Chapter 1. It runs from the label z to the data x. Now run it the other way. The data x is in your hands, and you want z. The lecture calls this inference, or recognition: going from what you see to the hidden cause. The answer is a probability for each label, the recognition distribution p(z | x).
The rule that turns the recipe around is Bayes’ rule. Think of two shops that sell the same spike. Shop A is small: it makes 30% of all spikes. Shop B is big: it makes 70%. A spike of height 2.0 arrives. Which shop made it? Two things matter. How big is each shop? And how likely is each shop to make a spike of exactly this height?
Multiply the two. Shop A: 0.3 times the height of its bell curve at 2.0. Shop B: 0.7 times the height of its bell curve at 2.0. Each product is a score for one label. The share of the total score that A holds is the probability that A made the spike. The lecture writes the same thing in symbols.
Here is the lecture’s formula with real numbers. Let neuron A have mean 3 and neuron B mean 0, each with spread 1. Let p = 0.3. At x = 2.0 the A curve has height N1(2) = 0.2420 and the B curve has height N0(2) = 0.0540. A’s score is 0.3 × 0.2420 = 0.0726. B’s score is 0.7 × 0.0540 = 0.0378. Their total is 0.1104. So p(z = 1 | x = 2) = 0.0726 / 0.1104 = 0.658. The spike is a bit closer to A, yet A is rare, so the answer is only 66%, not 90%.
The lecture states the second probability too: p(z = 0 | x) = (1 − p) N0(x) divided by the same total. The two add to 1, as they must. Every spike gets its own pair.
Top: each neuron’s weighted bell curve. The yellow line is your spike. Bottom: the chance that A made a spike at each height. Drag the spike, then change how common A is.
Illustrative: neuron A has mean 3 and neuron B mean 0, both with spread 1, so the numbers match the worked example above. The curves are the exact formula from the lecture, computed live. The tipping point is where the two scores are equal.
Slide the spike toward the middle and the answer fades toward 50%. Slide it far right and A takes nearly everything. Now drop p to 0.05. At x = 2 the answer falls to 19%, because A is now so rare that even a spike near its centre is more likely to be a stray from B. The prior, p, pulls the tipping point toward the rarer neuron. With p = 0.3 the tipping point sits at 1.78, to the right of the midpoint 1.5.
For the whole recording, inference takes the N × 2 table of spikes and the parameters θ, and returns an N × 2 table of probabilities. Each row is one spike. Each column is one neuron. Each row adds to 1. These soft labels are what Chapter 8 calls responsibilities: how responsible each neuron is for each spike.
A failure hides in this tidy table. If the bell curves are narrow compared with the gap between them, the answer flips from nearly 0 to nearly 1 over a tiny stretch of x. With a gap of 3 and spread 1, the answer climbs from 5% to 95% over about 2 units of height. With a spread of 0.5, it does so over only about 0.5. A wrong guess for the means then produces confident wrong labels. That is why the later chapters keep soft labels, not hard ones: a soft label can be wrong gently.
Chapter 3
Find the log of a sum inside the likelihood, and see why it makes a bumpy surface with false peaks
You now have a model and a way to label spikes once its parameters are known. The real job is the reverse: find the parameters. Say you have 40 spike heights from one electrode. You want the two means, the two spreads and the mixing share. What do you do?
Here is the standard answer. Pick the parameters that make the data you saw as probable as possible. The probability of the data, read as a function of the parameters, is the likelihood. The best parameters are the maximum likelihood estimate, written θML in the lecture. You try a value of θ, ask “how probable would my 40 spikes be under this?”, and keep the value that scores highest.
Spikes are drawn independently, so their probabilities multiply. A long product of small numbers is awkward, and a computer would round it to zero (the product falls below the smallest number a computer can store, and it rounds to zero, which is called underflow). So we take a logarithm, which turns a product into a sum. The log is steady: the best θ for the likelihood is also the best θ for the log-likelihood. We call it L(θ).
Suppose each spike came with its label z. Then the probability of one spike with its label is the joint p(x, z) from Chapter 1. The lecture calls the probability P(X, Z | θ) of the spikes together with their labels the total-data likelihood. It contains the labels, so it is a statement about both what you saw and what was hidden.
The log of this total-data likelihood is easy. Each spike adds one term: the log of its coin chance plus the log of its bell curve. A bell curve’s log is a simple curved bowl. Setting the slope to zero gives the answer by hand: the mean is the average of that neuron’s spikes, the covariance is their scatter, and the share is their count over N. You met this at the top of the lesson.
Now remove the labels. The lecture shows the chain. The probability of the data is the sum over every possible labelling Z of P(X | Z, θ) P(Z | θ), which is the sum of the total-data likelihood over Z. Because spikes are independent, that sum splits spike by spike. Taking the log gives the line that matters.
Work three spikes by hand, with neuron A at mean 3, neuron B at mean 0, spread 1 and p = 0.3. At x = 1 the scores are 0.0162 and 0.1694, so p(x) = 0.1856 and its log is −1.684. At x = 2 they are 0.0726 and 0.0378, so p(x) = 0.1104 and the log is −2.204. At x = 4 they are 0.0726 and 0.0001, so p(x) = 0.0727 and the log is −2.622. The total is L = −6.51. Every score shows up inside a sum, then the log is taken of that sum.
With known labels, the log hits a single bell curve and the algebra stays tidy. With hidden labels, the log hits a sum of two bell curves. The log of a sum does not split into a sum of logs. So the slope no longer separates into one clean equation for each parameter. Every parameter ends up inside every term, and setting the slope to zero has no closed-form answer.
The lecture notes that you could, in theory, climb L(θ) by gradient ascent: compute the slope, step uphill, repeat. That works, but it is fussy. The covariances must stay valid, the share must stay between 0 and 1, and you must tune the step size. A deeper problem is the shape of the surface, which the device shows next.
The blue curve is the log-likelihood of 40 spikes as you slide the mean of neuron A. Pick a view, then drag the mean. Try the two labels known views: each is one smooth bowl.
Illustrative toy data: 40 made-up spike heights in three loose groups (near 1, near 2.8 and near 4.6). Neuron B is parked on the middle group (mean 2.8) with spread 0.45 and A uses the same spread with p = 0.45; only A’s mean moves. Every value is the exact log-likelihood, computed live. The “labels known” views fix each spike’s label by hand: spikes below 1.8 (left) or above 3.8 (right) go to A, the rest to B.
Drag the mean across the range with hidden labels. The curve has two peaks. The tall one near 0.84 puts neuron A on the left group and scores L = −133.1. The short one near 4.5 puts A on the right group and scores L = −178.0. Between them lies a valley. A method that only climbs uphill will stop at whichever peak is nearest. That false peak is a local maximum: a place where every direction goes down, though a higher peak exists elsewhere.
Now switch to the labels-known views. Each is one smooth bowl whose top sits exactly at the average of the labelled spikes: 0.83 on the left and 4.52 on the right. The bumpy blue curve is the best of many such bowls, one for each way of labelling the spikes. Hidden labels turn a simple bowl problem into a pile of overlapping bowls.
In code, the loss is a single line, and the log sits outside the sum. Real code uses a stable log-sum-exp so tiny scores do not round to zero.
pythondef loglik(X, p, mu1, mu0, C1, C0): # X has shape (N, 2) a = p * mvn.pdf(X, mu1, C1) # shape (N,): neuron A's score per spike b = (1 - p) * mvn.pdf(X, mu0, C0) # shape (N,): neuron B's score per spike return np.log(a + b).sum() # log of a SUM, then add over spikes
The failure has a clear symptom. Run a climbing method twice from different starts and get two different answers. The measurement is the score each one reaches. Start the mean at 0.2 and you land on the peak at −133.1. Start it at 5.5 and you land on the peak at −178.0. The second run scores 45 log-units worse, which is a likelihood smaller by a factor of about 3 × 1019. The fix is not a smarter climb. It is to run from several starts and keep the best score, which Chapter 8 does.
Chapter 4
Swap the log of a sum for a sum of logs, and measure the gap you pay for the swap
Chapter 3 left us with a log that sits outside a sum, and that single fact blocks a clean answer. Here is the lecture’s way out. Do not attack the hard curve head on. Build an easy curve that always sits below it and touches it where you stand. Then climb the easy curve. The tool for building it is a short fact about the logarithm.
The slides announce this step plainly: EM is an iterative procedure for finding the maximum likelihood estimate, and the derivation was done on the board in three parts. Jensen’s inequality. The evidence lower bound. Two useful forms of it. This chapter covers the first two. Chapter 5 covers the third.
Draw the curve of the natural logarithm, log(u). It rises, but ever more slowly. A curve that bends down like this is called concave. Pick two heights on it, u1 and u2, and draw the straight line between the two points on the curve. That line is a chord. Because the curve bends down, the chord always lies below the curve between its ends.
Now give each height a weight: weight w for u1 and 1 − w for u2. The weighted average of the heights is ū = w u1 + (1 − w) u2. Two things can be read off the picture. The height of the curve above ū is the log of the average. The height of the chord above ū is the average of the logs. Chord below curve means the average of the logs is smaller. That is Jensen’s inequality for the log.
Try numbers. Let u1 = 1 and u2 = 4, with equal weights. The average is 2.5, and log(2.5) = 0.916. The logs are 0 and 1.386, and their average is 0.693. The gap is 0.223, and it is positive, as Jensen promises. Play with the device below to feel how the gap grows and shrinks.
Two heights sit on the log curve, joined by a chord. Blue marks the log of the average. Purple marks the average of the logs. Drag the two heights and the weight. Or press Use the Chapter 2 spike.
Exact arithmetic with natural logarithms. The Chapter 2 spike is x = 2 with p = 0.3, A at mean 3, B at mean 0 and spread 1: its two scores 0.0726 and 0.0378, each divided by 0.5, give heights 0.1452 and 0.0756. The axes rescale to fit the points.
Three things stand out. Make the heights equal and the gap closes to zero. Push the weight to 0 or 1 and the gap also closes, because one point has all the weight. Spread the heights far apart and the gap widens. The gap is the price of swapping the order of “average” and “log”.
Back to the hard curve. We want to bound log p(x | θ), and that is a log of a sum over labels z. Five small moves turn it into a lower bound. Each move is one action.
Check it on one spike with numbers. Take the Chapter 2 spike at x = 2 and choose q = (0.5, 0.5) for the two labels. The heights are u(A) = 0.0726 / 0.5 = 0.1452 and u(B) = 0.0378 / 0.5 = 0.0756. Their average under q is 0.1104, which is the true marginal p(x), so log p(x) = −2.204. The average of their logs is 0.5 × (−1.930) + 0.5 × (−2.582) = −2.256. So F = −2.256 sits below the log-likelihood −2.204, by 0.052.
Look at what changed. The log used to sit outside a sum. Now it sits inside, next to the total-data likelihood p(x, z | θ), and the sum over labels sits outside, weighted by q. That is a sum of logs of easy bowls, so a maximum over θ will have a clean answer, which Chapter 5 shows. Each term of the new bound is easy, and the bound never rises above the true curve.
A failure waits here. The bound holds for every choice of q, including silly ones. With q = (0.1, 0.9) the bound for our spike is −2.885, far below the truth. A loose bound is a poor guide to the real curve, and climbing it may not help. The symptom is a big gap between F and log p(x). The measurement is that gap. The fix is to choose q to shrink the gap, and the next chapter finds the exact best q.
Chapter 5
Read the same bound two ways, and watch each way hand you one step of the algorithm
The bound F has two knobs. One is φ, the choice of q. The other is θ, the parameters of the model. The lecture’s plan is to turn one knob at a time. For that to work, each knob needs a clear job. The trick is to rewrite F in two different ways. Each way makes one knob easy to set. Both are on the lecture’s “quick recap” slide, and both come from rearranging the same expression.
Two small ideas show up in the rewrites. The first is entropy, written H[q]. It measures how spread out a distribution is. If q puts all its weight on one label, H is 0. If q splits evenly between two labels, H is as large as it can be, 0.693 (the natural log of 2). Entropy depends only on q.
The second is the KL divergence, KL(q || r). It measures how different q is from another distribution r. Picture two weighted coins. KL adds up, label by label, how surprised you are on average if the truth follows q but you believed r. It is never negative. It is exactly zero only when q and r are the same. It is not symmetric, so the order matters.
Start from F = ∑z q(z) log [ p(x, z | θ) / q(z) ]. The joint splits as p(x, z | θ) = p(z | x, θ) p(x | θ). This is Chapter 2’s recognition distribution times the evidence. Put that in, pull out the evidence term, and one piece stays: the average of log [ p(z | x, θ) / q(z) ], which is minus a KL.
This form answers the first knob. To make the bound as tight as possible with θ held fixed, make the gap zero. The gap is zero when q equals the recognition distribution. So the E-step is: set q(z | φ) = p(z | x, θ). That is exactly Chapter 2. The letter E stands for expectation, because the soft labels are the expected value of each label given the data.
One spike at x = 2. The purple curve is the bound F for every possible q. The blue line is the true log-likelihood. Drag q, or press E-step to set q to the recognition distribution.
Illustrative single spike, the same model as Chapter 2: x = 2, p = 0.3, A at mean 3, B at mean 0, spread 1. The scores are 0.0726 for A and 0.0378 for B. Both forms of F are computed live from these numbers and agree to the digit shown.
Slide q about. The purple curve rises to a single top, and that top lies exactly on the blue line, at q = 0.658. That is the recognition distribution from Chapter 2, so the gap shrinks to 0. Anywhere else the bound sits below the line. At q = 0.5 the gap is 0.052. At q = 0.10 it grows to 0.682. A poor q wastes most of the bound.
Now split the log differently: log [ p(x, z | θ) / q(z) ] = log p(x, z | θ) − log q(z). Averaging the first piece under q gives the expected total-data log-likelihood. Averaging the second gives minus the entropy of q, so adding it back gives +H[q].
This answers the second knob. To raise F with q held fixed, only the first term matters. Maximise it over θ. This is the M-step: θnew = arg maxθ ∫ q(z | φ) log p(x, z | θ) dz. The M stands for maximisation. The log now sits next to the bowl from Chapter 3, so the answer has a closed form: weighted averages.
See both forms agree on the device’s spike at q = 0.5. Form 1: log p(x) − KL = −2.204 − 0.052 = −2.256. Form 2: the average total-data log-likelihood is 0.5 × log 0.0726 + 0.5 × log 0.0378 = −2.949, and H[q] = 0.693, so the sum is −2.256. Two roads, one number.
Take three one-dimensional spikes at x = 1, 2 and 4, with the same starting model as before. The E-step gives neuron A the shares 0.0873, 0.6576 and 0.9987. In the M-step, each spike counts toward A’s mean by the share A owns of it. A’s new mean is the weighted average (0.0873 × 1 + 0.6576 × 2 + 0.9987 × 4) / (0.0873 + 0.6576 + 0.9987) = 5.397 / 1.7436 = 3.10. A’s new share is the total weight over the spike count: 1.7436 / 3 = 0.581. In code, with R of shape (N, 2):
pythonNk = R.sum(axis=0) # shape (2,): soft spike count per neuron mu = (R.T @ X) / Nk[:, None] # shape (2, 2): weighted means pi = Nk / len(X) # shape (2,): new mixing shares
A failure is easy to commit. Suppose you change θ and then reuse the old q. The old q no longer equals the recognition distribution for the new θ, so the gap is open again, and the bound sits below the curve. The symptom is a log-likelihood that rises more slowly than it should. The measurement is the KL between your stale q and the fresh recognition distribution. The fix is to redo the E-step after every M-step.
Chapter 6
Run the E-step and M-step on a real curve and watch the bound touch, lift and land
Now put the two steps to work. Picture yourself on the bumpy blue curve from Chapter 3, in fog. You can feel the ground under your feet, but you cannot see the peaks. EM gives you a trick. At your feet, it builds a smooth purple hill that never rises above the blue ground and that touches the ground exactly where you stand. You walk to the top of the purple hill. Then you do it again.
The lecture draws this over six slides, and the plot is the same each time. The horizontal axis is the parameter θ. The vertical axis is the log-likelihood. The blue curve is L(θ), the true log-likelihood. The red curve is the bound F(φ, θ). Here is each beat in order.
In the lecture’s notation, round k does two things. The E-step sets q(z | φk) = p(z | x, θk−1). The M-step sets θk = arg maxθ ∫ q(z | φk) log p(x, z | θ) dz. The loop “alternates until convergence”, with the E and M boxes joined by a curved arrow.
Try it on the 40 spikes from Chapter 3. Press E-step and see the purple bound appear, touching the blue curve under your marker. Press M-step and see the marker hop to the bound’s top. Press them again, or use Run EM.
Pick a starting guess. Then alternate E-step (draw the purple bound) and M-step (hop to its top). Grey bounds are earlier rounds.
The same illustrative 40 spikes and model as Chapter 3: neuron B parked at mean 2.8, spread 0.45, p = 0.45, and only A’s mean moves. The bound is the exact F with q fixed at the recognition distribution, and each hop goes to its exact top (a weighted average of the spikes). No numbers are drawn by hand.
Start on the left, at 0.2. The log-likelihood there is −146.83. The E-step builds a bound that touches at exactly −146.83. The M-step hops to 0.827, the top of that bound, where the bound reads −133.48. The true curve at 0.827 reads −133.10, a little higher. One round lifted the score by 13.7. A second round lands at 0.838 and stays. The loop has converged on the tall peak.
A simple chain of three comparisons proves it. Say you stand at θk−1 with a fresh E-step done. The bound touches the true curve here, so F(φk, θk−1) = L(θk−1). The M-step then picks the top of the bound, so F(φk, θk) is at least that. The bound lies under the true curve everywhere, so L(θk) is at least the bound’s height there.
Put the three together: L(θk−1) = F(φk, θk−1) ≤ F(φk, θk) ≤ L(θk). On our numbers: −146.83 ≤ −133.48 ≤ −133.10. The log-likelihood never goes down in a round. This guarantee is the reason EM has no step size to tune. A gradient method can overshoot and lose ground. An EM round cannot.
EM stops when the hop has length zero. That happens when the top of the bound sits right under the marker. At the touch point the bound and the true curve also share the same slope. So the top of the bound is a place where the true slope is zero too. EM halts at a stationary point of L: a peak, and occasionally a saddle.
Now the failure. Press Start right (5.5) and run EM. The marker hops to 4.62, then 4.52, then settles at 4.50 with L = −177.98. That is the short, false peak from Chapter 3. The symptom: a converged fit that looks reasonable but sits 45 log-units below the best one. The measurement: compare final L across starts. The start in the middle (3.6) falls to the same false peak. The fix: several starts, keep the best, which is what Chapter 8 does with three neurons.
Chapter 7
See EM as coordinate ascent: one move up, one move across, until the top
Chapter 6 showed EM along one slice: the bound as a function of θ with q frozen. The lecture then zooms out and shows a second picture, on six slides headed alternative view: coordinate ascent of free energy. Here you see both knobs at once. The picture explains why EM is steady, and why it is sometimes slow.
Think of F(φ, θ) as a hill. Every point on a flat map is a pair of choices: θ across (the model’s parameters) and φ up (the choice of q). The height at each point is F. The lecture draws the hill as contour lines, like a walker’s map: each closed loop joins points of equal height, and the loops shrink toward the summit.
Climbing a hill when you can only move in two directions is an old problem. The simplest plan is coordinate ascent: move along one axis until you cannot go higher, then switch to the other axis, then switch back. Each move is a straight line. The result is a staircase, which the lecture draws in red.
EM is coordinate ascent on F. The two steps map onto the two axes.
The lecture adds one more line on the last slide. A blue curve winds through the hills and is labelled 1D manifold where free energy and log-likelihood touch. This is the set of points that the E-step reaches: for each θ, the φ that makes the gap zero. Along that curve, F equals the true log-likelihood. The top of the whole hill sits on this curve, at θML.
To see the arithmetic, take a simple hill. Let the height be F = −½ [ u² − 2ρ u v + v² ], where u is how far θ sits from the summit and v is how far φ sits from it. The number ρ sets how tilted the loops are. For ρ = 0 the loops are circles. For ρ near 1 they are long thin ovals along the diagonal.
The best v for a given u is v = ρ u. That is the vertical move, the E-step. The best u for a given v is u = ρ v. That is the horizontal move, the M-step. After one round u becomes ρ² u. With ρ = 0.8 each round keeps 64% of the distance. Starting at u = −2, the sequence is −2, −1.28, −0.82, −0.52, and so on. After 9 rounds the distance falls below 0.05.
Pick how narrow the hill is. Press E-step to move up to the blue curve, and M-step to move across. Or press Run and count the rounds.
Illustrative: this hill is a made-up two-variable bowl, chosen only to show the staircase shape; it is not the free energy of any spike data. The horizontal axis is θ and the vertical axis is φ, as in the lecture. Each step goes to the exact best value along its line. A round counts as done when θ is within 0.05 of the summit.
On the round hill (ρ = 0.5) each round keeps only 25% of the distance, and you are done in 3 rounds. On the tilted hill (ρ = 0.8) you need 9. On the narrow ridge (ρ = 0.95) each round keeps 90.25%, and you need 36 rounds. The steps get smaller and smaller as the loops get thinner, because each straight move can only go along one axis, and the ridge runs diagonally.
Chapter 6 held q fixed and moved along θ. This chapter moves one coordinate at a time. Both describe the same loop. The monotone climb of Chapter 6 shows up here as a staircase that never steps downward: each move goes to the top along its line, and the top along a line is never below where you were.
This picture also explains a slow start you may have seen in the hero. Press Both near the middle at the top of this lesson and run EM. The log-likelihood creeps along near −360 for about ten rounds before it escapes. The two ellipses start on top of each other, so the loops of the hill are narrow and tilted along the diagonal, and the staircase takes tiny steps.
The data flow stays the same as before. One E-step maps (X, θ) to the N × K table of shares. One M-step maps (X, shares) to the new θ. The free energy is the bookkeeping number: it equals L after every E-step, and it rises after every M-step. You can print it each round as a sanity check. If it ever falls, there is a bug.
The failure is the slow ridge. The symptom: log-likelihood rises by smaller and smaller amounts, and the fit looks done long before it is. The measurement: the change per round shrinks by a fixed ratio, here ρ². The fixes are to wait longer, to start from a better guess (for example, centres picked from the data, as Chapter 8 does), or to hand the last stretch to a gradient method. Do not stop at a fixed small number of rounds without looking at the change.
Chapter 8
Write the exact updates, run them on three neurons, and break the fit with a bad start
The lecture ends on a picture of EM at work. Three panels show the same spikes after iteration 2, iteration 5 and iteration 50. In the first, two big circles overlap in the middle and the labels are smeared. By iteration 5, the circles have pulled apart. By iteration 50, the clusters are clean. Each letter is drawn larger when the model is more sure of it: the label size shows the probability of assignment to a cluster. The figure is credited to Dayan and Abbott. We build our own version, with three neurons.
Chapters 2 and 5 gave the two steps in general terms. For a mixture of Gaussians with K neurons, each step is a short recipe. Neuron k has a share πk, a mean μk and a covariance Ck. The lecture’s slides show the E-step formula for two clusters. The M-step results below are what you get by maximising ∫ q log p(x, z | θ) dz, as Chapter 5 set out. The slides show them in pictures. This is the standard closed form.
Why is the mean a weighted average? Start from the M-step: maximise ∑i rik log N(xi | μ, C) over μ. The slope of each log Gaussian term is C−1(xi − μ). Set the weighted sum of the slopes to zero: ∑i rik (xi − μ) = 0. Solve for μ and you get the weighted average. If every share were 0 or 1, this is the plain average of Chapter 0’s labelled data. Soft shares give the soft version.
Now run it on a harder case. The device holds 150 spikes from three neurons, 50 each, with their features drawn from three clouds. We fit three ellipses. Each start picks three spikes at random as the first centres. Scrub the iteration slider or press Play. Watch the soft colours settle. Then try all four starts.
Each start picks three random spikes as first centres. Spikes take the colour of the neuron that owns them. Press Play, or drag the iteration. Compare where the four starts end up.
Illustrative toy data: 150 made-up spikes from three made-up neurons (50 each), the same on every visit. The four starts are fixed random draws of three spikes, with first covariances of 0.5. The fit is the exact EM of this chapter with full covariances and a tiny floor of 0.0001 added to each variance; each log-likelihood is computed live over 60 iterations.
Start 1 finds the three clouds cleanly and ends at a log-likelihood of −248.8. Start 2 ends at −269.2, Start 3 at −271.9, and Start 4 at −284.3. Open Start 4 and look at the ellipses. One ellipse wraps the left cloud. A second stretches over the middle and right clouds together. The third is a small ellipse tucked inside the same region. Two neurons got merged and one got split. That is a local maximum: every nearby move lowers the score, yet a far better fit exists.
The whole algorithm fits in a dozen lines. The shapes are in the comments. The tiny floor keeps a covariance from collapsing to zero.
pythondef em(X, K, iters=100, seed=0, floor=1e-4): rng = np.random.default_rng(seed); N, D = X.shape # X: (N, D) spikes mu = X[rng.choice(N, K, replace=False)] # (K, D): start on K random spikes C = np.stack([0.5 * np.eye(D)] * K); pi = np.full(K, 1 / K) for t in range(iters): dens = np.stack([pi[k] * mvn.pdf(X, mu[k], C[k]) for k in range(K)], axis=1) # (N, K) ll = np.log(dens.sum(1)).sum() # log-likelihood, for monitoring R = dens / dens.sum(1, keepdims=True) # E-step: (N, K) responsibilities Nk = R.sum(0); pi = Nk / N # M-step: counts and shares mu = (R.T @ X) / Nk[:, None] # (K, D) weighted means for k in range(K): d = X - mu[k]; C[k] = (R[:, k, None] * d).T @ d / Nk[k] + floor * np.eye(D) return pi, mu, C, ll
Three failures deserve a symptom, a measurement and a fix. First, the false peak you just met. The symptom is a fit with merged or split neurons. The measurement is the final log-likelihood, which was 35.5 lower for Start 4 than for Start 1. The fix is to run several starts and keep the highest. Press Pick the best start to do it by hand.
Second, a collapsed variance. If one ellipse shrinks onto a single spike, the Gaussian’s height at that spike grows without limit, and the log-likelihood races to infinity. The measurement is a covariance with a determinant near zero. The fix is the floor above, or a prior on the covariance. Third, the wrong number of neurons K. The algorithm cannot choose K. It will fit three ellipses to two neurons and split one. Choose K by comparing log-likelihoods that are penalised for size, or by looking at spike shapes.
Chapter 9
Keep the numbers, the checklist and the code, and find where to go next
Some models hide a variable: a label that was never recorded. A mixture of Gaussians draws a hidden label z from a coin, then draws the data x from that label’s bell curve. With the parameters known, Bayes’ rule recovers the label: that is inference. Fitting the parameters directly is hard, because the log sits outside a sum over the hidden label. Jensen’s inequality builds a floor F under the log-likelihood. F has two faces. One says the gap is a KL, so the E-step sets q to the recognition distribution. The other says F is an average of an easy bowl plus an entropy, so the M-step refits the parameters with weighted averages. Alternating them is coordinate ascent on F, and the log-likelihood never falls. It stops at a peak, maybe a false one, so you run several starts.
| Term | What it is | Number from this lesson |
|---|---|---|
| Free parameters | Two neurons, two features: one share, two means, two covariances | 1 + 4 + 6 = 11 numbers |
| Recognition distribution | The chance a spike came from neuron A, given its height | 0.658 at x = 2 with p = 0.3 |
| Log-likelihood, three spikes | Sum of the logs of the marginals (the log sits outside the sum over z) | −6.51 for x = 1, 2, 4 |
| Jensen gap | Log of the average minus the average of the logs | 0.223 for heights 1 and 4 |
| Bound and evidence | F with q = (0.5, 0.5) against log p(x) | −2.256 against −2.204, gap 0.052 |
| One EM round | Mean of A hops from 0.2, log-likelihood rises | −146.83 to −133.10 at 0.827 |
| Two peaks | The tall peak and the false one on the same 40 spikes | −133.1 near 0.84, −178.0 near 4.5 |
| Staircase speed | Rounds until θ is within 0.05 of the summit | 3, 9 and 36 for ρ = 0.5, 0.8, 0.95 |
| Four starts | Final log-likelihood of three-neuron EM from four starts | −248.8, −269.2, −271.9, −284.3 |
| Term | Plain meaning |
|---|---|
| Latent variable | A quantity the model needs that nobody measured, such as which neuron fired a spike. |
| Marginal likelihood | The chance of the data with the label summed out. The lecture calls it the evidence. |
| Total-data likelihood | The chance of the data and the labels together. Its log is an easy bowl. |
| Evidence lower bound (ELBO) | The floor F under the log-likelihood. The lecture also calls it the variational free energy. |
| KL divergence | How far one distribution is from another. Never negative, and zero only when they match. |
| E-step and M-step | Set q to the recognition distribution. Then refit the parameters by weighted averages. |
python# One EM round for two neurons in one dimension: the lecture's formulas, line by line. a = p * norm.pdf(x, mu1, s1) # (N,) score of neuron A: p N1(x) b = (1 - p) * norm.pdf(x, mu0, s0) # (N,) score of neuron B: (1 - p) N0(x) r = a / (a + b) # E-step: recognition distribution p(z=1 | x) F = (r * np.log(a / r) + (1 - r) * np.log(b / (1 - r))).sum() # the free energy, touches log p(x) p = r.mean() # M-step: new share mu1 = (r * x).sum() / r.sum() # weighted mean of A mu0 = ((1 - r) * x).sum() / (1 - r).sum() s1 = np.sqrt((r * (x - mu1) ** 2).sum() / r.sum()) # weighted spread of A (s0 likewise)
EM is a special case of a larger idea: bound the hard quantity from below with an easy one and climb the bound. The same F appears as the ELBO that trains variational autoencoders. When the recognition distribution is too hard to write down, the E-step is replaced by sampling or by a learned guess. The two big uses in neural data are clustering (spike sorting) and latent-variable models of populations.
This lesson follows Lecture 16 of NEU 560, Statistical Modeling and Analysis of Neural Data, taught by Jonathan Pillow at Princeton in Spring 2024. See the course site and the lecture slides. The lecture’s closing figure of EM on a mixture of Gaussians is credited there to Dayan and Abbott. Every device, number and example here is our own, and the toy data are labelled illustrative where they appear.
Now press Teach and explain one EM round out loud, from memory: what the hidden label is, what the E-step computes, why the bound touches the curve, what the M-step averages, and why the likelihood cannot fall. Then go back to the spikes at the top and run EM again, and this time say what each button does before you press it.