Latent Variable Models

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.

Recover the hidden driver

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

Why We Need a Variable Nobody Measured

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.

What the earlier lectures built

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.

The first fingerprint: shared variability

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.

Turn up the shared gain

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.

0.60

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.

Why this matters for a model

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 road

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.

  1. Laplace warmup: approximate a posterior with a Gaussian for a Bernoulli GLM.
  2. Likelihood, KL and kernels: maximum likelihood as closeness, plus nonlinear regression.
  3. From stimulus to hidden variable: what changes when x is unknown.
  4. Neural examples: latent trajectories, the chicken and egg problem, spike sorting.
  5. Why the likelihood is hard: an integral over everything hidden.
  6. Three ways to fit: Gibbs sampling, EM and variational inference.
  7. Prior plus mapping: the recipe, and the model zoo it produces.
  8. Inference and fitting: the two jobs, Bayes rule and the integral.
  9. The binary mixture of Gaussians: worked by hand and by EM.
  10. The field guide: numbers, terms, code and links onward.
Two neurons receive the identical stimulus on every trial, yet their trial-by-trial spike counts correlate at 0.5. What is the most direct explanation?

Chapter 1

Warmup: A Gaussian Stand-In for a Posterior

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 warmup, step by step

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.

∂L/∂w
The slope of the log-likelihood. At the best w the slope is zero.
x · (y − f(xw))
Input times the miss: the real outcome y minus the predicted probability. It says “push w up when the model under-predicts spikes”.
∂²L/∂w²
The curvature: how sharply the log-likelihood bends at its peak. Always negative here, so there is one peak.
−x² f(1 − f)
Curvature is large when x is large and when the spike probability f is near one half. It shrinks when f is near 0 or 1.

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 Laplace recipe

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ŵ))).

One worked example, every step

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.

Fit a Gaussian to the posterior

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.

10

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.

When the approximation misleads

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 practice quiz, answered

The slides close the warmup with five questions, each with a short answer. Read them as a checklist for Bayesian regression.

  1. The MAP estimate. Maximise the log-likelihood plus the log-prior over w.
  2. The posterior P(w | Y, X). Apply Bayes rule: likelihood times prior, divided by a normaliser called the evidence.
  3. The evidence, or marginal likelihood. It is the integral of likelihood times prior over every w: P(Y | X) = ∫ P(Y | X, w) P(w) dw.
  4. The Laplace approximation for a non-Gaussian model. Find ŵmap, compute the Hessian H there, and use the Gaussian with mean ŵmap and covariance −H−1.
  5. The evidence from Laplace. Take likelihood times prior at ŵmap, then divide by the Gaussian’s own height there.

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.

In the Laplace approximation, what sets the width of the Gaussian that replaces the posterior?

Chapter 2

Loose Ends from Regression: Likelihood as Closeness, Kernels, Priors

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.

Loose end 1: maximum likelihood is a search for closeness

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.

DKL(Ptrue ‖ Pθ)
How far the model is from the truth. This is the score we would like to minimise, but we cannot compute it: Ptrue is unknown.
Σ Ptrue log Ptrue
Minus the entropy H of the true source. It does not contain θ, so no choice of model changes it.
Σ Ptrue log Pθ
The average of the model’s log-probability, weighted by how often each count really occurs.
(1/N) Σ log Pθ(xi)
The same average, estimated from N real samples. This is just the average log-likelihood, which we can compute.

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.

Slide the model toward the data

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.

2.0

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.

Loose end 2: kernels and Gaussian processes

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.

Loose ends 3 and 4: other priors and other approximations

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.

When the best model is still wrong

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.

Why can we minimise DKL(Ptrue ‖ Pθ) without knowing Ptrue?

Chapter 3

From a Known Stimulus to a Hidden Variable

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.

Two ingredients, two stages of noise

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.

What you can still compute, and what you cannot

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.

P(y)
The probability of the recording, with the hidden variable averaged out. It is called the marginal likelihood or the evidence.
P(y | x)
The mapping: how probable the recording is if the hidden variable has this exact value.
P(x)
The prior: how plausible that hidden value was before seeing the recording.
Σ over x1 to xm
The same average when the hidden variable takes only m separate values, such as “state A or state B”. An integral becomes a sum.

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.

Know x, or average over 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.

1.2

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.

The shortcut that fails: plug in a guess

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.

A latent variable model gives P(y | x) and P(x). How do you get the probability of the recording y itself?

Chapter 4

Latent Variables in Neural Data: Trajectories and a Chicken and Egg Problem

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.

The model behind the picture

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.

Breaking the circle by taking turns

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.

Take turns: signal, then couplings

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.

What can go wrong

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.

The same idea, other signals

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.

Why is finding both the couplings and the hidden signal called a chicken and egg problem?

Chapter 5

Why the Likelihood Is Hard to Compute

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!

The easy case: no hidden variable

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.

The hard case: add a hidden variable

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.

The worst case: a hidden path

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.

A case small enough to count by hand

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.

Count the paths, then skip them

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.

