Neural Latent Time Series Models

Hundreds of neurons fire, yet a few hidden numbers steer them all. Give a model only the spikes and it can recover that hidden path.

Learn the family of models that turn raw spike trains into a few smooth, readable variables, and learn how to pick one for your own data.

Switch between what the electrodes record and what a model infers. Then add neurons and watch the guess close in on the hidden path. After that we build every model in the lecture's survey, piece by piece.

You need a feel for what a spike train is (a list of times when one neuron fired) and a little algebra. We build the rest from zero.

Based on Lecture 23 of Princeton NEU 560: Statistical Modeling and Analysis of Neural Data (Spring 2024), taught by Jonathan Pillow. Every idea is re-taught here in our own words and devices; the lecture slides (PDF) are on the course site. It sits on the BCI latent variable models lesson.

Recover the hidden path

8

Illustrative toy: one hidden path, neurons with bump-shaped tuning curves, Poisson spikes, all seeded so they are the same on every visit. The estimate is the simple maximum-likelihood decoder (it knows each tuning curve) smoothed over 5 time bins, a stand-in for the lecture's fitted models. Error is the root-mean-square gap in units of the path's full range.

Chapter 0

Why Spikes Need a Hidden Story

See why a wall of spikes from a hundred neurons is really the shadow of a few hidden numbers, and run the last quiz on the way in

Picture a rat running along a track. An electrode array records 100 neurons for ten seconds. You plot the result as a raster: one row for each neuron, one tick for each spike, time along the bottom. It looks like static on an old television.

Yet the rat is doing very little. It is somewhere on the track, moving at some speed, in some mood. A handful of numbers describes the whole scene. The hundred rows are a noisy, scrambled copy of those few numbers.

That is the central bet of this lecture. A latent variable is a number you never measure but believe exists, like the true temperature behind a flickering thermometer. A latent time series is that hidden number as it changes from moment to moment. The lecture surveys the models that recover it from spikes alone.

Why bother

There are three reasons, and each matches a goal of the survey. The first is denoising: one spike train is a very noisy glimpse of a neuron’s rate, but a hundred of them share one cause, so you can average the noise away. The second is compression: ten seconds of 100 neurons in 50 ms bins is a table of 100 by 200 counts, while a three-number latent path is three by 200.

The third is interpretation. A path that rotates, or switches between two modes, or drifts toward a bound, tells you something about the computation. The lecture lists this as one of three goals for new methods: do the fits tell us something meaningful?

The story every model tells

Every model in the lecture tells the same two-part story. First, the hidden path x(t) evolves by some rule. Second, each neuron’s spikes y(t) are drawn from a rate that depends on the path. The models differ only in which rule and which mapping they pick. Chapter 4 lays out all the choices on one grid.

The hero above uses the simplest mapping: each neuron likes one place on the path, and fires more when the path is near that place. That bump of preference is a tuning curve. With the curves known, a decoder can guess the path from the spikes. Real models must also learn the curves and the rule, and that is the harder job.

A lecture that opens with a quiz

This is Lecture 23 of Jonathan Pillow’s Spring 2024 course, taught near the end of the term. It opens with the course’s final practice quiz, on the models met earlier in class. The quiz is a useful map of what you need before the survey, so here it is as flash cards. Try to answer in your head, then reveal.

Answer the practice quiz

Read the question, say your answer, then press Reveal. Mark whether you knew it. Chapters 1 and 2 teach every answer.

The eight questions and answers are the lecture’s own (slides 2 and 3). The score lives only in this page and is not saved.

Here are the answers in plain words. The EM algorithm for a hidden Markov model (HMM) is called Baum-Welch. Its E step is the forward-backward algorithm. For a linear dynamical system (LDS) the E step is the Kalman filter-smoother: the forward half is the filter, the backward half is the smoother.

The forward pass of forward-backward has two steps, predict then update. The Kalman filter has the same two steps. You will see why in Chapter 1.

Where the system settles

Questions 7 and 8 ask where each model settles if you run it for a long time. For an HMM the answer is the top left eigenvector of the transition matrix A, renormalised so the entries add to 1. A two-state example with stay-probabilities 0.9 and 0.8 gives long-run shares of 2/3 and 1/3. Check: the flow from state 1 to 2 is (2/3)(0.1) = 0.067, and the flow back is (1/3)(0.2) = 0.067. They balance.

For an LDS the answer is a Gaussian, x ~ N(0, P), where P solves the discrete-time Lyapunov equation.

P
The long-run spread of the hidden state: how far it wanders from zero once the start is forgotten.
A P A⊤
The spread left over after one step of the dynamics. The matrix A shrinks or rotates the cloud.
Q
The fresh noise added at each step. Spread settles where what is kept equals what is added.

one dimension, A = 0.9, Q = 0.1: P = 0.1 / (1 − 0.81) = 0.526 (spread 0.73)

In one dimension A and P are plain numbers, so the equation says P = a²P + q. Solve it: P = q / (1 − a²). The pull toward zero (a = 0.9) keeps the state near home, and the noise keeps kicking it out. The balance is a spread of 0.73.

Course admin, in one paragraph

The slide lists three tasks: fill out the course evaluation, sign up for a one-on-one meeting about the final project, and vote on a date and time for the final project talks. Nothing here changes the science, so we move on.

The road

The survey has one clear arc. It reviews the linear model and how to fit it, adds switches, lays every model out on a grid, studies three models in depth, shows how familiar methods are special cases, and ends with models of many brain regions.

  1. Inferring the hidden path: the Kalman filter and smoother, step by step.
  2. Fitting the model: the M step and the full EM loop.
  3. Switching dynamics: discrete modes, recurrence, and decisions.
  4. The menagerie: one grid for every model in the survey.
  5. Nonlinear spikes: linear dynamics with a nonlinear readout, and smooth latents.
  6. Latent manifold tuning: when the hidden path lives on a curved surface.
  7. Old methods as special cases: DMD, jPCA, communication subspaces.
  8. Many brain regions: coupled latents and switching coupling.
  9. Choosing a model: flexibility, fittability, interpretability.
  10. Field guide: numbers, checklist, code and links onward.
A 100-neuron recording looks like static, yet a three-number latent path fits it well. What does that tell you?

Chapter 1

Inferring the Hidden Path

Follow the Kalman filter as it predicts, updates and then looks backward, and learn what the gain tells you about trust

You track a drifting signal in the brain, say the slow shift in a population’s overall activity during a task. Your sensor reads it once per time bin, but the reading is noisy. Your physics is also loose: you know the signal tends to stay where it was, and you know it wanders a little.

Neither source alone is reliable. The Kalman filter combines them in the best possible way when the noise is Gaussian. The lecture opens its review of the linear dynamical system (LDS) with this E step, the step that infers the hidden path.

The model in two lines

