Forty neurons fire with no stimulus, yet they rise and fall together. One hidden signal drives them all, and with 40 neurons we recover it almost exactly.
Learn how a model can explain spike trains with a variable nobody measured, how to infer it, and why fitting such a model is hard.
Press 3 neurons, 10 neurons and 40 neurons. Watch how well the warm estimate follows the purple hidden driver. Then we build, piece by piece, the hidden-variable model, the integral that makes it hard, and the algorithms that fit it.
You need a rough idea of probability (a number from 0 to 1 for how likely something is) and what a spike train is. We build the rest from zero.
Based on Lecture 15 of Princeton NEU 560: Statistical Modeling and Analysis of Neural Data (Spring 2024), taught by Jonathan Pillow; the lecture slides and notes are linked from the course site. Every idea is re-taught here in our own words and devices.
Simulated, not recorded: each neuron fires as a Poisson process whose rate is exp(baseline + loading × driver), over 120 time bins. The estimate here is told each neuron’s loading and averages the smoothed spike trains with those weights; Chapter 4 shows what changes when the loadings are unknown too.
Chapter 0
See why identical trials still give neurons that rise and fall together, and meet the idea that explains it
Picture a mouse sitting in a dark, quiet box. A thin probe in its cortex records 40 neurons. The screen is blank, the room is silent, and the mouse does nothing. You expect noise. Instead you see waves: for half a second most neurons fire a little more, then most fire a little less.
Nobody gave the mouse a stimulus, so nothing in your data table explains the waves. Something is still moving the whole population. It might be attention, arousal, a memory replaying, or a brain state you have no name for. You did not measure it. Yet it leaves fingerprints on every spike train you did measure.
This lecture is about models for exactly that situation. Princeton NEU 560, taught by Jonathan Pillow, spends Lecture 15 on latent variable models. The word latent just means hidden: a variable we believe exists but never observe. The models explain what we see by positing something we do not see.
Until now the course fitted encoding models, also called regression models. These answer one question: given a known stimulus x, what spikes y does a neuron produce? We write that as P(y | x), read “the probability of y given x”. A stimulus goes in, a spike train comes out, and the model learns the mapping.
Lecture 15 asks what to do when there is no x. The slides pose it in a single line: what if there’s no stimulus? The goal changes from predicting responses to finding simplifying structure in the responses themselves. Statisticians call this unsupervised learning, because no known answer supervises the fit.
Here is the clearest fingerprint of a hidden driver. Take two neurons and repeat one identical stimulus many times. Each repeat is a trial. If each neuron fired by independent chance, a high count in neuron A would tell you nothing about neuron B on the same trial.
A hidden driver breaks that independence. On a trial where the driver is strong, both neurons fire more. On a weak trial, both fire less. Plot neuron B’s count against neuron A’s across trials and the points lean into a diagonal. The amount of lean is the correlation: 0 for none, 1 for a perfect line.
The device below makes this concrete. Each trial gets a hidden gain, a number that turns the firing rate of both neurons up or down together. You control how strongly that gain acts. Drag the slider and watch the cloud lean.
Each dot is one trial of an identical stimulus: neuron A’s spike count across, neuron B’s up. Purple dots had a high hidden gain, faint dots a low one. Drag the strength of the shared gain from 0 to 1.
Simulated, not recorded: each neuron is Poisson (random events at an average rate) with a typical count of 8 spikes per trial, multiplied on every trial by the same hidden factor exp(strength × 0.5 × gain), where gain is a standard normal draw. The 60 random numbers are fixed, so the dots move smoothly as you drag.
At strength 0 the cloud is round: knowing A tells you nothing about B. At strength 1 it leans clearly. Notice that neither neuron has changed its own behaviour. Each still fires with a Poisson count around 8. Only the hidden gain, shared between them, ties them together.
You cannot fix this with a better stimulus model, because the stimulus never changed. The only honest model includes the hidden gain as a variable. We give it a name, give it a probability distribution, and let it influence every neuron. That is a latent variable model in one sentence.
The slides draw the same picture. A brain sits between the world and the recordings, and in the lecture’s later figure a red dot labelled “latent variable” sits inside the head. It produces membrane potentials, spikes and imaging signals. We record those. We never record the dot.
The lecture opens with a warmup, a practice quiz and a tour of loose ends from regression (slides 2 to 9, Chapters 1 and 2). Then it turns to hidden variables. Chapter 3 defines them. Chapter 4 gives neural examples. Chapter 5 shows why they are hard, and Chapter 6 gives three ways to fit them. Chapter 7 lists the models they define, and Chapter 8 separates inference from fitting. Chapter 9 works one model in full, as the board did. Chapter 10 collects the numbers and code.
Chapter 1
Derive the Laplace approximation for a spike-or-no-spike neuron, and see how few trials it needs to look right
You record one neuron on 40 trials. On each trial you turn a light on with some strength x, and you note one thing: did the neuron spike, yes or no? You suspect that stronger light makes a spike more likely, and you want to know how strongly. That strength is one number, a weight w.
The lecture starts with this model, a Bernoulli GLM. Bernoulli means each outcome is yes or no. GLM (generalised linear model) means the probability of yes is a fixed curve applied to a weighted input. Here the curve is the logistic function, f(u) = 1 / (1 + e−u), which squashes any number into a probability between 0 and 1. The spike probability on a trial is f(x · w).
The slides ask for the Laplace approximation of the posterior over w, with a flat prior. Two words need defining. The posterior is your belief about w after seeing the data. A flat prior means you had no preference for any w beforehand, so the posterior is shaped by the likelihood alone. The likelihood is how probable the observed spikes were, as a function of w.
Start with one trial. The log-likelihood is L(w) = y log f(xw) + (1 − y) log(1 − f(xw)). Substitute the logistic curve and the y terms cancel, as the slide notes, leaving L(w) = −(1 − y)xw − log(1 + e−xw). Now differentiate twice.
With many trials, add the terms: the slope becomes Σ xi(yi − f(xiw)) and the curvature becomes −Σ xi² f(1 − f). No y appears in the curvature, so it depends on the stimuli and the current w, not on which trials spiked.
The posterior is hard to write down. So we replace it with a Gaussian that matches it at its peak. Three steps. First, find the MAP estimate (maximum a posteriori): the w with the highest posterior, written ŵmap. Second, compute the Hessian H, the matrix of second derivatives of the log-posterior at that point. With one weight it is a single number. Third, use the Gaussian whose mean is ŵmap and whose variance is −H−1.
Why a Gaussian? Near a peak, the log of almost any smooth bump looks like a downward parabola. A parabola in the log is exactly a Gaussian. The curvature sets the width: sharp peak, narrow Gaussian. For this model the variance is 1 / (Σ xi² f(xiŵ)(1 − f(xiŵ))).
Three trials, all with light strength x = 1. Two trials spiked (y = 1, 1, 0). The slope is the sum of (y − f(w)) over the three trials: (1 − f) + (1 − f) + (0 − f) = 2 − 3f. Set it to zero: f = 2/3. The logistic curve reaches 2/3 at w = ln 2 = 0.693, so ŵ = 0.693. The curvature is −3 × (2/3)(1/3) = −0.667. The variance is 1 / 0.667 = 1.5 and the standard deviation is 1.22. So the Laplace posterior is a Gaussian centred on 0.69 with spread 1.22. Three trials give a wide belief, as they should.
The purple curve is the exact posterior over w. The warm curve is its Laplace Gaussian. Drag the number of trials and watch the two curves converge.
Simulated: stimuli are standard normal draws and spikes are Bernoulli with true weight 1.2, seeded so every visit shows the same trials. The exact posterior is computed on a grid from −4 to 6 with a flat prior; the Laplace curve uses Newton steps for the peak and the curvature formula above.
With few trials, the exact posterior is lopsided and the Gaussian misses its shape. With 40 or more trials the two curves almost coincide. That is the general rule: the more data you have, the more a posterior looks like a Gaussian, so the approximation improves exactly when you most want to trust it.
The failure shows up at the left end of the device. The symptom: at 10 trials the two curves disagree, and the Gaussian is too wide. The measurement is the pair of spreads in the read-out: 1.80 for the Laplace Gaussian against 1.41 for the exact posterior. When they differ by more than a few percent, do not trust the Gaussian. The fix is more data (at 40 trials the spreads are 0.47 and 0.50) or a method that does not assume a bell shape, such as the sampling and variational methods of Chapter 6. With only a few trials, the stimulus may separate the spikes from the non-spikes perfectly. Then the likelihood has no peak at all, and the Laplace approximation does not exist.
The slides close the warmup with five questions, each with a short answer. Read them as a checklist for Bayesian regression.
Try answer 5 on the worked example. Suppose the prior is flat over a range of width 10, so P(ŵ) = 0.1. The likelihood at 0.693 is (2/3)²(1/3) = 0.148. The Gaussian’s peak height is 1 / √(2π × 1.5) = 0.326. So the evidence is about 0.148 × 0.1 / 0.326 = 0.0455. The exact integral is 0.05. The approximation lands within 9%, from three trials. Remember this move: it returns in Chapter 5, where the evidence becomes the hard part.
Chapter 2
See why maximum likelihood is really a search for the nearest model, then tour the extensions the lecture lists
Before leaving regression, the lecture ties off four loose ends. Think of a mechanic closing the hood: the engine is fine, but a few parts deserve a name. Two of them get real teaching time: the link between maximum likelihood and KL divergence, and the kernel trick. The other two are lists to look up later.
Suppose you counted the spikes of one neuron in 50 trials. The counts come from some unknown true source, which the slides call Ptrue(x). You pick a model Pθ(x), for example a Poisson distribution with average rate θ. Maximum likelihood picks the θ that makes the observed counts most probable: θ̂ = arg max Σi log P(xi | θ).
Is “make the data most probable” a sensible goal? The lecture says yes, for a clean reason. It uses the KL divergence, a score for how far apart two distributions are. It is zero when they match and grows as they differ. Expand it.
Read the last line. The entropy term is a constant. The other term is the average log-likelihood with a minus sign. So maximising the likelihood is the same as minimising the KL divergence. We never need the unknown truth: the data stand in for it. Try it below.
Top: blue bars are how often each spike count occurred in 50 trials; the warm outline is a Poisson model with your rate. Bottom: the KL divergence (warm) and the negative average log-likelihood (blue) for every rate. Drag the rate and find the bottom of both curves.
Simulated counts, seeded: 50 trials from a Poisson whose rate varies from trial to trial, so the data are wider than any single Poisson. The KL divergence uses the empirical histogram as Ptrue, in natural-log units (nats). The two curves differ by the constant entropy of that histogram.
The two curves bottom out at the same rate, and for a Poisson that rate is simply the average count. The bars never match perfectly, because a Poisson cannot be as wide as these data. KL stays above zero. It is the price of a model that is too simple, and maximum likelihood finds the least costly version.
Linear regression draws straight lines. A neuron’s tuning curve to stimulus orientation is a bump, not a line. The standard fix is to transform the input: replace x with a longer list of features φ(x) = (1, x, x², x³, x4), then do linear regression on the list. The slide shows this as polynomial regression: y = w0 + w1x + w2x² + … + noise.
The lecture then makes a surprising claim: some linear algebra tricks let us skip the explicit mapping, even for infinitely long feature lists. Here is the smallest case. Use φ(x) = (1, √2·x, x²) and two stimuli x = 2 and x′ = 3. Then φ(2) = (1, 2.83, 4) and φ(3) = (1, 4.24, 9). Their dot product is 1 + 12 + 36 = 49. Now compute (1 + x·x′)² = (1 + 6)² = 49. Same number, with no feature list built. A function that returns such dot products directly is a kernel, and regression that uses only kernels is a kernel method. Treating the kernel as the covariance between function values gives a Gaussian process, the slides’ name for nonlinear regression this way.
Slide 9 lists two more topics without derivation. First, other priors on the weights: sparsity-promoting priors (the “lasso”, an L1 penalty that drives many weights to exactly zero), Automatic Relevance Determination (ARD), Automatic Locality Determination (ALD) and heavy-tailed “robust” priors. Second, other ways to approximate a posterior and evaluate the evidence: MCMC sampling and variational inference. Both come back in Chapter 6, where they become tools for fitting hidden-variable models.
Set the device to its best rate and look again. The symptom is plain: the warm outline is too narrow. It misses the tails on both sides of the blue bars. The measurement that names the problem is the Fano factor, the variance of the counts divided by their mean. A Poisson always has a Fano factor of exactly 1. These counts have mean 4.8 and variance 12.0, a Fano factor of 2.5. Real spike counts often show Fano factors above 1 too.
The fix is a wider family of models. One option is a model whose rate itself changes from trial to trial. That is the hidden gain of Chapter 0. Averaging Poisson distributions over a spread of rates gives a distribution wider than any single Poisson. The rest of this lecture builds that kind of model, and the tools to fit it.
Chapter 3
Add one factor, a probability for x itself, and see how a prediction problem becomes an averaging problem
Slide 10 is a picture the course has used all term. A stimulus x, say a photo of a jumping person, enters an eye. The brain responds. We record the response y in whatever form we have: a membrane potential, a spike train or a calcium image. A box underneath is labelled P(y | x), the encoding model. It says how likely each response is for a given stimulus.
Slide 11 removes the photo and asks “what if there’s no stimulus?” The brain still responds. Slide 12 fills the gap. A red dot labelled latent variable, marked x and described as “unobserved or hidden”, sits inside the head. The box under it now reads P(y | x) P(x), in red for the new factor. That one new factor is the whole difference.
A note on letters. These slides call the hidden variable x and the recorded data y. The lecture notes swap them: x for data and z for the hidden variable. This lesson follows the slides in Chapters 3 to 8, and the notes in Chapter 9, where the board example comes from them. We say which each time.
A latent variable model has two parts. The first is a prior over the latent, P(x): how the hidden variable behaves before you see any data. It might be “usually near 0, rarely far away”. The second is the mapping P(y | x): given a value of the hidden variable, how the recorded data are produced. This is the same kind of box as an encoding model, with the hidden x in place of the stimulus.
The notes call such models doubly stochastic, meaning random twice. First, nature draws x from its prior. Second, nature draws y from P(y | x). Even if you knew x, y would still be noisy. And you do not know x. Both kinds of randomness sit in your data.
Multiplying the two parts gives the joint distribution, the probability of a hidden value and a recording together: P(y, x) = P(y | x) P(x). For neural data, y is a list of spike counts, one per neuron (a vector of length N), and x is a short list of hidden numbers (length d, often 1 to 10). A whole recording stacks T time bins: Y has shape N × T and the hidden trajectory X has shape d × T. With N = 40 and d = 2, the model explains 40 numbers per bin using 2.
With a known stimulus, one number answers the question “how well does this model explain the data?” You plug the real x into P(y | x). With a hidden x, you have no value to plug in. The notes give the fix: average over every x the prior allows, weighted by how likely each x is.
The device uses three neurons that respond to a hidden variable x with different preferences: one fires more as x rises, one fires less, one rises slowly. You see one recording of their spike counts. First pretend you know x. Then hide it.
The warm curve is P(y | x): how probable your recording is for each x. The purple dashed curve is the prior P(x). Choose whether x is known. Then press New recording to see another set of counts.
Illustrative toy: neuron rates are exp(1 + a · x) spikes per bin with a = 0.9, −0.7 and 0.5. The five recordings are fixed draws made at x of 1.2, −1, 0, 2 and −2. The prior is a standard normal, and P(y) is the area under the product of the two curves, computed on a grid.
In “known” mode, you read one number off the curve at your x. Slide it to the peak and the number is largest. In “hidden” mode, the shaded product of the two curves (drawn at its own height) has an area, and that area is the evidence. It is smaller than the peak of the warm curve, because most x values give the data a low probability, and the prior spreads its weight over all of them. That averaging is the cost of not knowing.
There is a tempting shortcut. Pick your best single guess for x, the peak of the warm curve, and treat it as known. The symptom is a flattering number. The probability at the peak is always larger than the evidence, because the evidence averages the peak with many worse values of x.
You can measure the gap in the device. Choose “x is known”, drag x to the top of the curve, and note the value. Switch to “x is hidden” and compare. The peak value overstates how well the model explains the data. Worse, a model with more hidden freedom has a taller peak, so comparing peaks always favours the more flexible model. The fix is the average: use the evidence for comparing models, and keep a whole distribution over x instead of one guess.
The simplest hidden variable takes only a few separate values. Think of a neuron that is either in a quiet state or an active state, with probabilities 0.6 and 0.4. Then the integral is a two-term sum: P(y) = 0.6 · P(y | quiet) + 0.4 · P(y | active). Chapter 9 works this exact case.
Chapter 4
See hidden trajectories pulled from a raster, then watch two unknowns teach each other
Slide 13 shows a raster, the standard picture of a population recording. Each row is one neuron. Each tick is one spike. Time runs left to right. The slide credits Jakob Macke and marks the data as simulated: 50 neurons, stretches of busy firing, stretches of quiet. At a glance it looks like static.
Slide 14 adds a second panel below the raster: “inferred latent variables”, two wavy lines called trajectories, one red and one blue. They rise and fall slowly. Compare them with the raster above and the bursts line up with the swings. Two slow curves explain what 50 jumpy rows cannot. That is the promise of the whole lecture: a small hidden signal behind a large noisy one.
Slide 15 gives the title “latent variable models = GLMs where we don’t know x”. Recall the GLM from earlier lectures: an input drives a nonlinear function, noise is added, and spikes come out. Now draw one hidden signal x feeding many such neurons. Each neuron has its own coupling, a number ci for how strongly it listens to x. Neuron i then fires with a rate that depends on ci · x(t), passed through a nonlinearity, plus its own Poisson noise.
The slide states the goal: “find shared structure underlying y”. It then names the difficulty: a chicken and egg problem. To find the couplings, you need the hidden signal. To find the hidden signal, you need the couplings. You have neither.
The usual escape is to take turns. Guess the couplings. Given that guess, find the best hidden signal. Given that signal, find better couplings. Repeat. Each half-step is an ordinary regression you already know, because with one unknown frozen the other is a plain least-squares fit.
Take the simplest version, with counts treated as numbers that a hidden signal scales up or down, plus noise: yit = ci xt + noise. With the couplings fixed, the best x at each time bin is a weighted average of the neurons’ counts: xt = Σi ci yit / Σi ci². With x fixed, the best coupling of neuron i is ci = Σt xt yit / Σt xt². In data-flow terms, the first update reads an N × T table, multiplies each row by its coupling and sums down the rows, giving T numbers. The second multiplies each row by the T numbers and sums along the row, giving N numbers.
A worked mini-case. Two neurons with couplings c = (2, 1) see counts (4, 3) in one time bin. Then x = (2·4 + 1·3) / (4 + 1) = 11/5 = 2.2. The louder neuron gets four times the vote of the quieter one, because its coupling squared is four times larger.
Top: the hidden signal (purple) and its current estimate (warm). Bottom: each neuron’s true coupling (purple) and estimate (warm). Press the two update buttons in turn, or run five rounds, and watch both estimates converge.
Simulated, seeded: 12 neurons over 60 time bins, y = coupling × signal + noise with noise spread 1.5. This is the plain-regression version, not a spiking model. After each signal update the signal is rescaled to unit spread, because x and the couplings can trade scale and sign freely: only the shape is recoverable.
At first the estimate is a flat line, because the couplings are random. After the first signal update the warm curve has the right rhythm, though a poor shape. Two or three rounds later it sits close to the purple one. Neither unknown was ever given. Each taught the other.
The symptom: your estimated couplings come out twice as large as the true ones, or with every sign flipped, even though the trajectory looks perfect. The measurement is a correlation, which ignores both scale and sign: the device reports an absolute correlation for exactly that reason. The cause is that x and c appear only as a product. Doubling x and halving every c leaves every prediction unchanged. The fix is to pin the scale by convention, here unit spread for x, which is what a standard-normal prior on x does in a full model.
A second symptom is a stuck fit: the turns stop improving at a poor answer. Taking turns climbs a hill and can stop on a low hill. The fix is to restart from several random couplings and keep the best likelihood.
Slide 16 lists three more latent variable problems in neuroscience. In spike sorting (electrophysiology), a probe hears several neurons at once, and the hidden variable is which neuron fired each spike. In calcium imaging, the hidden variables are each cell’s region of interest, its underlying spikes (deconvolution) and the separation of overlapping cells (demixing). In EEG, scalp electrodes record a mix of brain sources, and source separation recovers the sources. In each case the thing you want is the thing you did not measure.
Chapter 5
Count the hidden paths a spike train could have taken, and see how the count explodes with time
You have a recording and a model, and you want one number: how probable are these spikes under the model? Every fitting method needs that number, or its slope. With an ordinary encoding model the number is easy. With a hidden variable it is the hardest step of the whole job. Slide 17 says so in one line: hard to compute likelihood!
Slide 18 shows the sensory encoding model: a known stimulus x feeds the neuron and spikes y come out. For a Poisson GLM the log-likelihood is a plain sum over time bins: log P(Y | X) = Σt yt log λt − λt. Here yt is the spike count in bin t and λt is the model’s predicted rate. The slide notes that λt is a deterministic function of the stimulus and the parameters. So you evaluate one formula per bin and add. The cost grows in a straight line with T.
Slide 19 places a latent variable model beside it. The input x is now hidden, and the slide’s fitting formula is log P(Y) = log ∫ P(Y | X) P(X) dX. It adds, in red: requires an integral! Chapter 3 introduced this: you must average the mapping over every hidden value the prior allows.
For one hidden number the integral is a curve you can sample on a grid, as the Chapter 3 device did. The trouble starts when the hidden variable changes over time.
Slide 20 shows a latent dynamical model. The hidden state at time t, called xt, depends on the state one step earlier through a rule called the dynamics: p(xt | xt−1). Each hidden state produces an observation yt through the observation model: p(yt | xt). The slide then writes the likelihood: log P(Y) = log ∫ ∏t=1T p(yt | xt) p(xt | xt−1) dx1 dx2 … dxT, labelled a high-dimensional integral.
Why is it so bad? You integrate over the whole hidden path, x1 to xT, not one value. One second at 10 ms per bin is T = 100 bins. That is a 100-dimensional integral. A grid with just 10 points per dimension has 10100 cells. No computer can visit them.
Make the hidden variable discrete so the integral becomes a sum. A neuron is in a quiet state or an active state. In each 10 ms bin it spikes (y = 1) with probability 0.1 when quiet and 0.6 when active. It starts in either state with probability 0.5, and it stays in its state with probability 0.8 per bin. Observe two bins, both spikes: y = (1, 1).
List every hidden path and multiply along it: prior, spike, switch-or-stay, spike. Quiet then quiet: 0.5 × 0.1 × 0.8 × 0.1 = 0.004. Quiet then active: 0.5 × 0.1 × 0.2 × 0.6 = 0.006. Active then quiet: 0.5 × 0.6 × 0.2 × 0.1 = 0.006. Active then active: 0.5 × 0.6 × 0.8 × 0.6 = 0.144. The sum of the four paths is P(y) = 0.160.
Now a shortcut. Let αt(s) be the probability of the spikes so far and being in state s now. At t = 1: α(quiet) = 0.5 × 0.1 = 0.05 and α(active) = 0.5 × 0.6 = 0.30. At t = 2: α(quiet) = (0.05 × 0.8 + 0.30 × 0.2) × 0.1 = 0.010, and α(active) = (0.05 × 0.2 + 0.30 × 0.8) × 0.6 = 0.150. The sum is 0.160, the same number. Each step reused the last one instead of re-walking every path. This is the forward recursion of the hidden Markov model.
Each bar is one hidden path of a quiet or active neuron and the probability that it produced the spikes shown. Choose the number of time bins. Brute force must add every bar. The forward recursion reaches the same total with far fewer multiplications.
Illustrative toy: states quiet and active, spike probabilities 0.1 and 0.6, stay probability 0.8, start probability 0.5 each. Observed spikes: 0 0 1 1 1 0 1 0 1 1, cut to the chosen length. Multiplication counts: 2T − 1 for each path, and 2 + 6(T − 1) for the recursion.
Brute force grows by a factor of 2 for every extra bin, and the multiplications per path grow too. The recursion grows by a fixed amount per bin. At 10 bins the gap is already a factor of about 350. At the real scale of 100 bins with 10 states the paths number 10100, while the recursion needs roughly 10 × 10 × 100 = 10,000 steps.
The recursion works because of the chain structure and because the states are a short list. Two other cases also have formulas. If the dynamics and the observations are both linear and Gaussian, the integral can be done exactly, and the result is the Kalman filter (with the smoother for looking backwards). But a Poisson spike model with a continuous hidden path has no such formula. Then you must approximate, and Chapter 6 shows three ways.
Chapter 6
Compare sampling, expectation maximisation and variational inference, and see the bound that makes the last two work
Chapter 5 left you with an integral you cannot do. You still need to fit the model: choose its parameters θ so that it explains the spikes. Slide 21 lists three ways. Picture three hikers searching for the top of a foggy hill. One wanders randomly and keeps a diary of where she has been. One alternates between two simple moves. One builds a cheap map that always lies below the true hill, then climbs the map.
The slide calls it fully Bayesian inference, because it treats the parameters θ as unknown too, with their own prior. The target is the joint posterior P(x, θ | Y) over the hidden variables and the parameters. That joint is hard to draw from directly. Gibbs sampling avoids it by drawing one group of unknowns at a time, each from its own conditional distribution.
The recipe has two steps, repeated many times. Step one: freeze the parameters and draw the hidden variables from P(x | Y, θ). Step two: freeze the hidden variables and draw new parameters from P(θ | Y, x). The slide writes these as two lines with the iteration index (i) on each. Each conditional is usually easy, because with one side frozen the model looks like an ordinary regression. After many sweeps, the stream of draws behaves like draws from the joint. Their histogram is your answer, with honest error bars.
The second way keeps only a single best estimate of θ, not a full distribution. Expectation maximisation (EM) alternates two updates, as the slide says: update the posterior over the latents, then update the parameters. The first is the E-step (expectation): with θ fixed, compute P(x | Y, θ), which says how probable each hidden value is given the data. The second is the M-step (maximisation): with that posterior fixed, choose the θ that explains the data best, counting each hidden value in proportion to its posterior. Chapter 9 runs this loop on a real example, and the lesson on EM for Gaussian mixtures teaches it in depth.
The third way gives up on the exact answer and optimises a lower bound, a number guaranteed to sit at or below the true log-likelihood. Raising the bound pushes the truth up with it. The bound comes from one step of algebra. Pick any distribution q(x) over the hidden variable, called the variational distribution. Multiply and divide inside the sum.
The gap between the two sides has a name: it is the KL divergence from q to the true posterior P(x | y). So the bound touches the truth exactly when q is the true posterior. A worked case with two hidden values, quiet and active. The prior is 0.5 each. The recording has probability 0.1 under quiet and 0.4 under active. So P(y, quiet) = 0.05 and P(y, active) = 0.20, and P(y) = 0.25, with log P(y) = −1.386. The true posterior is (0.2, 0.8).
Try q = (0.5, 0.5). The bound is 0.5 · ln(0.05 / 0.5) + 0.5 · ln(0.20 / 0.5) = 0.5(−2.303) + 0.5(−0.916) = −1.609. That is below −1.386 by 0.223, which equals KL(q ‖ posterior). Now try q = (0.2, 0.8): the bound is 0.2 · ln(0.05 / 0.2) + 0.8 · ln(0.20 / 0.8) = −1.386, touching the truth.
The warm curve is the bound for every guess q. The dashed purple line is the true log P(y). Drag your guess for the probability of the active state. Press E-step to snap the guess to the exact posterior.
Illustrative toy numbers from the worked case: prior 0.5 each, data probability 0.1 under quiet and 0.4 under active. The bound is computed exactly in natural-log units (nats); the gap is the KL divergence from q to the posterior.
Only one guess touches the line. Every other guess leaves a gap. EM exploits this directly: its E-step sets q to the exact posterior, which closes the gap, and its M-step then raises the bound by changing θ. Each round can only move the likelihood up. Variational inference uses the same bound but restricts q to a simple family, so the gap never fully closes, and it trades some accuracy for speed.
Each method has its own symptom. Gibbs crawls when the latents and parameters are tightly linked: the chain moves in tiny steps, because each conditional barely moves from the last. Measure it with the correlation between successive draws, and fix it by drawing linked groups together. EM climbs and stops on a local peak: measure it by refitting from several random starts and comparing the final likelihoods, and keep the best. Variational inference tends to report too little uncertainty, because a simple q is narrower than the true posterior. Measure it against a long Gibbs run on a small problem.
Chapter 7
Choose a prior and a mapping, and watch familiar models fall out of the recipe
Suppose you want to build a model for a recording you do not understand yet. Where do you start? Slide 22 gives the answer in two lines. Every latent variable model is defined by two quantities. The first is the prior over the latent, P(x). The second is the mapping, P(y | x), the conditional probability of the data given the latent. Together they give the joint distribution: P(y, x) = P(y | x) P(x).
Slide 23 adds a detail that matters when you fit the model. Each part has its own knobs. The prior has parameters θx, and the mapping has parameters θy. So the full joint is P(y, x | θx, θy) = P(y | x, θy) P(x | θx). Fitting means finding both sets. Notice that the notes write one symbol θ for both together.
Slide 24 is a menu. Pick a kind of prior, pick a kind of mapping, and the pair has a name you may know already.
| Prior on the latent | Mapping to the data | Model | Where we teach it |
|---|---|---|---|
| Discrete | Gaussian | Mixture of Gaussians (“clustering”) | EM for Gaussian mixtures, Chapter 9 |
| Gaussian | Linear, Gaussian | Factor analysis (PCA is a special case) | PCA |
| Linear Gaussian dynamics | Linear, Gaussian | Linear dynamical system (“Kalman filter”) | Kalman filter |
| Discrete transitions | Any | Hidden Markov model (HMM) | Hidden Markov models |
Read each row as a story about spikes. A mixture of Gaussians: the brain is in one of a few discrete states, such as attending left or right, and each state produces a cloud of activity. Factor analysis: one smooth hidden number, like arousal, scales a whole pattern of firing. A linear dynamical system: the hidden state itself moves, following a fixed rule such as a rotation or a decay, and the recordings are noisy views of it. A hidden Markov model: the hidden state jumps between a few values, with a fixed chance of switching each bin.
A model is a recipe for making fake data. Run the recipe forward, and the model’s character is plain to see. The device below runs it for each of the four. Choose a model, then raise the mapping noise and watch the structure blur.
Pick a model. Blue dots are what you would record. Press Reveal the latent to colour the data by the hidden variable that made them. Raise the noise to make the hidden structure harder to see.
Toy models with made-up numbers. Mixture: 120 points, two clusters, each point drawn from one. Factor analysis: 120 points on a line set by one Gaussian latent. Dynamical system: 80 steps of a rotation by 0.18 radians with 0.985 decay, observed with noise. Hidden Markov: 60 bins, two states with means 2 and 8, switching with chance 0.1.
Compare the four in the observed space. The mixture makes blobs. Factor analysis makes a line. The dynamical system makes a spiral that a single rotation rule explains. The hidden Markov model makes a staircase of plateaus. A model you pick imposes its own shape. Fitting the model means finding the version of that shape that best matches your data.
The parameters θx and θy are real arrays, and counting them shows what fitting asks for. The mixture of Gaussians of Chapter 9 has θ = {p, μ0, C0, μ1, C1}. In two dimensions that is 1 + 2 + 3 + 2 + 3 = 11 numbers (a 2 × 2 covariance has three free entries). Factor analysis on N neurons with d hidden numbers learns an N × d loading matrix and N noise levels. A dynamical system adds a d × d matrix for the dynamics. A hidden Markov model with K states learns a K × K table of switching chances and the numbers inside each state’s mapping.
So the choice of family sets both the story and the size of the fitting problem. With 40 neurons and d = 2, factor analysis learns about 80 loadings plus 40 noise levels, fitted from thousands of bins. That is a well-posed job. The same family with d = 40 would have 1,600 loadings and far less data per number.
The symptom of a wrong choice is a fit that is confident but strange. Fit a two-cluster mixture to data that really lie along one continuous line, as in factor analysis with a strong latent. The clusters will cut the line in half and report two “states” that do not exist. The measurement is the log-likelihood on data you held out of the fit: the wrong family scores lower there than the right one. The fix is to change the prior or the mapping. This is why the recipe matters: swapping one part is a model-design decision, not a tuning detail.
Chapter 8
Turn a recording into a distribution over the hidden variable, then see why fitting needs that distribution
You have built a model. Now you want to use it. Slide 25 says there are two things we tend to want to do with a latent variable model. The notes call them the two key things. Imagine a decoding screen for a brain-computer interface. A person’s neurons stream spikes onto your screen. Job one: from this minute of spikes, what is the person’s hidden state right now? Job two: before any of that works, how did you learn what the hidden state does to the spikes?
The first job is inference, which the slide also calls recognition: infer the hidden variable xi from the observation yi. The answer is not one value. It is a distribution, the recognition distribution P(x | y), and Bayes’ rule produces it.
Chapter 6 gave the discrete case: P(quiet | y) = 0.05 / 0.25 = 0.2 and P(active | y) = 0.20 / 0.25 = 0.8. A continuous case with a closed form is also worth one line. Say the prior is a standard Gaussian, N(0, 1), and one neuron reads x with Gaussian noise of spread 1, so P(y | x) = N(y; x, 1). You observe y = 2. Add precisions (1 over variance): the prior gives 1, the data give 1, the total is 2. The posterior mean is (0 × 1 + 2 × 1) / 2 = 1, and the posterior variance is 1/2. The data pulled the belief halfway from the prior mean 0 toward the reading 2, and the spread shrank from 1 to 0.71.
The hidden variable x really has the value you set with the teal slider. Four neurons fire according to it. The purple dashed curve is the prior. The warm curve is the posterior after the bins you choose. Add bins and watch the belief sharpen around the truth.
Illustrative toy: four neurons with rates exp(0.5 + a · x) spikes per bin, a = 0.9, −0.7, 0.5 and 0.3. Counts are fixed random draws scaled to the true x and the number of bins; the prior is standard normal; the posterior is computed on a grid with Bayes’ rule and the exact Poisson likelihood.
Drag “bins observed” from 1 to 40. With one bin the posterior is almost as wide as the prior, because a handful of spikes says little. With 40 it is a narrow peak at about the true value. Now drag the true x. The peak follows it, and that is decoding.
The second job is fitting: inferring the parameters θ = {θx, θy} from the dataset {yi}, i = 1 to N. Maximum likelihood chooses θ to make the data most probable. The slide writes it in two lines: θ̂ML = arg maxθ log P(Y | θ) = arg maxθ log ∫ P(Y, X | θ) dX. The second line is the Chapter 5 integral: the likelihood of the data with every hidden variable averaged away.
In data-flow terms, inference maps a recording Y (N × T) to a posterior over X (d × T means plus their spreads). Fitting maps a whole dataset to the numbers in θ. They depend on each other. Inference needs θ, because it needs P(y | x). Fitting needs inference, because the likelihood averages over X. That loop is exactly what EM from Chapter 6 resolves: infer with the current θ, refit θ with that inference, and repeat.
In practice the two jobs run at different times. Job 2 happens once, offline: you record a long session, fit θ with EM, and save it. Job 1 happens many times, online: with θ frozen, each new bin of spikes updates the posterior over x, and the answer streams out. For the linear Gaussian models of Chapter 7, that online update is the Kalman filter, and it costs a fixed few matrix multiplications per bin. For other models, the update is an approximation.
This split also tells you where errors come from. If decoding is poor, ask which job failed. Did the fit land on a bad θ (a local peak, too little data), or is the inference approximate (a loose bound, a non-Gaussian posterior squeezed into a Gaussian)? The two have different fixes, and the device above shows the second kind: the width of the posterior changes with the evidence even when θ is perfect.
The symptom: the posterior is tight but wrong, with its peak far from the hidden value. This happens when the mapping inside your model is wrong. A narrow posterior only shows that the model is sure, and the data had no say if the model was a poor description. The measurement is a calibration check on held-out recordings: if 95% intervals contain the truth only 60% of the time, the model is overconfident. The fix is to repair the mapping, for example with a richer nonlinearity or more hidden dimensions, before trusting any one posterior.
Chapter 9
Take the simplest hidden-variable model, write every formula, and fit it by taking turns
Slide 26 is nearly blank: “example model: binary mixture of Gaussians (on board)”. Professor Pillow worked it on the board, and the lecture notes (section 3) carry the same derivation. This chapter rebuilds it, with spikes. Here the notes’ letters apply: x is the observed data, z is the hidden variable.
The scene. You count a neuron’s spikes on 90 trials. The histogram has two humps, one near 4 spikes and one near 11. It looks as if the neuron has two modes of operation, but you did not record which mode each trial was in. The hidden variable is that mode.
The notes define it in two lines. The hidden variable is a coin flip: z ~ Ber(p). Bernoulli means z is 1 with probability p and 0 with probability 1 − p. Given z, the data are Gaussian: x | z ~ N(μ0, C0) if z = 0, and x | z ~ N(μ1, C1) if z = 1. A Gaussian is the bell curve with a centre μ and a variance C (in one dimension, a single number). The parameters are θ = {p, μ0, C0, μ1, C1}.
Inference is Bayes’ rule, because with two values the sum has two terms. Write N0(x) and N1(x) for the two bell curves evaluated at the data point x.
For a whole dataset the likelihood is a product of such terms, one per trial, because each trial draws its own z. Taking logs turns the product into a sum: log P(X | θ) = Σi=1N log[(1 − p) N0(xi) + p N1(xi)]. The notes observe that you could code this sum and hand it to a numerical optimiser. EM is an alternative that uses the structure instead.
Take p = 0.5, state 0 with mean 4 and spread 1, and state 1 with mean 10 and spread 2. A trial shows x = 5 spikes. Evaluate the bell curves: N0(5) = 0.3989 × e−0.5 = 0.2420, and N1(5) = (0.3989 / 2) × e−3.125 = 0.00877. The likelihood of the point is 0.5 × 0.2420 + 0.5 × 0.00877 = 0.1254. The responsibility of state 1 is 0.00877 / (0.2420 + 0.00877) = 0.035. A trial of 5 spikes is almost surely from the low mode.
The E-step computes the responsibility ri = P(z = 1 | xi) for every trial, using the current θ. The M-step refits θ with weighted versions of the usual formulas. It counts trial i as ri parts state 1 and 1 − ri parts state 0. The new values are: p = mean of ri; μ1 = Σ ri xi / Σ ri; C1 = Σ ri (xi − μ1)² / Σ ri; and the same for state 0 with weights 1 − ri.
A three-trial check. Counts x = (3, 5, 11) with responsibilities r = (0.01, 0.04, 0.98). Then p = 1.03 / 3 = 0.343. The state-1 mean is (0.03 + 0.20 + 10.78) / 1.03 = 10.69. The state-0 weights are (0.99, 0.96, 0.02), which sum to 1.97, so μ0 = (2.97 + 4.80 + 0.22) / 1.97 = 4.06. The one high count dragged state 1 up and the two low counts set state 0.
Blue bars are 90 simulated trial counts. Purple curves are the two states; the warm curve is the mixture. Dots below show each trial’s responsibility: solid means state 1, faint means state 0. Press E-step, then M-step, or run several rounds. Change the starting point to see a failure.
Simulated, seeded: 90 counts, 45% from a Gaussian with mean 11 and spread 2, the rest with mean 4 and spread 1.2, clipped at 0. Counts are treated as Gaussian for the lesson’s sake. Starts: near uses means 6.5 and 8.5, symmetric uses 8 and 8, wide uses 2 and 14, all with spread 3 and p = 0.5.
From the near start, a few rounds find the two humps. The log-likelihood in the lower panel never goes down, as the Chapter 6 bound promised. The means settle near 4 and 11, the values that made the data, and the high-state weight lands near 40%, close to the 45% used to generate it. Nothing told the model where the humps were.
Two failures matter. First, the symmetric start. If both components begin with the same mean and spread, every trial gets responsibility exactly 0.5, the M-step makes both components identical again, and the likelihood never moves. The symptom is a flat trace; the measurement is the gap between the two means, which stays zero; the fix is to break the symmetry with different starts, or a quick clustering of the data first. Second, variance collapse. A component can shrink onto a single data point, its spread falling toward zero, and the likelihood climbs without bound. Measure the smallest spread across components. Fix it with a floor on the variance or a prior on it.
The lesson on EM for Gaussian mixtures goes deeper on both, and on choosing the number of components.
Chapter 10
Keep the numbers, terms, checklist and code, and see where to go next
The whole lecture in one paragraph. A regression model explains spikes from a known stimulus. When no stimulus is known, a latent variable model explains them from a hidden variable x with a prior P(x) and a mapping P(y | x). The probability of the data is an integral of their product over every hidden value, which is easy only when the hidden variable has few values or the model is linear and Gaussian. Otherwise you fit by sampling (Gibbs), by expectation maximisation, or by variational inference. Two jobs follow: infer P(x | y) with the parameters fixed, and fit the parameters by maximising the evidence. The binary mixture of Gaussians shows every piece in miniature.
| Quantity | Value | Where it came from |
|---|---|---|
| Laplace posterior, three trials | mean 0.69, spread 1.22 | Chapter 1: two spikes in three trials at strength 1, curvature −0.667 |
| Evidence by Laplace | 0.0455 against 0.05 exact | Chapter 1: 9% low, with a flat prior of width 10 |
| Fano factor of the counts | 2.5 (variance 12.0, mean 4.8) | Chapter 2: a Poisson has exactly 1 |
| Posterior, two hidden values | (0.2, 0.8), P(y) = 0.25 | Chapters 6 and 8: 0.05 and 0.20 over 0.25 |
| Paths in a two-state chain | 2T; 1,024 at T = 10 | Chapter 5: 19,456 multiplications against 56 |
| Lower bound, worst guess | −1.609 against −1.386 | Chapter 6: gap 0.223 nats, the KL divergence |
| Gaussian posterior | mean 1, variance 0.5 | Chapter 8: prior N(0, 1), reading 2, noise spread 1 |
| Responsibility at 5 spikes | 0.035 for the high state | Chapter 9: likelihood 0.1254 |
| Term | Meaning |
|---|---|
| Latent variable | A variable posited to exist behind the data and never observed. Also called hidden. |
| Doubly stochastic | Random twice: noise in the latent, then noise in the mapping from latent to data. |
| Prior over the latent | P(x): what the hidden variable does before seeing data. |
| Mapping | P(y | x): how data arise from a hidden value. |
| Marginal likelihood | P(y): the integral (or sum) of P(y | x) P(x) over x. Also called the evidence. |
| Recognition distribution | P(x | y) by Bayes’ rule: the posterior over the hidden variable. |
| Fitting | Choosing θ to maximise log P(Y | θ), the log of an integral. |
| Gibbs, EM, variational | Sampling each unknown in turn; alternating posterior and parameter updates; optimising a lower bound. |
This is the binary mixture of Gaussians from Chapter 9 in about twenty lines. Each step maps to a formula above. x is a vector of N spike counts.
pythonimport numpy as np def npdf(x, m, s): return np.exp(-0.5 * ((x - m) / s) ** 2) / (s * np.sqrt(2 * np.pi)) def em_binary_mog(x, iters=50, seed=0): """z ~ Bernoulli(p), x | z ~ Normal(m_z, s_z). x has shape (N,). State labels can come out swapped.""" rng = np.random.default_rng(seed) p = 0.5 m0, m1 = rng.choice(x, 2, replace=False) # different starts break the symmetry s0 = s1 = x.std() for _ in range(iters): a = (1 - p) * npdf(x, m0, s0) # E-step: prior times bell curve, per state b = p * npdf(x, m1, s1) r = b / (a + b) # responsibility of state 1, shape (N,) p = r.mean() # M-step: responsibility-weighted formulas m1 = (r * x).sum() / r.sum() m0 = ((1 - r) * x).sum() / (1 - r).sum() s1 = max(0.3, np.sqrt((r * (x - m1) ** 2).sum() / r.sum())) # floor stops variance collapse s0 = max(0.3, np.sqrt(((1 - r) * (x - m0) ** 2).sum() / (1 - r).sum())) loglik = np.log((1 - p) * npdf(x, m0, s0) + p * npdf(x, m1, s1)).sum() return p, (m0, s0), (m1, s1), loglik
Latent variable models are the shared language of population neuroscience. Each family in Chapter 7 is a lesson of its own: PCA, EM for Gaussian mixtures, the Kalman filter with its smoother, and hidden Markov models. The Poisson spiking layer on top is the generalised linear model. The approximation tools are taught in Monte Carlo and importance sampling. The next lecture of this course, Lecture 16, goes deeper on EM.
This lesson follows Lecture 15 of Princeton NEU 560, Statistical Modeling and Analysis of Neural Data (Spring 2024), taught by Jonathan Pillow: the slides and the lecture notes on latent variable models. The simulated raster and inferred trajectories on slides 13 to 15 are credited there to Jakob Macke. All devices here, and every number in them, are our own constructions, and each says in its fine print what is simulated. The course is at pillowlab.princeton.edu/teaching/statneuro2024.
Now press Present or Teach and explain the model from memory: what the hidden variable is, why the likelihood is an integral, and how EM takes turns. Then go back to the hidden-driver instrument and press 40 neurons again.