When the shortcut does not exist

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.

A recording has T time bins and a hidden state with K possible values at each bin. How does the number of hidden paths scale?

Chapter 6

Three Ways to Fit a Model with Hidden Variables

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.

Way 1: sampling, the fully Bayesian route

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.

Way 2: expectation maximisation

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.

Way 3: variational inference and its bound

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.

log P(y)
The quantity we want and cannot compute: the log of the evidence.
q(x)
Any distribution you choose over the hidden variable. It is a guess at the posterior.
P(y, x) / q(x)
The joint probability, reweighted by the guess. Averaging it under q gives back P(y) exactly.
Σ q log [P(y,x)/q]
The bound. It uses Jensen’s inequality: the log of an average is at least the average of the logs. The right side is easy to compute.

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.

Raise the bound

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.

0.50

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.

Where each one breaks

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.

In the worked case, why does q = (0.2, 0.8) give a bound exactly equal to log P(y)?

Chapter 7

Prior Plus Mapping: One Recipe, Four Famous Models

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.

The menu on slide 24

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 latentMapping to the dataModelWhere we teach it
DiscreteGaussianMixture of Gaussians (“clustering”)EM for Gaussian mixtures, Chapter 9
GaussianLinear, GaussianFactor analysis (PCA is a special case)PCA
Linear Gaussian dynamicsLinear, GaussianLinear dynamical system (“Kalman filter”)Kalman filter
Discrete transitionsAnyHidden 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.

See each one generate data

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.

Run the recipe forward

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.

0.50

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.

What each family has to learn

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.

Choosing the wrong family

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.

You believe a neuron population switches between a quiet and an active state at random times, and you record spike counts. Which prior and mapping describe it?

Chapter 8

The Two Jobs: Inferring the Hidden Variable and Fitting the Model

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?

Job 1: inference, also called recognition

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.

P(x | y)
The posterior: your belief about the hidden variable after seeing the recording.
P(y | x)
The mapping: how likely this recording is for each hidden value.
P(x)
The prior: your belief before seeing the recording.
P(y)
The evidence from Chapter 3. It rescales the top so the answer adds up to 1.

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.

Watch the posterior narrow

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.

1.0
3

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.

Job 2: fitting the parameters

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.

Offline fitting, online inference

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.

When inference misleads

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.

Which statement correctly separates the two jobs?

Chapter 9

The Binary Mixture of Gaussians, Worked by Hand and by EM

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 model, symbol by symbol

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.

P(z=1 | x)
The responsibility of state 1 for this data point: the probability that the neuron was in mode 1 on this trial. State 0 gets 1 minus it.
p N1(x)
The prior chance of state 1, times how well state 1’s bell curve explains x.
(1 − p) N0(x) + p N1(x)
The same product summed over both states. It is the likelihood of this point, P(x | θ), and it rescales the top to a probability.

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.

One data point, every number

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.

EM: the two steps

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.

Fit the two humps by taking turns

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.

What can go wrong

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.

In the M-step, how is the state-1 mean μ1 computed?

Chapter 10

Field Guide: Latent Variable Models on One Page

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.

The numbers to remember

QuantityValueWhere it came from
Laplace posterior, three trialsmean 0.69, spread 1.22Chapter 1: two spikes in three trials at strength 1, curvature −0.667
Evidence by Laplace0.0455 against 0.05 exactChapter 1: 9% low, with a flat prior of width 10
Fano factor of the counts2.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.25Chapters 6 and 8: 0.05 and 0.20 over 0.25
Paths in a two-state chain2T; 1,024 at T = 10Chapter 5: 19,456 multiplications against 56
Lower bound, worst guess−1.609 against −1.386Chapter 6: gap 0.223 nats, the KL divergence
Gaussian posteriormean 1, variance 0.5Chapter 8: prior N(0, 1), reading 2, noise spread 1
Responsibility at 5 spikes0.035 for the high stateChapter 9: likelihood 0.1254

The terms, in the lecture’s own words

TermMeaning
Latent variableA variable posited to exist behind the data and never observed. Also called hidden.
Doubly stochasticRandom twice: noise in the latent, then noise in the mapping from latent to data.
Prior over the latentP(x): what the hidden variable does before seeing data.
MappingP(y | x): how data arise from a hidden value.
Marginal likelihoodP(y): the integral (or sum) of P(y | x) P(x) over x. Also called the evidence.
Recognition distributionP(x | y) by Bayes’ rule: the posterior over the hidden variable.
FittingChoosing θ to maximise log P(Y | θ), the log of an integral.
Gibbs, EM, variationalSampling each unknown in turn; alternating posterior and parameter updates; optimising a lower bound.

Checklist before you fit one

The core as code

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

Where it sits in the field

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.

The takeaway. A latent variable model explains many noisy things with one hidden thing. The price is an integral over everything hidden. Every fitting method in this lecture is a way to pay that price in instalments.

Credit and sources

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.

NEU 560 Lecture 15: Latent Variable Models
The course site · Back to Gleams