An LDS says two things. The hidden state xt moves by a linear rule plus noise. The measurement yt reads the state through a linear map plus noise. The lecture draws this as a chain of circles with arrows, one chain for the latents and one row for the observations.

xt = A xt−1 + B ut + εt
The dynamics equation. A is the dynamics matrix, B weighs an optional input u, and ε is dynamics noise with covariance Q.
yt = C xt + ηt
The observation equation. C is the observation matrix that maps a few latents to many neurons, and η is observation noise with covariance R.

The parameters are θ = {A, C, Q, R}, plus B when you have inputs. The latents are low-dimensional, say three numbers. The observations yt are the neural data, say 100 numbers per bin. So C is a 100 by 3 matrix: three hidden numbers fan out to a hundred neurons.

Step one: predict

Suppose that after bin t you hold a belief about the state: a bell curve with mean μt and variance Pt. To look one bin ahead, push the whole bell curve through the dynamics. The mean moves to Aμt. The variance becomes A Pt A⊤ + Q, because the rule stretches the curve and the noise widens it. This is the predict step. The slide writes it as a Gaussian, N(Aμt, APtA⊤ + Q).

Step two: update

Now bin t+1 arrives with a reading yt+1. Multiply the predicted bell curve by the likelihood of that reading, which is how well each possible state explains it. This is Bayes’ rule, and the slide marks it so. The product of two Gaussians is another Gaussian, so the belief stays a bell curve. This is the update step.

In one dimension with C = 1 the arithmetic is short. Let the predicted variance be P− and the observation variance be R.

K
The Kalman gain, a number from 0 to 1. It is a trust slider: near 1 you trust the new reading, near 0 you trust your prediction.
μ = μ− + K (y − μ−)
The new mean. It starts at the prediction and moves a fraction K of the way toward the reading. The gap y − μ− is the innovation.
P = (1 − K) P−
The new variance. It always shrinks, because a reading adds information.

a = 0.9, μ = 1, P = 0.5, Q = 0.1, R = 0.5, y = 2: μ− = 0.9, P− = 0.81 × 0.5 + 0.1 = 0.505, K = 0.505 / 1.005 = 0.502, μ = 0.9 + 0.502 × 1.1 = 1.453, P = 0.251 (the toy numbers are illustrative)

The belief moved from 0.9 to 1.45, a little over half the way to the reading of 2, because the prediction and the reading were about equally trustworthy. Its variance dropped from 0.505 to 0.251, about half. Repeat predict and update along the whole recording and you have the forward pass, which is exactly the Kalman filter.

Try it yourself

The device below holds a hidden path and a noisy reading of it, both fixed. The truth has dynamics noise Q = 0.04 and reading noise R = 0.5. You set the numbers the filter believes. Believe the readings are too clean and the estimate chases noise. Believe the dynamics are too jumpy and it does the same. Believe the dynamics are too rigid and it lags.

Trust the model or the reading

Purple is the true hidden path. Blue dots are the noisy readings. The warm line is the estimate and its shaded band is two standard deviations. Move the two sliders, then switch on the smoother.

0.04
0.50

Illustrative toy: one-dimensional LDS with A = 0.95, C = 1, true Q = 0.04, true R = 0.5, 120 time bins, seeded. The sliders are logarithmic. The filter and smoother are the exact scalar Kalman and Rauch-Tung-Striebel recursions run live; error is the root-mean-square gap to the true path.

Near the true values the error is lowest. Slide R toward 0.1 and the error rises, because the filter treats noise as signal. The innovation, the gap between the reading and the prediction, is the number to watch: if your model is right, innovations look like noise with no pattern.

The backward pass

The filter at time t has seen only readings up to t. But in an offline analysis you hold the whole recording. A later reading says something about earlier states too: if the signal jumps up at bin 60, bin 59 was probably already rising. The Kalman smoother runs backward from the last bin and corrects each belief with the future. The smoother returns the belief given all the readings, P(xt | y1:T), instead of only those up to bin t, P(xt | y1:t).

Together the filter and smoother are the E step of EM for an LDS. Our Kalman filter lesson derives the filter in depth, and the smoothing lesson derives the backward pass. For a hidden Markov model the same two-pass idea is the forward-backward algorithm.

In a Kalman update the predicted variance is 0.5 and the observation variance is 0.5. What is the gain, and what does it mean?

Chapter 2

Fitting the Model: the M Step and EM

Learn A, Q and R from spikes alone by alternating a guess about the hidden path with a refit of the rules

Chapter 1 assumed you knew the rules: the dynamics A, the noise Q and R. In a real experiment you know none of them. You have only the readings. And you cannot fit the rules without the hidden path, nor find the path without the rules.

This is a chicken-and-egg problem. The way out is to take turns. Guess the rules, infer the path, then refit the rules as if the inferred path were the truth, and repeat. That loop is EM, short for expectation-maximisation. The inference half is the E step from Chapter 1. This chapter is the other half, the M step.

What the M step maximises

Imagine you could see the hidden path as well as the readings. Fitting would be easy: it would be two ordinary regressions. The probability of the path and readings together is the complete-data likelihood. Its log splits cleanly into three kinds of terms, and the lecture writes them out.

The first term scores the starting state. The second scores each step of the dynamics: how well A xt−1 predicts xt, with noise Q. The third scores each reading: how well C xt predicts yt, with noise R.

The path is hidden, so we cannot compute these scores. The E step hands us the next best thing: for each bin, the smoothed mean mt and variance Σt. The M step takes the expected complete-data log-likelihood under that belief and maximises it. The lecture titles this: update the parameters (A, C, Q, R) by maximising expected complete-data log-likelihood.

Why the uncertainty enters

Look at what a squared term needs. The dynamics score contains xt2. Its expected value is not the mean squared. It is E[xt2] = mt2 + Σt. The extra Σt is the variance of the belief. The slide gathers these into the “relevant moments”: sums of m m⊤ + Σ, of mt mt−1⊤ + Σt,t−1, and of y y⊤.

Set the derivative of the expected score to zero and the answers come out in closed form. Here they are for one hidden number with C = 1, so you can see every piece. The matrix versions on the slide have the same shape.

A
A regression slope: how much of the last state survives into the next. The sums run over bins, with expectations from the smoother.
Q
The average squared gap between the next state and A times the last one. It is the leftover the dynamics cannot explain.
R
The average squared gap between the reading and the state. It is the leftover that the observation cannot explain.

For the full matrix case the lecture also gives C: it is a regression of the readings on the smoothed means, (Σ y m⊤)(Σ (m m⊤ + Σ))−1. In words, C is the least-squares map from three latents to a hundred neurons.

The full loop, with numbers

One EM round on a recording of 300 bins goes like this. Run the Kalman filter and smoother with the current A, Q and R. For each bin collect mt, Σt and the cross term. Plug them into the three formulas. You now hold new A, Q and R. Repeat. EM has a guarantee: each round never lowers the likelihood of the readings.

