A neuron drifts between a quiet state and a busy state, and you only see its spikes. A hidden Markov model reads the state back out of the counts.
Learn how a chain of hidden states and a spike count in each time bin give you a model you can sample from, read, smooth and fit.
Press Smoother, then drag the stickiness. Watch the inferred state sharpen when the model may use the future as well as the past, and blur when it trusts the wrong stickiness. Then we build, piece by piece, the chain, the matrix, the emissions, and the three algorithms that read, smooth and fit it.
You need a rough idea of probability (a number from 0 to 1 for how likely something is) and what a spike count is. We build the rest from zero, including the Gaussian facts from the lecture’s practice quiz.
Based on Lecture 21 of Princeton NEU 560: Statistical Modeling and Analysis of Neural Data (Spring 2024), taught by Jonathan Pillow. Lecture slides. The deck is short, so we add the full topic from Christopher Bishop, Pattern Recognition and Machine Learning, chapter 13. Every idea is re-taught here in our own words and devices; it follows the course but does not copy its slides.
Illustrative toy: 40 bins, a quiet state firing 1 spike per bin on average and a busy state firing 5 (Poisson counts). The simulated neuron stays in its state with probability 0.92 per bin. The model knows the two rates but not the stickiness, which you set.
Chapter 0
See why one spike count cannot tell you what a neuron is doing, and why a model with a memory of the past can
Picture a single cortical neuron recorded for ten minutes under light anaesthesia. You cut the recording into 100 millisecond bins and count the spikes in each bin. The counts read 0, 1, 1, 0, 2, 6, 4, 7, 5, 3, 6, 1, 0.
Your eye splits that list at once. The first five numbers are small. The next six are large. Then it goes quiet again. You did not look at one number at a time. You saw a stretch of quiet and a stretch of activity, and you guessed that the neuron was in two different modes.
Real cortex does this. During slow-wave sleep and under some anaesthetics, populations of neurons switch between a long down state, where they are almost silent, and an up state, where they fire freely. Nobody sees the switch directly. The experimenter sees spikes. The mode is hidden.
This lesson follows Lecture 21 of Jonathan Pillow’s course. Its subject is the hidden Markov model, or HMM: a model for exactly this situation. A hidden state hops between a few values, one step at a time. At each step it produces something we can measure.
Why not label each bin on its own? Because a single count is ambiguous. Say the quiet state fires 1 spike per bin on average, and the busy state fires 5. These numbers are illustrative. A bin with 0 spikes is almost certainly quiet. A bin with 9 spikes is almost certainly busy. A bin with 2 or 3 spikes could come from either.
The tool for this is a Poisson distribution, the standard model for a count of random events in a fixed window. If the average count is λ, the chance of seeing exactly k spikes is λk e−λ / k!. You do not need to love the formula. It is a hump that sits near λ and has a tail. Chapter 6 returns to it.
Try the device. Move the slider to a count and compare the two humps at that count. The ratio of the heights tells you how strongly one state beats the other.
Pale purple bars: how likely each count is when the neuron is quiet (1 spike per bin on average). Solid purple bars: the same for busy (5 per bin). Drag the count and watch which bar is taller.
Illustrative rates: 1 and 5 spikes per bin. The percentage assumes the two states are equally likely before you see the count. The probabilities are exact Poisson values.
At 3 spikes the busy state wins, but only by about 70 to 30. That is far from certain. A fair guess needs more evidence, and the evidence is in the neighbours. If the bins on both sides hold 5 and 6 spikes, a 3 in the middle is probably a quiet moment inside a busy stretch, not a switch.
That is the idea of the whole lecture. Neighbouring bins share a state. The model keeps a belief about the state, updates it with every new count, and lets the belief carry over from bin to bin.
The deck is short. It opens with a six question practice quiz on the previous lecture: factor analysis, how Gaussians combine, and Monte Carlo gradients. It ends with a single summary slide on latent time series. We teach the quiz in Chapters 1 to 3 and the summary in Chapters 4 to 6. Because the summary only defines the model, Chapters 7 to 10 add what you do with it, following Bishop’s chapter 13: read the state, use hindsight, find the best story, and fit the parameters.
Chapter 1
Derive the prior, the conditional and the marginal of factor analysis and PPCA, the template every latent model in this lesson follows
The lecture opens with a practice quiz on the previous lecture. Its first three questions ask about factor analysis (FA) and probabilistic PCA (PPCA). They are worth a full chapter, because they set the pattern the hidden Markov model copies: a hidden thing, a rule that turns it into data, and a rule for the data alone.
Start with a scene. You record 20 neurons while an animal looks at a screen. On some trials all the neurons run a little hot, on others a little cool, and the cause is a fluctuation in attention that you never measured. Neuron 1 follows it strongly. Neuron 2 follows it weakly. Each neuron also has noise of its own.
Write the attention on one trial as a single number z, a hidden dial. It is a latent variable: a quantity that shapes the data but that you never observe. The data on one trial, x, is a list of 20 firing rates. The dial pushes each rate up or down by its own amount. Then private noise adds a little more.
Question 1: the prior. Before you see any data, what do you believe about z? The model says z is drawn from a standard Gaussian: mean 0, variance 1 in every direction. We write z ∼ N(0, I). With several dials, z is a list, and I is the identity matrix, which says the dials are independent and each has variance 1.
Why mean 0 and variance 1? Because the scale of a hidden dial has no meaning. If you doubled z and halved its effect, the data would look the same. Fixing the scale of z removes that ambiguity, and the loadings carry the scale instead.
Question 2: the conditional. Given z, what is the distribution of the data? Each rate is a weighted copy of the dial plus noise:
The two models differ only in Γ. In FA, Γ is a diagonal matrix with a separate variance σi² for each neuron. A noisy neuron and a quiet neuron are allowed. In PPCA, Γ = σ²I: every neuron gets the same noise.
Question 3: the marginal. If you ignore z and look only at x, what distribution do you see? The answer is another Gaussian, and the next chapter proves the rule behind it:
Work one case with every step. Two neurons, one dial, loadings a = (2, 1) and FA noise variances (1, 0.5). The dial part is aa⊤ = [[4, 2], [2, 1]]. Add Γ = diag(1, 0.5) and the covariance is [[5, 2], [2, 1.5]]. The correlation is 2 / √(5 × 1.5) = 0.73. Two neurons share one cause, and you see it as a correlation.
Each blue dot is one trial of two neurons. The warm ellipse is the formula AA⊤ + Γ. The purple line is the dial’s direction. Change a loading or a noise level and compare ellipse and dots.
Toy data: 300 trials from one dial, seeded so the same dial and noise draws are reused as you move the sliders. In PPCA mode neuron 2 copies the noise of neuron 1. The sample numbers come from those 300 dots, so they differ a little from the formula.
Look at what the formula says, not only what the dots do. With the dial removed (both loadings 0) the ellipse is axis aligned: no shared cause, no correlation. Switch off the noise and the dots collapse onto the purple line, one dimension in a two dimensional space. Real data sit in between, and that is the point of the model: a thin shared structure plus private noise.
Ordinary PCA finds the directions of largest variance and has no noise model. PPCA gives it one. As the shared noise σ² shrinks toward zero, the PPCA solution approaches the PCA directions. That is a result of Tipping and Bishop, and it is why PPCA is a probabilistic version of PCA.
The difference between FA and PPCA matters for neural data. Suppose one neuron is much noisier than the rest. PPCA assumes equal noise, so it treats that neuron’s large variance as signal and tilts its main direction toward it. FA gives that neuron its own σi², keeps its noise out of the shared part, and recovers the dial more cleanly. The symptom is a first direction that points at one loud neuron. The measurement is the fitted noise variances. The fix is FA.
Hold on to the shape of this construction. A hidden quantity with a simple prior. A conditional that turns it into data. A marginal you get by averaging the hidden quantity away. The HMM keeps all three, with one change: the hidden quantity is now a chain.
Chapter 2
Derive the mean and covariance of a weighted sum of two Gaussians, the one rule that powers the marginal of factor analysis and every step of a Kalman filter
Think of a cortical neuron’s membrane voltage. It receives a noisy push from excitatory inputs and a noisy pull from inhibitory inputs. Each input has a synaptic weight that scales it. The voltage you record is a weighted sum of the two. What does the sum look like?
Question 4 of the quiz asks exactly this. Say x is a Gaussian with mean μ1 and covariance C1. Say y is a Gaussian with mean μ2 and covariance C2. Form z = Ax + By. What is the distribution of z? The lecture’s answer is:
The slide leaves one condition unsaid: x and y must be independent, meaning that knowing one tells you nothing about the other. The rest of this chapter shows where that condition enters.
The mean of a sum is the sum of the means, and a constant factor comes straight out. For one number, E[2x] = 2E[x]. For vectors the same holds with a matrix: E[Ax] = A E[x] = Aμ1. So E[z] = Aμ1 + Bμ2. This step needs no independence and no Gaussians. It is just linearity of averaging.
The covariance C of a vector x measures how its parts spread and move together: C = E[(x − μ)(x − μ)⊤]. Apply a matrix A and the deviation becomes A(x − μ). Then the covariance of Ax is
E[ A(x − μ)(x − μ)⊤A⊤ ] = A C A⊤
The matrix lands on both sides because the deviation appears twice, once as a column and once as a row. For one number this is the familiar fact that doubling a variable multiplies its variance by four. The factor is A², not A.
Now add the two parts. The covariance of z has four pieces: the covariance of Ax, the covariance of By, and two cross terms that measure how Ax and By move together. If x and y are independent, they do not move together, so both cross terms are zero. That leaves AC1A⊤ + BC2B⊤.
Why is z Gaussian and not some other shape? A linear map of a Gaussian vector is again Gaussian. We use that fact without proof. It is the reason Gaussians are so easy to compute with: the answer always stays in the family, and two numbers, a mean and a covariance, say everything.
Take single numbers. x has mean 1 and variance 4. y has mean −2 and variance 9. Let A = 2 and B = 1.
For a matrix case, let x have covariance C1 = I (two independent unit Gaussians) and let A = [[1, 0], [1, 1]], which copies the first coordinate into the second. Then AC1A⊤ = AA⊤ = [[1, 1], [1, 2]]. A map that mixes the coordinates creates correlation. This is the same AA⊤ as in Chapter 1: that was this rule with y as the private noise.
x has mean 1 and variance 4. y has mean −2 and variance 9. The blue bars are 2,000 samples of z = Ax + By. The warm curve is the formula. Set the weights, then try a correlation between x and y.
Illustrative inputs. At correlation 0 the formula is the lecture’s. For correlation ρ the variance gains the cross term 2ABρ×2×3 (the product of the two standard deviations). The samples are seeded and reused as you move the sliders.
Start at A = 2, B = 1: the curve is centred on 0 with a standard deviation of 5. The samples match it. Now flip B to −1. The mean moves to 4 and the variance stays at 25, because B is squared. The sign of a weight moves the centre but never widens the curve.
Then raise the correlation with A = 2 and B = 1. The curve widens. Set B = −1 and raise it again: the curve narrows. When inputs that push in opposite directions are also correlated, they cancel. This is the failure mode of the independence assumption. The symptom is a spread that does not match the formula. The measurement is the sample covariance of x and y. The fix is to add the cross terms, AC12B⊤ + BC21A⊤.
A hidden state that evolves linearly with noise, zt+1 = Azt + noise, applies this rule at every step. The mean moves by A and the covariance becomes APA⊤ + Q. That is the predict step of the Kalman filter. The HMM keeps the chain but makes the hidden state a discrete label, which changes the maths from Gaussians to tables.
Chapter 3
Estimate the derivative of an average by sampling, and see why moving the parameter inside the sample makes the estimate far less noisy
You are fitting a model of a neuron’s firing. You draw samples from a distribution q that you control, score each sample with a target log-probability, and average the scores. To improve the model you need the derivative of that average with respect to q’s parameters. How do you differentiate an average over random draws?
The last two quiz questions answer this. The setting is small enough to solve on paper, which lets us check every estimate against the truth. Let q be a Gaussian with mean μ and variance σ². Let p be a Gaussian with mean a and variance b. The quantity of interest is the average score:
Monte Carlo integration replaces an average over every possible x with an average over a few random draws. Draw x1 to xn from q, score each, and take the mean. The estimate is noisy, but its error shrinks like 1/√n: four times as many draws halve the error. The Monte Carlo lesson builds this from darts.
Here the parameter a belongs to the target p, and q does not depend on a. So the derivative can move inside the average. Differentiating the Gaussian score gives (x − a)/b:
∂/∂a Eq[log p(x)] = Eq[ (x − a) / b ]
Now it is an ordinary average. The recipe has two lines, as on the slide. Sample: xi ∼ q. Evaluate: (1/n) Σ (xi − a)/b. Nothing else is needed.
Now the parameter μ belongs to q, the distribution we sample from. This is harder. Changing μ moves the samples themselves, so you cannot simply differentiate the score and leave the draws where they are. The derivative cannot go inside the average in the same way.
The lecture’s fix is the resampling trick, also called the reparameterization trick. Write each draw as a fixed standard noise value, shifted and scaled: x = μ + σε, where ε ∼ N(0, 1). The randomness now lives in ε, which does not depend on μ. The parameter sits inside the score, where we can differentiate it:
∂/∂μ Eε[ log p(μ + σε) ] = −Eε[ (μ + σε − a) / b ]
Recipe: sample εi ∼ N(0, 1). Evaluate −(1/n) Σ (μ + σεi − a)/b. Think of it as a pipeline. The noise ε flows through a fixed, differentiable function (shift by μ, scale by σ) and into the score. A derivative can flow back along the same path.
This trick is how variational autoencoders pass gradients through a random draw.
This problem has a closed form. The average score is a constant minus ((μ − a)² + σ²) / (2b). Differentiate: ∂/∂a gives (μ − a)/b, and ∂/∂μ gives −(μ − a)/b. Both estimators should settle on these values.
Work four draws by hand. Let μ = 1, σ = 1.5, a = 2, b = 1, and say the noise draws are ε = (0.5, −1, 0.2, 1.3). These are illustrative.
Four draws land at 0.625, short of 1. That is ordinary Monte Carlo noise. The device repeats this experiment 100 times so that you can see the spread.
Each dot is one estimate from n fresh draws. The line marks the exact answer. Rows 1 and 2 are the lecture’s two recipes. Row 3 is a third estimator for the same slope, to show why the trick helps.
Illustrative setting: q has mean μ = 1 and standard deviation σ = 1.5, and the target has variance b = 1. Row 3 is the score function estimator, the average of log p(x) × (x − μ)/σ², with no variance-reduction baseline. It is unbiased but noisier. That row is our addition; the lecture shows only rows 1 and 2. Dots beyond the edge sit on the edge.
Drag n up and the rows narrow together, like 1/√n. Now compare rows 2 and 3. Both aim at the same slope and both are centred on it. Row 3 spreads far wider. The score function method learns the direction only from the values of the score. The resampling method uses the score’s slope, which points straight at the answer.
Here is the failure mode as three steps. Symptom: training jumps around and the loss does not settle. Measurement: repeat the gradient estimate on a fixed model and look at its spread, as the device does. Fix: use the resampling trick when the draw can be written as a smooth function of noise, or add draws.
Chapter 4
Build the model from two simple rules, a hidden chain and a spike count in each bin, and write its joint probability as one product
Play nature for a moment and make a spike train. First choose the neuron’s state for the first bin, quiet or busy. Then draw a spike count from that state’s firing rate. For the second bin, decide whether the state stays or flips, with a bias to stay. Draw another count. Repeat for as many bins as you want.
You have just run a latent time series model: a sequence of hidden states, one per time step, each producing one measurement. The lecture’s summary slide opens with this phrase. When the hidden states take a small number of values, it is a hidden Markov model. “Hidden” is the state you cannot see. “Markov” names the rule for how it moves.
The first rule is the dynamics model. It says how the state moves from one bin to the next. The lecture writes it as P(zt+1 = j | zt = i) = Aij. Read it as: if the neuron is in state i now, the chance it is in state j next is the number Aij. The table of all these numbers is the transition matrix A, and Chapter 5 studies it.
The second rule is the observation model, written P(xt | zt). It says what you measure when the state is zt. Here it is a Poisson spike count. Chapter 6 covers the choices.
Two assumptions hide inside this recipe. The Markov property: the next state depends on the present state only, not on the longer history. And conditional independence of the observations: given the state, each count is independent of every other count. Together they say the past matters only through the current state. That is a strong claim and a very useful one.
Draw each variable as a node and each direct dependence as an arrow. A row of states z1, z2, z3, … has an arrow from each to the next. Below it, each zt has one arrow down to its count xt. This is the graphical model. A missing arrow is a claim of independence: there is no arrow from z1 to z3, because z2 carries all the news.
The graph tells you how to write the joint probability of everything, states and counts together. Multiply one factor per node, each conditioned on its parents:
The capital pi means “multiply together”, as a capital sigma means “add”. Count the factors for T bins: one start, T − 1 transitions, T emissions. Nothing else is in the model.
Now work one case with every number. Two states, quiet (L) and busy (H), that start 50/50. Each state stays with probability 0.9. The rates are 1 and 5. Take the path L, H, H with counts 1, 4, 5.
The device samples a chain one step at a time and keeps this running product for you. Press Next bin and watch each new state and count add exactly two factors.
Top row: the hidden states, purple when busy. Bottom row: the counts you would record. Each arrow is a direct dependence. Press Next bin, or drag the stickiness to see the same random draws behave differently.
Illustrative: rates 1 and 5 spikes per bin, a 50/50 start, and fixed random numbers reused as you change the stickiness. The product uses the exact Poisson probabilities.
The probability falls fast, as in any long product of small numbers. That is not a bug. Many stories are possible, so each one is individually unlikely. Chapter 7 shows how to avoid numerical underflow.
Here is the failure mode of the model itself. Suppose a real neuron stays up for a very regular 300 ms. The HMM cannot say that. Its dwell times come out geometric (Chapter 5): short stays are always the most likely. The symptom is a histogram of fitted state durations that does not look like the real one. The measurement is that histogram. The fix is to add states or to use a model with explicit durations.
Also notice where the hidden Markov model sits next to chapter 1. Both have a hidden variable, a rule from hidden to data, and a marginal over data alone. In FA the hidden variable is a Gaussian dial that is fresh on every trial. In the HMM it is a label that remembers where it was.
Chapter 5
Read a stochastic matrix row by row, derive why its eigenvalues stay at or below 1, and find the long-run state of a chain
Your neuron is in the quiet state this bin. What happens in the next bin? It might stay quiet, with some chance, or it might switch to busy. You need one probability for each possibility, and the probabilities must add to 1, because something has to happen.
Collect those answers for every starting state and you have a table. Each row is a starting state. Each column is a destination. Entry Aij in row i, column j is the chance of going to j next when you are in i now. This table is the transition matrix A. For our two states, with quiet first:
0.9 0.1 0.2 0.8
The top row says that a quiet neuron stays quiet 90 percent of the time and turns busy 10 percent of the time. The bottom row says that a busy neuron turns quiet 20 percent of the time. These are illustrative numbers.
The lecture calls A a stochastic matrix and lists four properties. We take them one at a time and explain why each holds.
An eigenvector of A is a direction that A only stretches, never turns: Av = λv. The stretch factor λ is the eigenvalue. Properties 3 and 4 say something about all the stretch factors of A.
Property 4 is easy to show. Take v = (1, 1, …, 1), a column of ones. Then Av has, in each entry, the row sum of A. Every row sums to 1, so Av = v. The eigenvalue is 1.
Property 3 needs one more idea. Suppose Av = λv and look at the entry of v with the largest size, say vi. Row i of A gives λvi = Σ Aijvj. Each vj is no larger than vi in size, and the weights Aij are positive and add to 1. So the right side is at most vi in size. Therefore |λ| ≤ 1. A weighted average cannot be bigger than the biggest thing you average.
Track the whole population of possible states. Let pt be a row of probabilities, one per state, for bin t. One step later it is pt+1 = ptA. Repeat that and pt usually settles to a distribution that A leaves alone: πA = π. This is the stationary distribution, a row eigenvector with eigenvalue 1. It tells you what share of bins a neuron spends in each state in the long run.
For two states there is a shortcut. Let a = ALH (leave quiet) and b = AHL (leave busy). The stationary probability of quiet is b / (a + b). The other eigenvalue is 1 − a − b. With a = 0.1 and b = 0.2 the numbers are:
The second eigenvalue sets the speed. The gap to the stationary distribution shrinks by a factor of 0.7 on every step. A value near 1 means a slow, sticky chain that forgets its start only after many bins.
Left: the two states and how likely each is to leave. Right: the chance of being busy over time, starting quiet. The dashed line is where it settles. Change the leaving chances.
Illustrative probabilities. The numbers come from multiplying the matrix out step by step, not from a formula, and the eigenvalue and stationary values are the exact two-state results.
Slide the leaving chances down to 0.02 each. The eigenvalue climbs to 0.96 and the curve needs about 96 steps to get within a percentage point of its limit. Push them up to 0.5 each and the second eigenvalue is 0: the chain forgets its start in a single step, because every bin is a fresh coin flip.
Staying is repeated. To stay d bins and then leave, the chain stays d − 1 times and leaves once: Aiid−1(1 − Aii). This is a geometric distribution. Its mean is 1/(1 − Aii). With ALL = 0.9 a quiet stretch lasts 10 bins on average. With 100 millisecond bins that is one second. The most likely single stay is always one bin, which is the weakness Chapter 4 warned about.
Here is the failure mode in practice. Symptom: probabilities leak, so the model’s total mass drifts away from 1 over a long sequence. Measurement: print the row sums of A. Fix: divide each row by its sum. A related slip is a hard zero: if Aij = 0, no path through that move can ever be recovered, however strong the data.
Chapter 6
Choose Gaussian, discrete or Poisson emissions, and see that inference only ever needs one table of how well each state explains each bin
The hidden state is a label. The recording is numbers. Something has to connect them, and that something is the observation model P(xt | zt): the chance of measuring xt when the state is zt. Its form depends on what you record.
The lecture’s summary slide gives two forms. The first is Gaussian: P(xt | zt = j) = N(μj, Cj). Each state j has its own mean μj and covariance Cj. This suits a continuous signal, such as a local field potential or a vector of firing rates from many neurons. For d recorded numbers per bin, xt has shape d × 1, μj has shape d × 1, and Cj has shape d × d.
The second is discrete: P(xt = i | zt = j) = Cij. Here x takes one of M symbols, such as “spike” or “no spike” in a 1 millisecond bin. C is an M × K table, with a column for each state. Column j lists the probabilities of every symbol when the state is j. So the columns sum to 1, which is the opposite of A, whose rows sum to 1.
For spike counts there is a third form, which the slide does not list but Pillow’s own work uses constantly: Poisson, P(xt = k | zt = j) = λjk e−λj / k!. Each state j has a firing rate λj, measured in spikes per bin. The GLM lesson explains why Poisson is the natural count model: a count of rare, independent events. This is the form we used from Chapter 0 on.
Here is a point that makes the rest of the lesson simple. Once you have chosen an observation model, every algorithm after this chapter uses it in one way only. It asks, for each bin t and each state j: how likely is the recorded xt if the state were j?
Write the answers as a table E with T rows and K columns, E[t, j] = P(xt | zt = j). The data flow is:
That is why you can swap Gaussian for Poisson and keep the same code. Work the table for a Gaussian case with one number per bin. State 1 has mean 0, state 2 has mean 2, both with standard deviation 1. A bin reads x = 1.5.
The states are easy to tell apart when their emission distributions barely overlap, and hard when they overlap a lot. A clean measure is the best accuracy you could reach by labelling each bin alone, with equal prior odds: for each possible reading, pick the likelier state. Its accuracy is half the sum, over all readings, of the larger of the two probabilities. It is 50 percent when the states look identical and rises to 100 percent as they separate.
Pick an emission family. Pale purple is the quiet state and solid purple is the busy state. Drag the separation and read the best accuracy a single bin can reach.
Illustrative settings. Gaussian: standard deviation 1, means 0 and 6 times the separation. Discrete: P(spike) is 0.5 minus and plus 0.45 times the separation. Poisson: quiet rate 3 spikes per bin, busy rate 3 plus 9 times the separation. Accuracy assumes equal prior odds and is computed exactly from the distributions.
Try the three families at 50 percent. A single Poisson bin separates rates 3 and 7.5 correctly about 84 percent of the time, good but far from perfect. Raise the separation and watch the accuracy approach 1. Then notice that even at 100 percent the Gaussian is not at 100: its tails always overlap a little.
Single-bin accuracy is the floor of what an HMM can do. The chain adds the neighbours on top, and that is what Chapters 7 and 8 compute.
Here is the failure mode, in the usual three steps. Symptom: the fitted model invents extra states, one for every burst. Measurement: compute the variance of the counts in a stretch divided by their mean, the Fano factor. A Poisson state has a Fano factor of exactly 1. Real neurons often exceed it. Fix: use an emission with extra spread, such as the negative binomial, or accept more states on purpose.
Chapter 7
Update a belief about the hidden state one bin at a time with two moves, predict and update, and avoid the exponential cost of listing every path
You are watching a recording live. A new spike count arrives every 100 milliseconds. After each one you want a single answer: how likely is the neuron busy right now? The answer should use everything you have seen so far, and nothing from the future, because the future has not happened yet.
This is filtering, and its answer is a belief: a probability for each state, given all counts up to now. We write it P(zt | x1, …, xt). The belief is a short list, K numbers for K states, and it adds to 1.
Each new bin does two things to the belief. First predict: the state may have moved since the last bin, so blur the old belief through the transition matrix. If you were 99 percent sure of quiet, you are now a little less sure, because a switch might have happened. Then update: the new count favours some states over others, so multiply each state’s probability by how well it explains the count, and rescale so the list adds to 1.
As formulas, with Et(j) = P(xt | zt = j) the emission table from Chapter 6:
In matrix form it is one line. With αt a vector of K numbers, A of shape K × K and Et a vector of K numbers: αt = (A⊤ αt−1) ⊙ Et, where ⊙ means multiply entry by entry. At the first bin there is no past, so α1 = π ⊙ E1.
Why can the history collapse into one vector? Because of the Markov property. The state zt−1 carries every bit of the past that matters for zt. So summing over zt−1 replaces a sum over all earlier paths. The cost is K² operations per bin, or T K² in all. Listing every path would cost KT: for 2 states and 40 bins, about 1.1 × 1012 paths against 160 multiplications.
Use two states that each stay with probability 0.9, a 50/50 start, rates 1 and 5, and counts 0, 2, 6. Write beliefs as (quiet, busy).
Read bin 3. Before the count, the model gave busy 14 percent. The count 6 is about 290 times more likely under busy than under quiet. That evidence swamps the prior, and the belief jumps to 98 percent. The device lets you step through this on a longer train.
Blue bars are the counts seen so far. The warm curve is the belief that the neuron is busy. At the latest bin a hollow dot shows the belief after predict, and the filled dot shows it after the count updates it.
Illustrative spike train of 14 bins, quiet rate 1, busy rate 5, 50/50 start. The belief and the log-likelihood come from the scaled forward recursion in this page’s code, so the numbers match the worked example for the first three bins.
Step through bins 6 to 9. Counts of 6, 4, 7 and 5 push the belief up. Notice that a count of 4 in a busy stretch still leaves the belief high: the model remembers. Then lower the stickiness to 0.6 and replay. The belief now chases every single count, because a low stickiness says the state forgets quickly.
The rescaling totals have a second use. Each total ct is the probability of the new count given all earlier counts. Multiply them and you get the probability of the whole recording: P(x1:T) = c1 c2 … cT. In the worked example that is 0.1873 × 0.1725 × 0.0216 = 6.98 × 10−4. Chapter 10 needs this number to fit the model.
It also cures the failure mode. Symptom: with raw α values and no rescaling, the numbers shrink by a factor of roughly 0.02 to 0.2 per bin, hit zero after a few hundred bins, and then every belief turns into 0 divided by 0, which is not a number at all. Measurement: print the sum of α at each bin and watch it fall toward the smallest number your computer can hold. Fix: rescale at each bin as above, and add the logarithms of the totals: log P = Σ log ct = −7.27 in our example.
Chapter 8
Combine what the past says with what the future says to get the best belief about every bin, and see why the two halves multiply
Now the experiment is over. The whole recording sits on your disk. Bin 5 holds two spikes: a count that is ambiguous. The filter looked at bins 1 to 5 and shrugged. But you also have bins 6 to 14, and they hold counts of 6, 4, 7, 5. A busy stretch started right after bin 5. Does that change what you think about bin 5?
It should. If the neuron is busy at bin 6, it was probably already busy, or at least about to be, at bin 5, because states are sticky. Information flows backward through the chain as well as forward. Using it is smoothing, and the result is a belief about each bin given all the counts: P(zt | x1, …, xT).
The forward value αt(j) summarised the past. We need a twin that summarises the future. Define βt(i) as the probability of all the later counts, xt+1 to xT, given that the state at t is i. Read it as: how well would state i at bin t explain everything that came after?
It runs backward. At the last bin there is no future, so βT = (1, …, 1). Then fill in bins T − 1, T − 2, and so on down to 1. Cost: K² per bin, the same as the forward pass.
Now put them together. The probability of the state at bin t and all the counts is a product of a past part and a future part:
P(zt = i, x1:T) = αt(i) × βt(i)
The reason is the graph from Chapter 4. Once you fix the state zt, the counts before t and the counts after t are independent. The state is the only road between past and future, and fixing it closes the road. So the joint probability splits into two independent factors. Divide by their sum over i and you have the smoothed belief:
γt(i) = P(zt = i | x1:T) = αt(i) βt(i) / Σk αt(k) βt(k)
The forward-backward algorithm also gives a second quantity that Chapter 10 needs. It is ξt(i, j), the probability that bin t was in state i and bin t + 1 in state j. Its formula is αt(i) Aij Et+1(j) βt+1(j), rescaled to add to 1. It counts, softly, how often the chain made each move.
Take counts 0, 2, 6 again. The forward beliefs for busy were 0.018, 0.056, 0.980.
At bin 2 the filter said busy 5.6 percent. The smoother says 34.0 percent. The count of 6 at bin 3 reached back and lifted bin 2. The filter has no way to see it. At bin 3, the last bin, nothing lies ahead, so the smoother equals the filter: 98 percent either way.
The faint curve is the filter. The strong curve is the smoother. The teal bar is the bin right after the ambiguous bin 5. Change its count and watch bin 5.
Illustrative 14-bin train with quiet rate 1 and busy rate 5; only bin 6 is yours to change. Both curves come from the scaled forward and backward recursions in this page’s code.
Slide bin 6 down to 0. The smoother now gives bin 5 only 1.3 percent busy, and the filter has not moved from 4.9 percent, because bin 6 was never in its past. Slide it to 3 and the smoother says 24.2 percent. At 6 it says 31.8 percent. Beyond 6 it stops rising, because bin 6 is already surely busy, and the only open question left is whether the switch came one bin earlier, at bin 5.
Now the failure mode that matters for real-time work. Symptom: a decoder that looks excellent when you fit it offline falls apart when it runs live. Measurement: score the causal filter and the smoother on held-out data. The smoother wins, but only the filter is available in real time. Fix: a fixed-lag smoother, which waits L bins before it commits to a label. You pay L bins of delay and get most of the hindsight. The continuous-state version of this whole chapter is the RTS smoother, built on the Kalman filter.
Chapter 9
Swap the sum in the forward algorithm for a maximum, keep a pointer at every step, and trace back one best state sequence
The smoother gave you a probability for each bin. But sometimes you want one clean answer: a list of labels for the whole recording, quiet quiet quiet busy busy busy, that you can mark on a plot and hand to a colleague. Which list should it be?
A tempting answer is to take the likelier state in each bin on its own. That uses the smoothed belief γt and picks the larger entry at every t. It sounds right and often works. But the best choice for each bin separately is not always the best choice for the whole story. The bins are linked, and a list of individually good guesses can contain a combination that the chain finds unlikely.
The right question is: which single sequence of states Z has the highest joint probability P(X, Z) with the data? The Viterbi algorithm answers it.
Brute force would try all KT sequences. The forward algorithm avoided that by adding up routes into each state. Viterbi does the same with the best route. Define δt(j) as the probability of the single best path that ends in state j at bin t, counting all counts up to t:
Compare with the forward formula of Chapter 7. The only change is that Σ became max. That one swap changes the question from “what is the total probability of reaching j” to “what is the probability of the best single route to j”.
A maximum throws information away, so we must remember which i won. At each bin and state keep a backpointer ψt(j) = the winning i. After the last bin, pick the state with the largest δT. Then follow the pointers backward: from the final state to its winner at T − 1, and so on to bin 1. The sequence you walk is the best path. This is the same bookkeeping as a shortest-route search on a map.
Run it in logarithms. Products of many probabilities underflow, as in Chapter 7. So add log-probabilities instead: log δt(j) = log Et(j) + maxi [log δt−1(i) + log Aij]. A maximum survives the log, since log is increasing.
Counts 0, 2, 6. Stay 0.9, rates 1 and 5, a 50/50 start. Write log values as (quiet, busy), using natural logs.
The best path has probability e−7.717 = 4.4 × 10−4. The total probability of the counts, from Chapter 7, is 7.0 × 10−4. So this one story carries about 64 percent of all the probability that the model gives these three counts.
Look at the data flow. The input is the emission table E, shape T × K, and the matrix A, shape K × K. The working memory is a score table δ and a pointer table ψ, both T × K. The output is a list of T state labels, one integer per bin. The time cost is T K², the same as the forward pass. If two routes tie, either is a best path, so implementations simply pick the first.
Each column is a bin, each row a state. Purple dots are the counts. The warm line is the Viterbi path. The teal markers show the likelier state in each bin on its own. Drag the stickiness and compare.
Illustrative 12-bin train, simulated with quiet rate 2 and busy rate 4 spikes per bin, closer rates than elsewhere so the two answers can differ. The counts are written under each column. Both paths are scored with the exact joint probability.
At stickiness 0.7 the per-bin guesses flip back and forth, while the Viterbi path makes just one switch. The Viterbi path has the higher joint probability by construction: it is the maximum over every possible path, so no other list can beat it. Slide the stickiness up and the two answers move together.
Here is the failure mode. Symptom: the labels from the per-bin rule contain rapid flicker, or, in a model where some moves are forbidden (Aij = 0), a step the model says can never happen. Measurement: score the label list with the joint probability, as the device does, and check for −∞. Fix: use Viterbi when you need one valid story, and use γ when you need a probability for each bin.
Chapter 10
Fit the rates, the transition matrix and the start from spike counts alone, by alternating soft state guesses with weighted averages
Until now you knew the firing rates and the stickiness. A real recording hands you neither. All you have is the counts. Somewhere inside the data sit a quiet rate, a busy rate, a transition matrix and a start, and you must find them.
It is a chicken and egg problem. If you knew the states, fitting would be easy: average the counts in the busy bins to get the busy rate, and count how often busy turned quiet. If you knew the parameters, finding the states would be easy: run the forward-backward algorithm of Chapter 8. You know neither. So you do what the EM lesson does for mixtures. You guess, use the guess to infer the states, use those states to refit, and repeat.
The E step (expectation) asks: given the current parameters, how likely is each state in each bin? That is the smoothed belief γt(j) from Chapter 8, along with the pair beliefs ξt(i, j). They are soft labels: instead of “bin 7 is busy” you hold “bin 7 is busy with weight 0.93”.
The M step (maximization) refits the parameters as weighted averages, with those soft labels as the weights. For Poisson emissions, three updates cover everything:
For Gaussian emissions the M step is the same shape: a weighted mean and a weighted covariance. For discrete emissions it is a weighted table of symbol counts.
The algorithm has a name, Baum-Welch, after its authors, but it is simply EM where the E step is forward-backward. Bishop’s chapter 13 derives it from the EM bound. The key fact is that each round can only raise the log-likelihood log P(X), or leave it unchanged. The log-likelihood you get from the forward pass of Chapter 7, as the sum of the log rescaling totals, is the number to watch.
Take the three bins with counts 0, 2, 6 from the last chapters. The smoothed beliefs for busy were 0.050, 0.340, 0.980, and for quiet 0.950, 0.660, 0.020. This is a toy: three bins is far too few to fit anything.
The rates land close to the true 1 and 5 (they become 0.88 and 4.79). The quiet row jumps to (0.42, 0.58) because there are only two transitions to count. With 300 bins, the counts would be far steadier.
Look at the data flow of one round. The E step takes the counts, shape T, and the current parameters, and returns γ with shape T × K and ξ with shape (T − 1) × K × K. The M step reduces those to a new π of shape K, a new A of shape K × K and K new rates. One round costs T K², so fitting 300 bins is instant. A common stopping rule is to quit when a round gains less than a tiny amount of log-likelihood, such as 0.001.
A 300-bin spike train was simulated from a known model. Pick a starting guess and run EM. Top: the log-likelihood after each round. Bottom: the fitted values (pink) against the values that made the data (green ticks).
Illustrative simulation: 300 bins, true quiet and busy rates 1 and 5, true stay probabilities 0.95 and 0.90. The fit uses the scaled forward-backward code in this page. Fitted values differ a little from the truth because 300 bins is a finite sample, not because EM is wrong. Bars show the lower-rate state first.
Press Run 1 round a few times from the close start. The log-likelihood rises every time, steeply at first, then flattens. After about 10 rounds nothing changes: EM has converged. Now choose Swapped and run it. The fit ends at the same likelihood, but the model’s state 1 has become the busy one. The state names are arbitrary labels; only the pattern matters.
Here is the failure mode. Symptom: the likelihood stops rising at a poor value, or two states settle on nearly the same rate. Measurement: refit from several random starting guesses and compare the final log-likelihoods. If they disagree, EM found different local peaks: it climbs the nearest hill, not the highest. Fix: run many restarts, keep the best, and make sure each state gets visited. A state that no bin believes in has a weight sum of 0, and the division 0 / 0 breaks the update.
Chapter 11
Keep the numbers, the terms, a checklist and the core code, and see where the model sits in the wider field
A hidden Markov model is a chain of hidden states with a measurement in every bin. Two tables define it: a transition matrix A that says how the state moves, and an emission table that says how a state shows itself. The lecture’s summary slide states exactly that, and the practice quiz on Gaussians and Monte Carlo supplies the tools behind latent models in general. Everything else is bookkeeping with three algorithms: forward for the present, backward for hindsight, Viterbi for one best story, and EM to fit it all.
| Term or number | What it means | Example in this lesson |
|---|---|---|
| Joint P(X, Z) | 1 start, T − 1 transitions, T emissions | 3 bins: 5.10 × 10−4 for the path L, H, H |
| Transition matrix A | Row i is where state i goes next. Rows sum to 1. | Stay 0.9 gives a 10 bin average stay |
| Eigenvalues of A | All of size at most 1; one equals 1 | 1 and 0.7 for leaving chances 0.1 and 0.2 |
| Stationary distribution | The row vector with πA = π | 2/3 quiet and 1/3 busy |
| Emission table E | E[t, j] = P(xt | zt = j), shape T × K | One bin of 3 spikes: busy 70%, quiet 30% |
| Forward cost | T K² operations, not KT paths | 160 against 1.1 × 1012 for 2 states, 40 bins |
| Filter | P(zt | x1:t): past only, for live use | Busy 14% before the count, 98% after |
| Smoother γ | P(zt | x1:T) ∝ αt βt | Bin 2 busy: 5.6% filtered, 34.0% smoothed |
| Pair belief ξ | P(zt = i, zt+1 = j | x1:T) | Feeds the M step for A |
| Viterbi | The single best path: max instead of sum, plus backpointers | Best path 4.4 × 10−4 of 7.0 × 10−4 total, 64% |
| Baum-Welch | EM with forward-backward as the E step; likelihood never falls | Converged in about 10 rounds on 300 bins |
| Practice quiz facts | z ∼ N(0, I); x | z ∼ N(Az, Γ); x ∼ N(0, AA⊤ + Γ); Ax + By ∼ N(Aμ1 + Bμ2, AC1A⊤ + BC2B⊤) | Variance of 2x + y: 25 |
pythonimport numpy as np from scipy.stats import poisson def forward_backward(A, pi, E): # A: (K,K) rows sum to 1. pi: (K,). E: (T,K), E[t,j] = P(x_t | z_t=j) T, K = E.shape al = np.zeros((T, K)); c = np.zeros(T) a = pi * E[0]; c[0] = a.sum(); al[0] = a / c[0] for t in range(1, T): a = (A.T @ al[t-1]) * E[t] # predict, then update c[t] = a.sum(); al[t] = a / c[t] # rescale every bin be = np.ones((T, K)) for t in range(T-2, -1, -1): be[t] = A @ (E[t+1] * be[t+1]) / c[t+1] # backward pass gam = al * be # (T,K) P(z_t | all x) xi = al[:-1, :, None] * A[None] * (E[1:] * be[1:])[:, None, :] / c[1:, None, None] return gam, xi, np.log(c).sum() # xi: (T-1,K,K); log P(x) def viterbi(A, pi, E): T, K = E.shape d = np.log(pi) + np.log(E[0]); bp = np.zeros((T, K), int) for t in range(1, T): s = d[:, None] + np.log(A) # (from, to) bp[t] = s.argmax(0); d = s.max(0) + np.log(E[t]) z = np.zeros(T, int); z[-1] = d.argmax() for t in range(T-1, 0, -1): z[t-1] = bp[t, z[t]] return z def baum_welch(x, lam, A, pi, iters=30): # x: (T,) spike counts for _ in range(iters): E = poisson.pmf(x[:, None], lam[None]) # (T,K) emission table gam, xi, ll = forward_backward(A, pi, E) # E step pi = gam[0] # M step A = xi.sum(0) / xi.sum((0, 2))[:, None] lam = (gam * x[:, None]).sum(0) / gam.sum(0) return lam, A, pi, ll
The HMM has a discrete hidden state. Give the state continuous values with Gaussian noise and the same forward and backward passes become the Kalman filter and the RTS smoother. Factor analysis from Chapter 1 has a hidden state with no memory at all. Put the three together and you have the family of latent-variable models for neural data: discrete or continuous, with or without dynamics. Their parameters are fitted by the same EM loop that the EM lesson builds for mixtures.
Now press Teach and explain one thing out loud from memory: why the smoothed belief at a bin is the forward value times the backward value. Then go back to the instrument at the top and watch the filter and the smoother disagree.
The course sources: Jonathan Pillow’s NEU 560 course site, the Lecture 21 slides (practice quiz and summary), and Christopher Bishop’s Pattern Recognition and Machine Learning, chapter 13, for the forward-backward, Viterbi and Baum-Welch material. This lesson re-teaches those ideas in its own words and devices; all toy numbers are marked illustrative.