The device runs this loop for real. It starts from a poor guess (A = 0.3, Q = 1, R = 1) and the data come from A = 0.9, Q = 0.3, R = 0.2. Press Run 10 rounds and watch the log-likelihood climb and the three estimates settle on the truth.

Run EM, round by round

Left: the log-likelihood after each round. Right: each estimate divided by its true value, so a line at 1 means the truth. Compare the two settings of the M step.

Illustrative toy: 300 bins from a scalar LDS with true A = 0.9, Q = 0.3, R = 0.2 (seeded); C is fixed at 1 because a free C would only trade scale with the latent; the start is N(0, 1) and fixed. The E step is the exact Kalman filter and smoother from Chapter 1, and the M step is the closed form above, run live.

With the uncertainty kept, the estimates land close to the truth, and each round raises the likelihood. Switch to the mean-only version and look at Q and R. Q collapses toward zero and R swells far past the truth. The reason is plain: the smoothed path is smoother than the true path, so squaring only its mean ignores the doubt that remains. The model decides the hidden path is nearly noise-free and blames everything else on the readings.

When EM misleads you

The symptom: two runs from different starts end at different answers, or a fit looks too confident. The measurement: compare the final likelihood across several random starts, and check that the innovations from Chapter 1 look like white noise. The fix: run several restarts, keep the best, and keep the uncertainty terms. EM climbs to a hilltop, but not always the highest one.

Chapter 5 returns to a harder problem. Real spikes are counts, not Gaussian numbers, and then the formulas above no longer have a closed form. Our EM lesson builds the same alternation on a simpler model, and the PCA lesson shows the no-dynamics cousin of this fit.

In the M step, why do the formulas use m² + Σ instead of just m² for the square of a hidden state?

Chapter 3

Switching Dynamics: Modes, Recurrence and Decisions

Let the rule of motion change from moment to moment, and see why the switch must listen to the state

Picture a monkey watching dots drift across a screen. It must say which way they move. At first it is unsure. Its population activity creeps one way, then the other. Then, quite suddenly, it commits. After the commitment the activity holds steady until the answer is given.

One linear rule cannot make that. A single matrix A either keeps creeping or it holds still. The brain here seems to follow two rules and swap between them. The lecture calls the swap a discrete latent: a hidden label, not a hidden number, that says which rule is active.

The switching linear dynamical system

Add a hidden label zt that takes one of K values, such as 1 for “undecided” and 2 for “decided”. Each label owns its own set of matrices. The switching linear dynamical system (SLDS) says the state moves by the rule that the label picks.

xt = Azt xt−1 + …
The same dynamics equation as Chapter 1, but the matrices carry a subscript zt. The slide marks them state-dependent dynamics and state-dependent input weights.
Pij
A fixed transition matrix. Row i holds the chances of moving from label i to each label j. It does not look at x.

The observation equation yt = Czt xt + ηt may switch too. Fitting an SLDS is EM again. It is harder than Chapter 2, because the label is hidden as well as the state, and exact inference over both is no longer closed form. The models in the survey use approximations for it.

The flaw in a fixed switch

Look at Pij again. The chance to switch is the same wherever the state sits. So the model cannot say “switch to decided when the state reaches the bound.” It can only say “switch with some chance per time bin.” Those are different stories, and only the second one ignores the evidence.

The fix is the recurrent switching linear dynamical system (rSLDS). The slide marks the new arrows: the state xt−1 now feeds the label zt. The chance of each label depends on where the state is.

R, r
Recurrent transition weights and offsets, one set for each current label. A large weight on a coordinate makes the switch fire when the state crosses a value there.

The right side is a softmax: score each next label, exponentiate, divide by the sum. In the lecture’s words the switch becomes a function of the continuous state. The model can now carve the state space into regions, each with its own linear rule.

Why many straight pieces make a curve

Slide 19 shows a toy called a race track. The true dynamics circle a closed loop, a curved nonlinear path. A rSLDS fit to it learns several linear regions, each pushing the state along a short straight stretch, and the stretches join into a loop. The slide calls it a piecewise-linear approximation to a nonlinear dynamical system. Simulating from the fitted rSLDS reproduces the loop. Simulating from a fitted SLDS without recurrence, the lecture shows, does not.

Think of a road made of short straight planks. From far away it looks round. The more planks, the rounder the road. And each plank is a model you already know how to analyse, because each is a plain LDS.

Decisions as a switching model

The lecture then makes a claim that ties the survey to neuroscience: rSLDS gives a general framework for decision-making models. The classic one is the drift-diffusion model (DDM). A number x accumulates noisy evidence. It drifts toward the correct bound at a speed set by the evidence, and noise jostles it. When x touches either bound the animal commits. Slide 20 casts this as an rSLDS: a continuous state xt that accumulates inputs, and a discrete state zt that flips from “deciding” to “decided.” The flip is recurrent, because it happens exactly when x reaches a bound.

Slide 21 lists variants that fit the same frame: multi-dimensional accumulation, collapsing bounds, a variable lower boundary, and trial-history effects. The citations are Gold and Shadlen 2007, Drugowitsch et al. 2012, Roitman and Shadlen 2002, Churchland et al. 2008, Hawkins et al. 2015 and Urai et al. 2019, all from the lecture. The paper behind slides 20 and 21 is Zoltowski, Pillow and Linderman, 2020.

Try the model below. It runs 300 simulated trials. In Recurrent mode the label flips when the state hits a bound. In Fixed switch mode it flips at random, with a steady 2% chance per 10 ms bin, whatever x says. The choice is whichever side of zero x is on when the label flips.

Make a decision with a switch

Each line is one trial of the hidden state. Purple means undecided. Pink means the label has flipped to decided. Dashed lines are the bounds. Set the evidence strength, then compare the two switches.

1.5
1.00

Illustrative toy, not the paper’s fit: x moves by drift × 0.01 s plus unit Gaussian noise scaled by the square root of 0.01 s, starts at 0, for at most 4 s; 300 seeded trials. The exact answer for the recurrent case is 1 / (1 + e−2 · drift · bound) correct.

In Recurrent mode accuracy sits close to the formula: at drift 1.5 and bound 1 the formula says 95% and the 300 trials give 97%. Switch to Fixed and accuracy falls to about 81%, because the label flips at moments that have nothing to do with how far x has travelled, often too early. A stronger bound raises accuracy and slows decisions, the speed-accuracy trade-off that the DDM is famous for.

The failure to watch for: your fit gives crisp labels, yet they do not line up with anything in behaviour. Measure it by comparing label-flip times with response times, and fix it by letting the switch see the state. Chapter 1’s smoothing tools still apply inside each region; our hidden Markov model lesson builds the discrete half from zero.

What does recurrence add to a switching linear dynamical system?

Chapter 4

The Menagerie: One Grid for Every Model

Split any latent model into two choices, how the hidden path moves and how it becomes spikes, and place the whole field on one table

You open a paper that says “we fit a PLDS.” The next paper fits a GPFA, then an rSLDS, then a vLGP. Each name sounds new. It is easy to feel that the field is a pile of unrelated tricks.

It is not. The lecture’s section title is “Menagerie of models,” and its point is that every animal in the zoo is built from the same two parts. Learn the two parts and each new name becomes a pair of choices.

Part one: the prior over the hidden path

The first part is a prior: what you believe about the hidden path before you see any spikes. The slide writes it P(x). It answers: how does the hidden path move from one moment to the next? The lecture lists five answers, which become the five rows of the grid.

The linear dynamical system (LDS) moves by a matrix, as in Chapter 1. The switching LDS (sLDS) changes matrix by mode, as in Chapter 3. The third row is a general nonlinear function, written nNDS, for nonlinear dynamical system: the next state is any smooth function of the last, such as a neural ODE. The fourth is a recurrent neural network (RNN) that carries the state forward. The fifth is a Gaussian process (GP), which does not give a step rule at all. It says only that the path is smooth, and a setting called a kernel says how smooth.

Part two: the mapping to spikes

The second part is a probabilistic mapping from the path to the spikes, written P(y | x). The columns give four choices. A linear Gaussian mapping says each reading is a weighted sum of the latents plus Gaussian noise. That is the y = Cx + noise of Chapter 1. It suits Gaussian signals such as filtered voltage or calcium traces, and it is a rough fit for counts.

A linear-nonlinear-Poisson (LNP) mapping fits spikes better. Take a weighted sum, pass it through a nonlinear function so the rate stays positive, then draw spike counts from a Poisson distribution. If you know generalised linear models, this is one. The third column uses a deep network (DNN) for the middle step, so the map from latents to rates can be any smooth shape. The fourth column goes further: each neuron gets its own free nonlinear tuning curve over the latent.

The slide pictures the first three as a small box diagram: weights, then a nonlinearity, then spikes. The fourth is a row of bump-shaped curves.

Following the data through one model

Take the model called PLDS, for Poisson LDS, from Macke et al. 2015. It sits where the LDS row meets the LNP column. Follow the shapes. At each time bin the latent xt has 3 numbers. It steps by the Chapter 1 rule, xt = A xt−1 + εt. A weight matrix C of shape 100 × 3 turns it into 100 numbers. The nonlinear step is an exponential, so the rate is λt = exp(C xt + d), one positive rate for each of 100 neurons. The data are counts yt ~ Poisson(λt Δt), also 100 numbers.

Now change one choice. Swap the exponential for a deep network and you get pfLDS (Archer et al. 2015, Gao et al. 2016). Swap the LDS row for a GP and you get Poisson-GPFA. Nothing else changes. That is the whole idea of the grid.

The grid

Put prior on the vertical axis and mapping on the horizontal axis, then write each published model in its cell. The lecture’s table has five rows and four columns. Several cells are filled, and several are empty. The device below holds that table. Tap a cell to read what it combines. Then switch to Find it and test whether you can place a model from its name.

Place each model on the grid

Rows say how the hidden path moves. Columns say how it becomes spikes. Faint cells are empty in the lecture’s table.

The cells and citations are the lecture’s table on slide 24, in our own words. The one-line descriptions combine the row and column choices and are our own gloss.

Look at the empty cells. A neural ODE prior with a linear Gaussian readout has no entry. A switching model with a deep network readout has none either. Some of these gaps may be hard to fit, and some may simply be unexplored. The lecture returns to this in its closing question: which boxes can we, and should we, fill in?

The failure mode of a menagerie is picking by name. The symptom is that a famous model fits your data poorly, or fits it but teaches you nothing. Measure it by asking which row and column your data really need: do the counts look Gaussian, does the path look smooth or switching? Then fix it by choosing the cell, not the name. Our generalised linear models lesson builds the LNP column from zero.

A model has a Gaussian process prior and a Poisson spike mapping with a linear-nonlinear step. Which two choices define it?

Chapter 5

Nonlinear Spikes: pfLDS and vLGP

Keep the hidden path simple and let the readout bend, or keep the readout simple and let the path be a smooth free curve

A neuron in visual cortex watches a grating drift across the screen. As the grating turns, the neuron fires hard at one direction and barely at the opposite one. Plot its rate against direction and you get a bump. A bump is not a straight line, so no weighted sum of a few latents, with Gaussian noise on top, can draw it.

This chapter covers two cells of the Chapter 4 grid that fix this in opposite ways. One keeps simple linear dynamics and makes the readout nonlinear. The other keeps a linear readout and lets the hidden path be a free smooth curve.

Why spikes need a bent readout

Counts are not Gaussian. A neuron cannot fire a negative number of spikes, and its variance grows with its rate. The standard repair is the Poisson distribution, a recipe for counts with one parameter, the average rate λ. To keep λ positive, pass the weighted sum of the latents through a nonlinear function f first. That gives the linear-nonlinear-Poisson step of Chapter 4.

The lecture draws this on slide 28 as a short pipeline. Latent processes enter on the left. Each is multiplied by a loading weight, a number saying how strongly the latent drives this neuron. The sum goes through the nonlinear function. A feedback arrow, labelled an autoregressive filter, lets the neuron’s own recent spikes change its next rate. Then Poisson spiking draws the count.

λt
The firing rate in spikes per second. The weights α load the latents x, b is a baseline, and β weighs the last bin’s spike count. A negative β makes a refractory dip.
yt
The spike count in a bin of width Δt. Poisson means the mean equals the variance.

The device: a neuron reading a rotating latent

To feel the difference, give the neuron a hidden path that goes round a circle. This path comes from a plain LDS whose matrix A is a rotation: each step turns the pair (x1, x2) by a fixed angle. The neuron prefers one angle on the circle. Choose the shape of f, then turn up the gain and watch what each choice does to the rate.

Read a latent through a readout

Top: the rate the model asks for (warm), with a dashed zero line. Bottom: spikes drawn from it (blue). Switch the readout, then raise the gain.

1.2
0.0

Illustrative toy: the latent circles once every 2 s in 20 ms bins (a rotation LDS with no noise), the neuron prefers angle 0, baseline 10 spikes per second, three seconds shown, seeded. Linear uses rate = 10 + 10 × gain × cosine; exponential uses rate = 10 × egain × cosine. A negative rate is clipped to zero only when drawing spikes. History multiplies the rate by eβ × last count.

With the exponential readout the rate is always positive and it bends smoothly. At gain 1.2 it swings between about 3 and 33 spikes per second. With the linear readout and gain above 1, the requested rate dips below zero for part of every lap. A negative rate has no meaning. That part of the model is simply wrong, and the fit must fudge the rest to compensate.

Now slide β to −3. After each spike the next bin is almost silent, and the spikes spread out. That is a refractory period. Slide it to +1 and spikes come in bursts. This history term is the reason the spike-train models in Chapter 4 are more than a rate plot.

pfLDS: a simple path, a bendy readout

The first model is pfLDS (Gao, Archer, Paninski and Cunningham, 2016), the cell where linear dynamics meet a deep network. The slide calls it linear dynamics plus nonlinear observations. The latent path stays a plain LDS from Chapter 1, so inference keeps its nice structure. The readout from latents to rates becomes a deep network, a stack of weight matrices and nonlinearities that can draw almost any smooth map. The lecture shows a video of a fitted model on slide 26.

Why do that? Because a 2D rotation plus a good readout can produce rich population activity. In the device above, the circle is trivial, but the neurons’ responses are bumps, which no linear readout makes. A deep readout learns bumps, ridges and more, with fewer latent dimensions.

vLGP: a free path, a Poisson readout

The second model is vLGP, the variational latent Gaussian process (Zhao and Park, 2016). Slide 28 labels its two halves: a Gaussian process for the latents, P(x), and a Poisson GLM for the mapping, P(y | x). The Gaussian process gives each latent coordinate a smooth path with no step rule. The lecture titles the slide “nonlinear dynamics plus linear observations.” The word variational names the fitting method: instead of exact inference, which is out of reach, it fits an easier stand-in belief and tightens it.

The showcase is data from V1 (the first cortical visual area). The recording holds 63 neurons recorded at once (Graf et al. 2011) while drifting sinusoidal gratings play on the screen. The video that goes with the slides is titled “Latent dynamics in V1 driven by drifting grating,” with the arXiv number 1604.03053 by Yuan Zhao and Il Memming Park. A second video is titled “Latent trajectories for 36 directions form a torus.” We cannot rerun that fit here, but the shape is worth holding in mind: the hidden path of a direction code can wrap around a ring, and two such rings make a torus.

What to watch for: a GP latent has no step rule, so it describes how the path looks, not what drives it. If you need to simulate new trials or predict the future from dynamics, the symptom is a fit that looks fine but cannot extrapolate. Measure it by holding out the end of a trial, and fix it by choosing a dynamical prior from the earlier rows. Our Gaussian processes lesson builds the smooth prior, and the extended Kalman filter lesson shows another route to nonlinear inference.

Why does a spike model pass the weighted sum of the latents through a function like the exponential before the Poisson step?

Chapter 6

Latent Manifold Tuning

Find the hidden path and every neuron’s tuning curve at once, from spikes alone, even when the path lives on a curved surface

A rat runs a W-shaped maze while 31 hippocampal neurons are recorded. Each neuron fires when the rat is in one patch of the maze, its place field. Now suppose you do not know where the rat is. You hold only the spikes, as three coloured rows of ticks on slide 33: neuron 1, neuron 2, neuron 3.

The slide poses the challenge in one line: learn this from spikes alone. Learn the hidden position, and learn each neuron’s tuning curve over that position, with no labels for either. That is what the Latent Manifold Tuning model (LMT) of Wu et al. (2017) does. It is the Poisson-GPLVM cell in the lower right of the Chapter 4 grid.

Why PCA is the wrong first try

The lecture’s motivating example is principal component analysis (PCA). PCA finds the straight directions in the 100-neuron space along which the activity varies most, and keeps the top few. Slide 33 shows three neurons plotted against each other, and a latent variable that wanders through them.

PCA is the right tool when the neurons respond to the latent linearly. Tuning curves are bumps. Bumps are not linear. A single hidden angle going round a ring, read out by bump-shaped neurons, traces a loop in neuron space that is curved. A flat sheet laid through a curved loop needs many directions to cover it. So PCA reports a high dimension for something that has one.

The device builds exactly that. Twenty neurons have bump tuning around a ring, and the hidden angle sweeps the ring. It runs PCA on the spike counts and shows the first two components and the share of variance each component explains.

Run PCA on bump-tuned neurons

Left: the population at each moment, plotted on its first two PCs and coloured by the hidden angle. Right: variance explained by each PC. Make the tuning narrower and watch the loop and the bars change.

0.80 rad

Illustrative toy, not the paper’s data: 20 neurons with von Mises bumps (peak 30 spikes per bin above a floor of 0.5) evenly spaced around a ring, 300 bins, Poisson counts, seeded. The true latent is one angle. PCA is exact: eigenvectors of the 20 × 20 covariance of the counts.

At width 0.8 radians each neuron covers about a quarter of the ring. Two components hold about 80% of the variance and the loop in PC space is neat. At width 0.3 each neuron responds to a small arc, the variance spreads over many components, and the first two give only about a third of it. The true latent has not changed. It is still one angle. Go very wide and the tuning flattens, so Poisson noise starts to hide the loop instead.

The LMT model, step by step

LMT replaces the straight lines with a two-layer story, drawn on slides 35 and 36. Follow it down from top to bottom.

First, the latent process x(t) is drawn from a Gaussian process with a kernel over time, x(t) ~ GP(0, Kt). The kernel sets how smooth the path is: a wide kernel gives slow drift, a narrow one gives quick wiggles. Second, each neuron i has a tuning curve fi over the latent, and the model puts a second GP on the log of every curve, log fi(x) ~ GP(0, Kx). This second kernel sets how smooth the tuning curves are.

Third, the rate at time t is the curve read at the current latent: λi(t) = fi(x(t)). Fourth, spikes are Poisson: yi(t) ~ Poisson(λi(t)). Notice what is unusual. The model never says the curves are bumps or lines. The GP only says they are smooth, so the data decide the shape.

x(t) ~ GP(0, Kt)
The hidden path, smooth in time. The kernel Kt governs how smooth.
log fi(x)
The log of neuron i’s tuning curve over the latent, also smooth. The log keeps the curve positive.
λi(t)
The spike rate: read neuron i’s curve at where the latent is now.
yi(t)
The observed spike count, a Poisson draw from the rate.

This is a flexible model, and flexible models are hard to pin down. The latent can be stretched or bent as long as the tuning curves bend the opposite way. So the recovered latent matches the truth only up to a smooth reshaping. The lecture says so on its hippocampus slide, which shows the estimate “after affine transformation”.

The Möbius test

The lecture tests LMT on a hard made-up case. The simulated tuning is a 2D bump on the surface of a Möbius strip (slide 38), a one-sided twisted ribbon. A latent path circles along it (slide 39) and neurons with bumps at different spots on the strip produce firing rates, then Poisson spikes (slide 40). The raster looks like noise.

PCA on the spikes (slide 41) returns a tangle in its top three components, and its variance curve over 100 modes rises only slowly. LMT (slide 42) recovers a ring-shaped manifold that matches the true one, and its inferred latent time course follows the truth far better than a plain LDS fit, which is drawn as a dashed line. Slide 43 shows the payoff: re-sort the neurons by the inferred latent phase and the original messy raster turns into clean curved bands, one stripe of neurons after another.

The rat on the W maze

Then real data. The dataset has 31 simultaneously recorded hippocampal neurons (Karlsson et al. 2008), and the rat runs a W-shaped maze. PCA gives a bar chart of variance across components with no clean answer. LMT infers a two-dimensional latent from spikes alone. Compared with the rat’s true location, the lecture shows that LMT’s estimate tracks it, and slide 45 shows the learned tuning curves are place fields. The comparison models on slide 44 are PLDS and P-GPLVM. We do not copy the paper’s error numbers here; the slides show them as curves, and we cannot read exact values off the images.

The symptom to watch for in your own use: the inferred latent looks smooth, yet bears no relation to behaviour. Measure it by regressing a behavioural variable on the latent, allowing a smooth reshaping, and fix it by checking tuning curves look sensible before believing the latent. Our PCA lesson, Gaussian processes lesson and neural manifolds lesson go deeper.

One hidden angle drives bump-tuned neurons round a ring, yet PCA needs many components to explain the variance. Why?

Chapter 7

Familiar Methods as Constrained Models

See DMD, jPCA and communication subspaces as the same linear model with one knob locked, and learn what each lock costs

You have read papers that fit rotations to motor cortex, or that find a “communication subspace” between two brain areas. They come with their own names, code and fan clubs. It is easy to think each is a separate invention.

The lecture makes a quieter and more useful claim on slide 46. Each is an existing model with a constraint. Seen that way, you know what each one assumes, what it gives up, and when to reach for the full model instead.

The base model, reduced to a picture

Take the linear dynamical system from Chapter 1 in two dimensions: xt+1 = A xt + noise. Its matrix A has two eigenvalues, numbers that say what the matrix does to a path. A complex pair r e±iω means the path spirals. The radius r sets whether it grows (r above 1), shrinks (r below 1) or holds its size (r = 1). The angle ω sets how far it turns on each step. With ω = 20°, one lap takes 360 / 20 = 18 steps.

That is all a 2D LDS can do near the origin: spiral in, spiral out, or circle. Each method below locks something.

DMD: set the noise to zero

Dynamic mode decomposition (DMD; Kutz, Brunton, Brunton and Proctor 2016) fits xt+1 = A xt with no noise at all. In the lecture’s words, it is an LDS with the noise set to zero. With the noise gone, the fit is a plain least-squares regression of each state on the one before. The eigenvectors of the fitted A are the modes, and the eigenvalues give each mode a growth rate and a frequency. It is quick and clean when the states are measured accurately. The lock costs you the noise model, so it cannot tell dynamics noise from measurement noise.

jPCA: allow only rotation

jPCA (Churchland, Cunningham et al. 2012) fits an LDS with purely rotational dynamics. The matrix is not allowed to grow or shrink the path. It can only turn it. In our 2D picture that locks the radius at r = 1. The jPCA name comes from the finding that motor cortex population activity rotates during reaching. The lock costs you decay: a real path that dies away still gets drawn as a perfect circle.

Communication subspace: cap the rank

The third method is about two brain areas. Communication subspace (Semedo et al. 2019) models linear communication between neural populations. Its method is reduced rank regression: linear regression with a limit on the rank of the weight matrix. Say area 1 has 100 neurons and area 2 has 80. A full linear map from one to the other holds 100 × 80 = 8,000 weights. Force the map to pass through a rank of 2 and it needs only 2 × (100 + 80) = 360 weights.

Rank 2 means area 2 listens to only two directions in area 1’s activity, however many neurons area 1 has. Those two directions are the “communication subspace.” If prediction barely worsens as you lower the rank, the channel between the areas is thin.

The device: lock a knob and watch the fit

The device below simulates a 2D LDS with a true radius, a true angle and dynamics noise that you set. It then fits the model two ways: free, with a radius and an angle to learn, or locked to pure rotation as in jPCA. Set the true radius to 0.9 so the real path decays, then compare.

Fit it free, or lock it to a rotation

Thin purple lines are six noisy true paths. Warm lines are the fitted model run noise-free from the same starting points. Choose the fit, then change the true radius.

0.92
20°
0.020

Illustrative toy: a 2D rotation-and-scale LDS, six paths of 40 steps from points on the unit circle, seeded. The free fit is least squares of each state on the last, so it is DMD when noise is zero; the rotation fit keeps only the average turning angle and fixes the radius at 1.

With the free fit the model recovers both the radius and the angle, and its noise-free paths decay like the real ones. With the locked fit the angle is still right, but the fitted path circles at full size forever. At radius 0.92 after 40 steps a real path has shrunk to about 4% of its starting size, while the locked fit stays at 100%. That is the price of the lock. It buys a model with fewer numbers, which matters when data are scarce.

The symptom to watch: a rotation fit that looks great for one lap and wrong for long runs. Measure it by comparing the fitted radius from the free model with 1. Fix it by freeing the radius. Raise the noise slider and both fits drift a little, because noise blurs the regression. For the full model with noise on both sides, return to Chapter 2. Our PCA lesson covers the no-dynamics ancestor of these methods.

Which constraint turns a linear dynamical system into jPCA?

Chapter 8

Many Brain Regions, One Model

Give each region its own hidden path, let the paths push on each other, and let the strength of that push depend on the brain’s state

A mouse makes a decision while cameras image 16 cortical regions at once. Activity sweeps across the cortex as the choice forms. Somewhere in that sweep, information moves from one region to the next, but you cannot see the wires.

One latent model for the whole cortex would blur the regions together. It could not say who talks to whom. The last part of the lecture builds models that keep the regions apart and then model the traffic between them.

Start uncoupled

Slide 48 shows the simplest multi-region model: two separate LDS models side by side. Brain region 1 has its own hidden path, its own dynamics equation and its own observation equation. Region 2 has the same, with its own matrices. The paths never touch.

In the lecture’s notation, region 1 reads x(1)t+1 = A(1) x(1)t + V(1) ut + εt and its observations read y(1)t = C(1) x(1)t + ηt. The superscript says which region. Both regions share the same input ut, such as the stimulus. Without coupling, this is just two Chapter 1 models.

Add the coupling

Slide 49 adds one red dashed arrow, labelled the 2→1 coupling weights. The next hidden state of region 1 now depends on region 2’s current state, through a new matrix. Slide 50 adds the arrow in the other direction, the 1→2 weights. The slide’s summary is a single line: communication between brain regions occurs via coupling of latents.

A(11)
Region 1’s own dynamics, how its latent carries on by itself.
A(12)
The coupling weights from region 2 into region 1. A zero here means region 2 does not influence region 1 at this lag.

The coupling is on the latents, not on the neurons. That is a useful choice. Region 1 has 100 neurons and region 2 has 80, but the message between them can pass through a few numbers. This is the same economy as the communication subspace of Chapter 7.

Let the coupling depend on the state

Real communication changes with what the animal is doing. A region may listen to a partner only during a choice and ignore it at rest. Slide 51 builds that in. It is the multi-region rsLDS of Glaser et al. (NeurIPS 2020). A global discrete state zt, shared by all regions, picks which matrices apply, including the coupling weights. The slide says the coupling weights are state-dependent. Chapter 3’s recurrent switch reappears: the state follows from the latents.

Slide 52 goes one step further, to the multi-region switching nonlinear dynamics model (Karniol-Tambour et al. 2024). The linear maps become nonlinear functions: fA and fB for the dynamics of each region, gA and gB for the readouts. The global discrete state still switches them.

Why a switch matters for coupling

The device shows the reason. It simulates two regions with a hidden global state. In state 1 there is no coupling. In state 2 the 2→1 weight you choose is on. A fit that ignores the state averages the two halves. A fit that knows the state recovers each.

Recover who talks to whom

Top: the hidden path of region 1 (purple) and region 2 (pink). Bottom: the true coupling and what each fit recovers. Choose when coupling is on, then change the weights.

0.30
0.00

Illustrative toy, not the paper’s fit: each region has self-weight 0.6 and noise 0.3, 600 time bins, seeded. The fits are least-squares regressions of each region’s next latent on both current latents, run live, using the true latents (the hardest part, inferring them, is skipped).

Set 2→1 to 0.3 in “Only in state 2.” The all-run fit reports 0.18, well under the true 0.30, because it averages a half where the weight is zero with a half where it is 0.3. The state-aware fit finds 0.35 in state 2 and 0.05 in state 1. A wrong average can lead to a wrong claim, such as a weak connection where the truth is strong but intermittent.

The cortex-wide test

The lecture closes the section with real data from Pinto et al. (2019), widefield calcium imaging of 16 cortical regions as a mouse makes a decision. Slide 53 shows a single imaging frame, the full time-by-region image, and a PCA variance plot. Slide 54 shows the model’s inferred continuous latents and a discrete state sequence, with maps of average activity and average change in each of two states. Slide 55 shows a matrix of inferred communication between regions, and the finding is stated plainly: it recapitulates known connectivity. The authors on the slides are Orren Karniol-Tambour and Lucas Pinto.

The symptom to watch in your own use: coupling weights that move when you change the number of latents or the number of states. Measure it by refitting with a few settings, and fix it by reporting only the links that stay. Our smoothing lesson covers the inference these models need inside each state.

In a multi-region model, why is it better to let the coupling weights depend on a discrete state?

Chapter 9

Choosing a Model: Flexibility, Fittability, Interpretability

Weigh three needs against each other, test whether a fit is repeatable, and learn where the field is still wide open

You have a new recording and a menu of thirty models. A student asks which one to use. The honest answer starts with a question back: what do you want from it?

The lecture ends on exactly this. After the survey, slide 56 puts the grid from Chapter 4 back on screen with two questions. Which boxes can we, and should we, fill in? What columns or rows should we add? Slide 57 then names the three needs that decide the answer.

Three desiderata

The slide calls them desiderata, things a good method should have. Each comes with a short question in brackets, and each pulls against the others.

Flexibility: can we capture all nonlinearities and noise distributions? A flexible model can bend to fit any shape of data. The risk is fitting noise, and it is also harder to train. Fittability: speed, memory, and whether we get the same fits when we run it multiple times. A fittable model trains fast and gives the same answer every time. Interpretability: do the fits tell us something meaningful? An interpretable model has parts you can read, such as a rotation rate or a coupling weight.

The Chapter 4 grid is a map of these trade-offs. Move right and down and you gain flexibility. You usually lose fittability, because the maths gets hard, and interpretability, because the parts get opaque. The linear Gaussian LDS sits at the safe corner. It fits in seconds, it fits the same way each time, and its matrix A can be read. But it cannot bend.

Measure fittability, do not guess it

Fittability is the one desideratum you can measure cheaply. Run the fit from several random starting points. If every run lands in the same place, the model is fittable on your data. If the runs scatter, you cannot trust any one of them.

The device below does this for the Chapter 2 model. It starts EM from eight random points and plots where each run ends, as a value of A. Each run is the real EM loop. The true A is 0.9. Two knobs matter: how long the recording is, and how many EM rounds you allow.

Fit it from eight random starts

Hollow dots are random starting values of A. Filled dots show where EM ended. Red means the run finished clearly worse than the best. Shorten the budget, then lengthen it.

100 bins
3 rounds

Illustrative toy: the scalar LDS of Chapter 2 (true A = 0.9, Q = 0.3, R = 0.2, seeded), a random A between 0.05 and 0.95 and random Q and R between 0.05 and 5 as starts. Everything is computed live in your browser.

With three rounds the starts are still scattered: at the default setting the final A runs from about 0.54 to 0.90, and four runs finish well behind. That is the speed question. Give the fit 30 rounds and they pull together between 0.84 and 0.87. This model is easy. The deeper models in the menagerie have curved landscapes with several hilltops. There the same test can scatter even after hundreds of rounds, and you must keep the best of many starts.

A short guide to picking a cell

Use the grid as a checklist, and ask the data two questions per axis. For the column, the mapping: are the observations Gaussian signals, or counts? Counts call for a Poisson column. Do the tuning shapes look like bumps, ridges, or something odd? Bumps suggest a free tuning curve, as in Chapter 6. For the row, the prior: does the path look smooth with no clear rule, does it follow a stable rule, does it switch between rules, or does it need a rich nonlinear rule? Smooth with no rule suggests a Gaussian process. A stable rule suggests an LDS. Switching suggests an sLDS or an rSLDS. This guide is our own gloss on the lecture’s grid.

Start at the corner you can fit and read, and move out only when the data force you. Each step out should buy a concrete gain you can measure, such as better prediction on held-out spikes.

New directions

The slide lists six challenges. They read as a research agenda, and each one maps back to a chapter of this lesson.

Our BCI latent variable models lesson carries these tools into decoding, and the LFADS lesson builds the recurrent-network cell of the grid.

You fit a model from ten random starts and get ten very different answers. Which desideratum has failed, and what do you do?

Chapter 10

Field Guide

Keep the numbers, the checklist and the core code, and find where to go next

The lecture surveys one idea from many angles. Spikes from many neurons share a few hidden causes, and a latent time series model recovers them. Every model is a prior over how the hidden path moves plus a mapping from path to spikes. The linear model is fitted by EM, the Kalman filter and smoother in the E step and three regressions in the M step. Switches, nonlinear readouts, smooth priors and several regions are choices added to that base.

The numbers and terms

ItemValue or meaningWhere
Baum-WelchEM for a hidden Markov model. Its E step is forward-backward.Chapter 0
Kalman filter-smootherThe E step for an LDS. Forward half: filter. Backward half: smoother.Chapter 1
Kalman gainK = P− / (P− + R). Worked toy: 0.505 / 1.005 = 0.502.Chapter 1
Long-run spreadP = A P A⊤ + Q. One dimension, A = 0.9, Q = 0.1: P = 0.526.Chapter 0
HMM long-run sharesTop left eigenvector of A. Toy two-state example: 2/3 and 1/3.Chapter 0
M stepClosed-form updates for A, C, Q, R from the smoothed means and variances. Keep the variance terms.Chapter 2
SLDS and rSLDSA discrete label picks the matrices. In rSLDS the label depends on the state: P ∝ exp(R x + r).Chapter 3
Drift-diffusionRecurrent switch at a bound. Toy: drift 1.5, bound 1 gives 95% correct.Chapter 3
The grid5 priors by 4 mappings. 11 of the 20 cells hold models in the lecture’s table.Chapter 4
LNP readoutRate = f(weights · latent + baseline), counts are Poisson. Keeps the rate above zero.Chapter 5
LMTGP over the latent in time, GP over log tuning curves, Poisson spikes. Learns both from spikes alone.Chapter 6
DMD, jPCA, communication subspaceLDS with zero noise; LDS with rotation only; regression with a rank cap. Toy: rank 2 uses 360 weights, not 8,000.Chapter 7
Multi-region couplingOne latent per region, with coupling weights between latents, switched by a global state.Chapter 8
DesiderataFlexibility, fittability, interpretability.Chapter 9

A checklist before you trust a latent fit

  1. Say what your observations are. Counts call for a Poisson mapping, not a Gaussian one.
  2. Say how the path should move: smooth, a stable rule, switching, or nonlinear. Start with the simplest.
  3. Fit from several random starts and keep the best likelihood. Report the spread.
  4. Keep the variance terms in the M step. Check that innovations look like white noise.
  5. Hold out spikes and compare against a simpler cell of the grid.
  6. Compare the latent with behaviour, allowing a smooth reshaping.
  7. Refit with a different number of latents or states before you believe a coupling weight.

The core as code

Here is the whole E step and M step for a linear dynamical system with a vector latent, in about 40 lines. The data y has shape (T, n_neurons). It follows Chapters 1 and 2, with the matrix forms of the formulas.

import numpy as np

def kalman_smoother(y, A, C, Q, R, m0, P0):
    """E step. y: (T, n_neurons). Returns smoothed means, covariances, cross-covariances."""
    T, d = len(y), len(m0)
    mp, Pp, m, P = [None] * T, [None] * T, [None] * T, [None] * T
    for t in range(T):                                         # forward pass
        mp[t] = m0 if t == 0 else A @ m[t - 1]                 # predict: mean
        Pp[t] = P0 if t == 0 else A @ P[t - 1] @ A.T + Q       # predict: covariance
        S = C @ Pp[t] @ C.T + R
        K = Pp[t] @ C.T @ np.linalg.inv(S)                     # Kalman gain
        m[t] = mp[t] + K @ (y[t] - C @ mp[t])                  # update: mean
        P[t] = (np.eye(d) - K @ C) @ Pp[t]                     # update: covariance
    ms, Ps, G = m[:], P[:], [None] * T
    for t in range(T - 2, -1, -1):                             # backward pass
        J = P[t] @ A.T @ np.linalg.inv(Pp[t + 1])
        ms[t] = m[t] + J @ (ms[t + 1] - mp[t + 1])
        Ps[t] = P[t] + J @ (Ps[t + 1] - Pp[t + 1]) @ J.T
        G[t + 1] = Ps[t + 1] @ J.T                             # Cov(x_{t+1}, x_t | y)
    return ms, Ps, G

def m_step(y, ms, Ps, G):
    """M step: closed-form updates from the expected moments."""
    T = len(y)
    Exx = sum(np.outer(ms[t], ms[t]) + Ps[t] for t in range(T))
    Ex_now = sum(np.outer(ms[t], ms[t]) + Ps[t] for t in range(1, T))
    Ex_old = sum(np.outer(ms[t - 1], ms[t - 1]) + Ps[t - 1] for t in range(1, T))
    Ecross = sum(np.outer(ms[t], ms[t - 1]) + G[t] for t in range(1, T))
    A = Ecross @ np.linalg.inv(Ex_old)
    Q = (Ex_now - A @ Ecross.T) / (T - 1)
    C = sum(np.outer(y[t], ms[t]) for t in range(T)) @ np.linalg.inv(Exx)
    R = sum(np.outer(y[t], y[t]) - C @ np.outer(ms[t], y[t]) for t in range(T)) / T
    return A, C, Q, R

# EM: alternate the two until the likelihood stops rising
# for _ in range(50):
#     ms, Ps, G = kalman_smoother(y, A, C, Q, R, m0, P0)
#     A, C, Q, R = m_step(y, ms, Ps, G)

Keep going

Our lessons that teach the maths in depth: Kalman filter, RTS smoothing, hidden Markov models, EM and Gaussian mixtures, PCA, generalised linear models, Gaussian processes and the extended Kalman filter. For the same ideas in a decoding setting, go to latent variable models for BCI, LFADS, neural manifolds, the Kalman decoder and the point-process GLM.

Credit

This lesson follows Lecture 23, “A survey of modern latent time series modeling in neuroscience,” of Princeton NEU 560, Statistical Modeling and Analysis of Neural Data, Spring 2024, taught by Jonathan Pillow. The slides (PDF) and the rest of the course are on the course site. The models come from the papers the slides cite, among them Macke et al. 2015, Archer et al. 2015, Gao et al. 2016, Linderman et al. 2017, Zhao and Park 2016, Wu et al. 2017, Zoltowski, Pillow and Linderman 2020, Glaser et al. 2020 and Karniol-Tambour et al. 2024. Every device here is our own toy, labelled as such, and no slide image is reproduced.

The takeaway. Spikes are a noisy shadow of a few hidden numbers. Choose how the numbers move and how they become spikes, fit both from the spikes, and then test that the result is repeatable and means something.
A colleague fits an rSLDS and reports crisp states, but the states match nothing in behaviour and change with each restart. What should you suggest first?

Now try it yourself. Open Teach to draw these models on a whiteboard, or Sparks for a quick deck of single ideas. Then go back to the hidden path and see the hero with new eyes.

NEU 560 L23: Neural Latent Time Series Models
Course site · Back to Gleams