A few hidden numbers drive hundreds of noisy neurons. A linear dynamical system tracks them, and the Kalman filter turns jittery readings into an estimate you can trust.
Learn the model with two equations, why its hidden state needs a filter and a smoother, and how EM learns the whole system from data.
Drag the measurement noise up and down and watch the blue readings scatter while the warm estimate stays close to the purple truth. Then we build, piece by piece, the model, the filter, the smoother and the learning loop underneath.
You need a feel for averages and spread (a mean says where, a variance says how widely) and a little matrix multiplication. We build the rest from zero.
Based on Lecture 22 of Princeton NEU 560, Statistical Modeling and Analysis of Neural Data (Spring 2024), taught by Jonathan Pillow; the slides and notes are on the course site. The lecture deck is three slides, so we teach the full topic from the course’s own framing and from Bishop’s Pattern Recognition and Machine Learning, chapter 13. Every idea is re-taught here in our own words and devices; for the latent variable idea behind it, see Lecture 15 and Lecture 20.
Illustrative toy: a hidden point turns 0.18 radians per step while shrinking 0.5% per step, kicked by random noise of the size you set. A noisy sensor reports its position. The filter knows the true dynamics and both noise sizes, and uses the Kalman recursions of Chapter 6. The errors are measured over the last 40 steps in your browser.
Chapter 0
See how many noisy neurons can share a few hidden numbers, and why that calls for a model that tracks time
Picture an electrode array in a monkey’s motor cortex while the animal reaches for a cup. The array records 90 neurons (illustrative numbers). Every 10 milliseconds you count how many spikes each neuron fired. That gives you 90 numbers per time bin, and every one of them is noisy. A neuron that fires 3 spikes in one bin may fire 6 in the next with the reach unchanged.
Now look at the whole population over a second. The 90 jagged traces move together. They rise and fall in a few shared patterns, as if a small number of hidden knobs were being turned and every neuron were listening to them. The reach itself is smooth. The mess comes from the counting.
This lecture is about a model for exactly that picture. The model says: there is a short list of hidden numbers, the latent state, that changes smoothly in time by a simple rule. Each neuron reports a noisy, weighted copy of them. The job is to recover the hidden numbers from the noisy reports.
This is Lecture 22 of Jonathan Pillow’s Princeton course on statistical modeling of neural data. The lecture title is “(Latent) Linear Dynamical Systems (LDS)”, and its deck has three slides: a title, one slide with the model, and a summary. The course so far has built the tools this lecture uses: Gaussians and regression, latent variable models (Lecture 15), and the EM algorithm (Lecture 16). The deck is short because it leans on them. So we teach the whole topic here, from the slides’ model and summary and from Bishop’s chapter 13, and we link the site’s existing lessons where they teach the mathematics in depth.
The summary slide says three things, and each one gets its own chapters. First, an LDS has linear dynamics with Gaussian noise and linear observations with Gaussian noise (Chapters 1 to 4). Second, the E-step of EM for this model is the Kalman filter-smoother (Chapters 5 to 7). Third, because the E-step is solved exactly, the whole model can be learned from data (Chapter 8). Chapter 9 asks what a fitted model can and cannot tell you.
A word about letters. The deck uses x for the latent state and y for the observations on its model slide, and z and x the other way round on its summary slide. This lesson keeps one choice: x is hidden, y is what you measure.
A fair first idea: if each neuron is a noisy copy of the hidden signal, pool many of them. Noise that is random from neuron to neuron cancels in the average, while the shared signal adds up. This works, and the device below shows it. Each neuron here is the hidden signal times its own weight, plus its own noise. Drag the number of neurons and the noise level.
Top: one neuron, rescaled so the hidden signal (purple) is its target. Bottom: a weighted pool of the neurons you chose (warm). Raise the noise, then add neurons.
Illustrative toy: 100 time bins, a made-up smooth signal with unit spread, 40 neurons with weights between 0.5 and 1.5 and independent Gaussian noise, seeded so every visit looks the same. The pool is the least-squares estimate of the signal in each bin, the sum of weight times reading divided by the sum of squared weights. The correlation is computed live.
Pooling helps, but it throws away something. Look at the bottom trace. Even with many neurons it still wobbles, and it treats every time bin on its own. Yet you know more: the hidden signal at 10:00:00.010 cannot be far from where it was at 10:00:00.000. Smooth signals do not jump. Pooling ignores that memory.
A better method would use both facts at once: what the neurons say now and how the hidden state tends to move. It would also say how sure it is. That is what the Kalman filter does, and it does it in the best possible way when the model is linear and Gaussian. Getting there takes a few small steps.
The lesson follows the lecture in order: the model, then the inference that uses it, then the learning that fits it. Each chapter ends with a one-question quiz.
Chapter 1
Write a hidden state that moves by a rule and neurons that report it, and see why two short equations are the whole model
Think of a toy boat on a pond that you cannot see. You can see only a few floating corks that bob when the boat moves. The boat’s position changes by a simple rule from one second to the next. Each cork shows the boat’s position through a blur. Everything in this lecture is a version of that picture: a hidden thing that moves, and some noisy witnesses.
The model slide draws it as a chain. Along the middle runs a row of circles, x1, x2, x3, the continuous latents. “Continuous” means each one is a list of real numbers, not a label from a short menu. “Low-D” means the list is short, say 2 to 10 numbers. Below each latent hangs one circle, an observation yt: the neural data. Above, optional circles ut are inputs, things you control or know, such as the stimulus on the screen.
The first equation says how the hidden state moves. Take the state at the last time step, apply a fixed linear rule, add the push from any input, and add random noise. Here it is, written as on the slide.
The word linear has a strict meaning here: doubling the state doubles the next state. A matrix multiplication does that, and nothing curved can. The word dynamics means the state is a thing that evolves. The noise is also why this is called a stochastic system: run it twice from the same start and the paths differ.
The second equation says what the neurons report. Take the hidden state, mix it with a fixed matrix, and add noise that belongs to the measurement.
Two noises, two jobs. The dynamics noise Q says how much the hidden state itself wanders. The observation noise R says how badly the neurons report it. A filter has to guess how to split a surprise between the two, and Chapter 6 shows how.
Let the state have n = 2 numbers. Let the dynamics matrix be A with rows (0.9, −0.2) and (0.2, 0.9). Start at xt−1 = (1, 0). Then A xt−1 = (0.9, 0.2). Say the random kick is ε = (0.05, −0.03). The new state is xt = (0.95, 0.17).
Now a neuron whose row of C is (1.0, 0.5). It computes 1.0 × 0.95 + 0.5 × 0.17 = 1.035. Say its noise is η = −0.1. It reports y = 0.935. That neuron never sees 0.95 or 0.17. It sees one blurred mix of them.
xt = (0.95, 0.17) → y = 1.0 × 0.95 + 0.5 × 0.17 − 0.1 = 0.935 (toy numbers)
Two choices make the model easy to work with. The first is that only the last state matters: xt depends on xt−1 and not on anything earlier. This is the Markov property, and it lets an algorithm sweep through time one step at a time. The second is that every step is linear with Gaussian noise. A Gaussian pushed through a matrix is still a Gaussian, and a Gaussian plus independent Gaussian noise is still a Gaussian.
Together these facts mean something strong. Every belief you will compute in this lesson, about one state or about the whole path, stays a Gaussian. A Gaussian needs only a mean and a covariance to describe it, so the computer never has to track a growing pile of possibilities. That one property is why a filter can be exact here, and why it stops being exact the moment the dynamics curve.
With n hidden numbers and m neurons, the shapes are: x is n×1, y is m×1, A is n×n, C is m×n, Q is n×n and R is m×m. A typical neural fit has n of 2 to 20 and m of 50 to 1,000. Fix n = 10 and m = 90. Then A has 100 numbers, C has 900, Q has 55 (it is symmetric), and a diagonal R has 90. That is 1,145 numbers to describe 90 neurons over any length of time.
The device below runs the model forward. Choose the dynamics and the two noise sizes, and watch a 2-number hidden state (left) produce four neurons’ readings (right).
Left: the hidden state in a plane, path coloured from start to end. Right: four neurons, each a noisy mix of the two hidden numbers. Try decay 1.00 with low noise, then raise the measurement noise.
Illustrative toy: A is a rotation by the turn angle times the decay, C is a fixed 4 by 2 matrix of made-up weights, 80 steps from the start (1.5, 0), with random numbers seeded so only your settings change the picture.
With decay below 1, the loop tightens and the noise keeps nudging it, so the path never dies out completely. Raise the turn and the loop spins faster; the neurons then oscillate faster, though each one still shows only a blurred mix of the two hidden numbers. Chapters 2 and 3 take the matrices apart one at a time.
Chapter 2
Read the dynamics matrix as a rule for shrinking, growing and turning, and see what an input adds to it
A swing hangs still. You push it once and let go. It swings back and forth, each swing a little smaller, until it stops. Where it is now, and how fast it is moving, tells you where it will be next. The rule that turns “now” into “next” is the swing’s dynamics. The matrix A is that rule for the hidden state.
First, take the noise away. With no kick and no input, the dynamics equation reduces to xt = A xt−1. Apply it twice and you get A A xt−2. After t steps the state is At x0: the matrix multiplied by itself t times, then applied to the start. So A decides the whole shape of the path.
The simplest interesting A turns every point by a fixed angle θ and scales it by a factor ρ. Written out, its rows are (ρ cos θ, −ρ sin θ) and (ρ sin θ, ρ cos θ). Each step moves the point round a circle by θ radians and multiplies its distance from the centre by ρ.
Take ρ = 0.95 and θ = 0.3 radians. The distance from the centre after t steps is 0.95t. After 13.5 steps it has halved, because 0.9513.5 is about 0.5; we get 13.5 from ln(0.5) divided by ln(0.95). A full turn takes 2π / 0.3 = 20.9 steps. So the path is a spiral that winds in: about two thirds of a turn while it halves.
A matrix can do more complicated things than a rotation, but a short list of numbers summarises what it does to a path. An eigenvector of A is a direction that A only stretches. If A v = λ v, then v is an eigenvector and λ is its eigenvalue. Push the state along v and each step multiplies it by λ.
Some matrices have no real stretch directions, because they turn every direction. Then the eigenvalues are complex numbers, which you can read as a distance and an angle. For our rotation, the eigenvalues are ρ e±iθ: distance ρ, angle ±θ. The distance ρ is the modulus of the eigenvalue, and it is the number that matters most.
Three cases cover everything. If the modulus is below 1, the state shrinks to zero: the system is stable. If it equals 1, the state neither shrinks nor grows. If it is above 1, the state grows without limit. The angle sets the spin: zero angle means a straight slide, and a large angle means fast oscillation.
The input term B ut adds to the state without changing the rule. Suppose B is the column (1.5, 0) and u is zero except u20 = 1. At step 20 the state jumps by (1.5, 0). From then on A carries that jump forward like any other starting point. In a neural experiment, u might be the position of a target on the screen, and B how a target change moves the hidden state.
Now try it. Choose the modulus and the angle. The left plot is the path of a noise-free state from the start point (1, 0). The right plot shows its distance from the centre, with a dashed line at the starting distance 1.
Left: the path in the plane. Right: distance from the centre against time. Set the size to 1.00 for a ring, below for a spiral in, above for a spiral out. Then switch on the input pulse at step 20.
Illustrative toy: A is the rotation-and-scale matrix above, 60 noise-free steps from (1, 0). The pulse adds B u = (1.5, 0) once, at step 20. Half-life is ln 0.5 divided by ln of the size; doubling time is ln 2 divided by ln of the size.
Spend a minute at size 1.00. The path is a ring, and the distance plot is flat. With even a little noise, a ring state wanders: the kicks add up and nothing pulls the state back. Slow, persistent patterns in data push a fitted modulus toward 1, so you meet this edge often in practice.
This is more than a toy. Churchland and colleagues (Nature, 2012) reported that the activity of motor cortex neurons during reaching follows rotation-like paths when you look at the population: a spiral or loop in a plane of hidden numbers. A linear system with a complex eigenvalue pair is the simplest model that makes exactly such a loop. That is why LDS is a first model for population dynamics.
The symptom: you fit an LDS, run it forward to make a prediction, and the predicted activity explodes after a few hundred steps. The measurement: compute the eigenvalues of the fitted A and look at their moduli. If one is 1.02, the state grows by 2% every step, which is a factor of 7 in 100 steps. The fix: check stability after every fit, and if you need long forecasts, constrain the moduli to 1 or less, or refit with more data.
Chapter 3
See how a few hidden numbers become many neural readings, and how many readings pin the hidden numbers back down
Six friends stand in a circle around a stage. A performer walks somewhere on the stage, and each friend reports how close the performer is to them, with a bit of error. No friend knows where the performer is. Yet from six rough reports you can place the performer well. The friends are neurons, the performer is the hidden state, and the matrix C says how each friend listens.
Row i of C lists the weights neuron i puts on each hidden number. For two hidden numbers, row i is a pair, written (ci1, ci2). The neuron’s noise-free reading is ci1 x1 + ci2 x2. This is a dot product, and a dot product measures how well the hidden state lines up with the neuron’s row.
Give neuron i a row of length gi pointing at angle φi: (gi cos φi, gi sin φi). If the hidden state has length |x| and points at angle α, the reading is gi |x| cos(α − φi). The neuron is largest when the state points where it prefers and zero when the two are at right angles. That is a cosine tuning curve, the classic picture of a motor cortex neuron’s preferred direction. So linear observation matches a real tuning shape.
Take six neurons with preferred angles 0, 60, 120, 180, 240 and 300 degrees and every gain equal to 1. Let the hidden state be x = (1.0, 0.5). The six noise-free readings are 1.000, 0.933, −0.067, −1.000, −0.933 and 0.067. Check the second: cos 60° is 0.5 and sin 60° is 0.866, so 0.5 × 1.0 + 0.866 × 0.5 = 0.933. Six numbers now carry two numbers of information.
The reverse problem is a regression. You know C and the six noisy readings y, and you want x. The least-squares answer chooses the x whose noise-free readings C x come closest to y. It has a closed form, x̂ = (CT C)−1 CT y. Here CT C works out to 3 times the 2 by 2 identity matrix, because the six directions are evenly spread. So x̂ = CT y / 3: each neuron votes in its preferred direction, weighted by its reading, and the votes are averaged.
What does noise do to this? If every neuron has independent noise of spread r, the estimate of each hidden number has spread r divided by the square root of 3, about 0.58 r. With r = 0.5 that is an error of roughly ±0.29 in each number. More neurons would shrink it further: with 60 evenly spread neurons the divisor becomes the square root of 30. The device lets you see both sides. Move the hidden point, change the noise, and draw new noise.
Left: each neuron’s noise-free reading (bar) and its noisy reading (blue dot). Right: the true hidden point (purple) and the point recovered from the six dots (warm). Drag the hidden point, raise the noise, press New noise.
Illustrative toy: six neurons with preferred angles 0, 60, 120, 180, 240 and 300 degrees and gain 1, independent Gaussian noise, and the least-squares readout CT y / 3. The noise draws are real random draws in your browser.
Keep the noise at 0.5 and press New noise a dozen times. The blue dots jump around, yet the warm point stays near the purple one. Raise the noise to 1.5 and the warm point swings widely. This is the whole point of a low-dimensional latent: many noisy numbers vote on a few.
The usual choice is a diagonal R: each neuron has its own independent noise. That is a strong claim. It says that once the hidden state is known, the neurons are unrelated. Any shared variability across neurons must then be explained by the hidden state. This is exactly why the model is called a latent variable model: the latent absorbs all the correlation.
Spike counts are not Gaussian. They are non-negative whole numbers, and their variance grows with their mean. Two common repairs exist. You can transform the counts, for example with a square root, which makes the variance roughly constant, and then fit the Gaussian model. Or you can change the observation model to a Poisson one, as in the Poisson linear dynamical system of Macke and colleagues (2011); inference is then approximate. This lecture keeps the Gaussian version, which gives exact answers and is the base for the rest.
The symptom: the recovered point is steady for most time bins, then jumps for a few. The measurement: look at the readings from those bins. One neuron may be far from its expected value, such as a burst from a neighbouring cell. The fix: raise that neuron’s R entry so the filter trusts it less, or remove the neuron. A noise value that is too small tells the model to believe every spike.
Chapter 4
Count the four knobs of the model, then work out how widely the hidden state wanders once it has settled
Drop one marble onto a bowl’s curved floor and shake the bowl gently and forever. The marble does not roll off. The bowl pulls it back, and the shaking pushes it out. After a while the marble’s position has a steady spread: some typical distance from the centre that no longer changes. An LDS with a stable A does the same thing. The pull is A, and the shaking is the dynamics noise Q.
The model slide closes with one line: parameters θ = {A, C, Q, R}, plus B if we have inputs. Those are all the knobs. A and B set the motion, C sets how neurons read the state, Q sets how hard the state is shaken and R sets how blurry the readings are. Learning the model means finding values for them, and Chapter 8 does it.
The summary slide adds a fact about the hidden state itself: its asymptotic covariance obeys P = A P AT + Q, called the discrete-time Lyapunov equation. “Asymptotic” means “after a long time”. “Covariance” is the spread of the state, written as a matrix. Let us derive it.
Start with a single hidden number: xt = a xt−1 + εt, where the noise has variance q. The variance is the average squared distance from the mean, and it is the one-number spread. Two facts about variance do the work. Scaling a variable by a scales its variance by a squared. And adding an independent variable adds the variances.
The old state xt−1 is independent of the new kick εt. So the variance obeys a simple recursion.
To find the settled value, ask what P must be so that one more step changes nothing: P = a2 P + Q. Move terms: P (1 − a2) = Q. Divide, and P = Q / (1 − a2). The pull a2 removes variance, the kick Q adds it, and the settled spread is where the two balance.
Let a = 0.9 and Q = 0.19. Start with a state known exactly, so P0 = 0. Step 1: P1 = 0.81 × 0 + 0.19 = 0.190. Step 2: 0.81 × 0.190 + 0.19 = 0.344. Step 3: 0.81 × 0.344 + 0.19 = 0.468. The formula says the limit is 0.19 / (1 − 0.81) = 0.19 / 0.19 = 1.000. The steps are climbing toward it, closing about 19% of the remaining gap each time.
P: 0 → 0.190 → 0.344 → 0.468 → … → 1.000 (a = 0.9, Q = 0.19; illustrative)
Try it below. The cloud of 300 simulated runs shows the spread you can check by eye: the blue dots are the measured variance across the runs, the warm line is the exact recursion, and the dashed purple line is the limit.
Each dot is the variance across 300 simulated runs at that step. Push a toward 1 and the settling slows. Push it past 1 and there is no limit at all.
Illustrative toy: a scalar state that starts at exactly 0, 300 runs of 40 steps with seeded Gaussian kicks. The warm curve is Pt = a2 Pt−1 + Q from P0 = 0; the dashed line is Q / (1 − a2). The dots wobble around the curve because 300 runs is a finite sample.
With a hidden state of n numbers, the spread is an n by n covariance matrix P. The same two facts hold in matrix form. Scaling the state by A turns its covariance P into A P AT, and independent noise adds covariances. So Pt = A Pt−1 AT + Q, and the settled P satisfies P = A P AT + Q, the line from the summary slide. It has a solution only when every eigenvalue of A has modulus below 1, the same stability rule as Chapter 2.
You can solve it two ways. The first is to iterate the recursion until it stops changing, as in the worked example. The second is exact: write P as one long vector and solve a linear system, the route taken by library routines for the Lyapunov equation. In the special case A = ρ × rotation and Q = q I, the rotation drops out of A P AT when P is a multiple of the identity. Then P = q / (1 − ρ2) I, exactly the scalar answer on each axis.
The settled covariance has three jobs. It is a sanity check: if the fitted P is huge, the latent scale is out of line with the data. It is a natural starting belief about the first hidden state, before any data have come in. And it is a reference for how well any filter can do: a filter should always be at least as sure as this prior spread, because it has data on top.
The symptom: the prior spread for the first state comes out enormous or negative. The measurement: compute the largest eigenvalue modulus of A. If it is 1 or more, the Lyapunov equation has no valid answer, because the variance never settles. The fix: keep A stable, or give the first state a prior that you choose and stop trying to compute the settled one.
Chapter 5
Combine a prediction and a measurement by weighing each by how sure it is, and see the result beat both
You are looking for your friend in a crowd. Your memory says she was by the fountain, but you saw her ten minutes ago, so you are unsure. Then a stranger points and says “over by the bench”, but the stranger glanced for one second, so that is shaky too. You do not pick one source. You head to a spot between the two, closer to whichever source you trust more. That is the entire idea of this chapter.
The summary slide says the E-step of this model is the Kalman filter-smoother. The E-step asks: given all the data and the current parameters, what do we believe about the hidden states? The answer will come from repeating one small move, again and again. So we study the move first, in one dimension, where every number can be checked by hand.
A Gaussian belief about one number has two parts: a mean (the best guess) and a variance (how unsure you are). A small variance gives a tall, narrow bell; a large one gives a low, wide bell. The precision is one divided by the variance, so it measures how sure you are. A precision of 4 means a variance of 0.25.
Our prediction says the hidden state is near 2.0 with variance 1.0. Call these μ− = 2.0 and P− = 1.0; the minus sign means “before looking at the data”. The measurement is y = 4.0 and the neuron noise has variance R = 3.0. In words, the measurement says: whatever x is, I read it as 4.0 with a blur of variance 3. As a function of x, that is also a bell, centred at 4.0.
Bayes’ rule says: belief after = belief before × how well each x explains the data, then rescale. Here both factors are bells in x. The product of two bell curves is again a bell curve, and its centre and width have a clean form (this is a short calculation: add the exponents, collect the terms in x and complete the square).
The precisions add. The new mean is the average of the two means, each weighted by its precision.
Now put our numbers in. The precisions are 1 / 1.0 = 1 and 1 / 3 = 0.333. They add to 1.333, so Pnew = 0.75. The weighted sum is 2.0 / 1.0 + 4.0 / 3.0 = 3.333. Multiply by 0.75 and the fused mean is 2.5. The result N(2.5, 0.75) sits closer to the prediction, which was the more trusted source, and it is narrower than both inputs.
There is a second way to write it, and it is the one filters use. Start from the prediction and nudge it toward the data by a fraction K of the gap.
K = P− / (P− + R) = 1 / (1 + 3) = 0.25 μnew = μ− + K (y − μ−) = 2.0 + 0.25 × 2.0 = 2.5 Pnew = (1 − K) P− = 0.75
K is the Kalman gain. It is a trust slider between 0 and 1. When the measurement is very noisy (R large), K is near 0 and the update barely moves the prediction. When the measurement is very clean (R tiny), K is near 1 and the fused belief jumps to the data. The term y − μ− is the innovation: how much the data surprised the prediction.
The yellow bell is the prediction, the blue bell is what the measurement says, and the warm bell is the fused belief. Make the measurement noisier and watch the warm bell slide toward the yellow one.
The defaults are the worked example above (prediction 2.0 with variance 1.0, measurement 4.0 with variance 3.0). The curves are exact Gaussians, and the fused values come from the precision formulas, not from a fit.
A real recording has m neurons and a hidden state of n numbers. The same move holds, with matrices: the gain becomes K = P− CT (C P− CT + R)−1. Its shape is n by m: for each hidden number, a weight on each neuron. The update is μ = μ− + K (y − C μ−), and the new covariance is (I − K C) P−. When n = 1, m = 1 and C = 1, these lines reduce to the ones you just did by hand. The term C μ− is the reading you expected; the innovation is the gap between expected and actual.
For the full Bayesian derivation, with the prior and likelihood spelled out, see Lecture 12 on MAP inference. The new thing here is only the repetition: after fusing at time t, the answer becomes the prediction for time t + 1.
The symptom: the fused estimate follows every blip in the measurement. The measurement: K is close to 1 at every step. The cause: R is set too small or P− too big, so the filter believes the data over its own prediction. The fix: estimate R from data (Chapter 8) instead of guessing it, and check that the innovations have about the spread the model predicts.
Chapter 6
Walk forward through the data one time bin at a time, and keep a Gaussian belief about the hidden state that you sharpen with every reading
You steer a ship at night with no GPS. Each hour you do two things. First you use your speed and heading to guess where you moved, and you admit that your guess is a little blurrier than before. Then a lighthouse comes into view, you take a bearing, and you tighten the guess. Dead reckoning blurs; a sighting sharpens. Sailors did this long before computers, and the Kalman filter does it with exact arithmetic.
The summary slide puts it in one line: the Kalman filter is similar to the forward pass in HMMs and computes P(xt | y1:t). That reads: the probability of the hidden state now, given all the data up to now and none after. It is the answer to “where is the state, as far as I can tell in real time?”
In a hidden Markov model (see our HMM lesson), the state is one of K labels. The forward pass keeps a list of K numbers, the belief over labels. Each step it does two things: it pushes the belief through the transition table (predict), and it multiplies by how well each label explains the new data, then rescales (update).
The Kalman filter does the same two things, but the belief is a Gaussian, so it needs only two objects, a mean μ and a covariance P, instead of a list of K numbers. And because Gaussians stay Gaussian under both steps, the belief never grows more complicated. That is what makes the answer exact.
The predict step pushes the belief through the dynamics equation. The mean moves by A, and the covariance grows by the kick Q, as in Chapter 4. The update step is the fusion of Chapter 5.
Use one hidden number with a = 0.9, C = 1, Q = 0.19 and R = 1. Begin with belief μ = 0 and P = 1 before the first reading. At step 1 there is nothing to predict, so P− = 1. Say y1 = 2.0. Then K = 1 / (1 + 1) = 0.5, μ1 = 0 + 0.5 × 2.0 = 1.0, and P1 = 0.5.
At step 2, predict first. μ− = 0.9 × 1.0 = 0.9, and P− = 0.81 × 0.5 + 0.19 = 0.595. Say y2 = 1.0. Then K = 0.595 / 1.595 = 0.373, and the innovation is 1.0 − 0.9 = 0.1. So μ2 = 0.9 + 0.373 × 0.1 = 0.937, and P2 = (1 − 0.373) × 0.595 = 0.373.
step 1: K = 0.500, μ = 1.000, P = 0.500 → step 2: K = 0.373, μ = 0.937, P = 0.373 (toy numbers)
Notice two things. The gain fell from 0.5 to 0.373, because after one reading the filter trusted its own belief more. And the covariance 0.373 does not depend on what y was. In fact K and P never depend on the data at all: only the means do. So in a real-time system, the whole sequence of gains can be computed ahead of time. Run long enough and K settles to a constant: here it reaches 0.304, where the uncertainty added by Q each step equals what each reading removes.
The device below has a hidden state of 2 numbers that spirals, read by 6 neurons through C from Chapter 3. Step through time. The purple path is the truth, which the filter never sees. The warm path is the filter’s mean, and the warm ring is its two-spread uncertainty. Switch on the blackout: the neurons go silent for steps 30 to 45, the filter can only predict, and the ring should swell.
Press Play, or drag the step slider. Left: the hidden plane with the true path (purple), the filter mean (warm) and its uncertainty ring. Right: the filter’s own uncertainty over time, with the blackout shaded.
Illustrative toy: A is a rotation by 0.2 radians with decay 0.99, dynamics noise 0.06, six neurons with unit-gain cosine tuning (Chapter 3), 80 steps from a known start. The filter uses the true A, C, Q and R. Its uncertainty is the square root of the trace of P, the total spread over both hidden numbers.
With the blackout off, the ring stays small and the warm path hugs the purple one. With it on, the warm path glides on by the dynamics alone, still circling at about the right speed, while the ring grows. When the neurons come back, the first reading pulls the estimate toward the truth and the ring collapses. That is predict and update in one picture.
The symptom: the estimate lags behind sudden changes in the truth, and the filter seems stubborn. The measurement: average the squared innovations after scaling each by the spread the filter predicted for it. If the average is well above 1, the filter is surprised too often. The cause: Q is too small, so the filter thinks the state barely moves. The fix: raise Q, or learn it with EM (Chapter 8).
Chapter 7
Run a second pass backward so that every time bin is estimated from all the data, and see the estimate sharpen
A detective arrives at a house at noon. From the evidence she has seen so far, she thinks the burglar entered at about 9 a.m., give or take two hours. At 3 p.m. a neighbour tells her about a car that left at 9:30. She now revises the morning. The neighbour’s tip arrived after 9 a.m., yet it narrows the 9 a.m. estimate. Evidence from later can improve belief about earlier, because earlier causes later.
The filter cannot do this. At each bin it knows only the data up to that bin. The summary slide names the fix: the Kalman smoother is a backward pass that computes P(xt | y1:T). The index runs to capital T, the end of the recording. This is the belief about the state at time t given all the data, before and after.
The dynamics link neighbours. If xt+1 is known well, then xt must lie near the place that A would carry to it. Suppose the filter says xt is around 1.0, but later data say xt+1 is around 0.94, a bit higher than the filter predicted (0.9). Then xt was probably a bit higher than 1.0 as well. The smoother turns that reasoning into an exact formula.
The smoother of Rauch, Tung and Striebel (1965) starts at the last step, where there is no future, so the smoothed belief equals the filtered one. Then it moves backward one step at a time. At each step it needs only what the forward pass already computed: the filtered mean and covariance at t, and the predicted mean and covariance at t + 1.
The term in brackets, μst+1 − μ−t+1, is the correction the future gave to the next step’s prediction. J carries that correction one step back. A matching term in the covariance shrinks the spread.
Continue Chapter 6’s example: a = 0.9, two readings, and T = 2. The filter gave μ1 = 1.0 with P1 = 0.5, then predicted μ−2 = 0.9 with P−2 = 0.595, and filtered to μ2 = 0.937 with P2 = 0.373. At the last step the smoother copies the filter: μs2 = 0.937.
Now step back to t = 1. The gain is J1 = 0.5 × 0.9 / 0.595 = 0.756. The correction from the future is 0.937 − 0.9 = 0.037. So μs1 = 1.0 + 0.756 × 0.037 = 1.028. The covariance: Ps1 = 0.5 + 0.7562 × (0.373 − 0.595) = 0.5 − 0.127 = 0.373. The second reading moved the first estimate up by 0.028 and cut its variance from 0.5 to 0.373.
t = 1: filter (1.000, P 0.500) → smoother (1.028, P 0.373) (toy numbers)
The device below shows one hidden number over 80 steps, read by one noisy neuron. Each estimate has a band of plus and minus two spreads. Turn the filter and smoother on and off, and try the blackout, steps 30 to 45, where no reading arrives.
Purple is the truth. Warm is the filter (forward pass). Pink is the smoother (forward then backward). Shaded bands are two spreads. Switch each estimate on and off, then try the blackout.
Illustrative toy: one hidden number with a = 0.95, C = 1, noise sizes set by the sliders, 80 steps, seeded random draws that change on New run. Both estimates use the true parameters. Errors are root mean square against the purple truth, computed live.
With both estimates on, the pink band is narrower than the warm band at every step except the last, where the two coincide. The pink line also tracks sudden turns earlier, because the filter learns of a turn only after the data show it, while the smoother also looks back from later readings. During a blackout the effect is largest: the smoother uses the readings on both sides of the gap to bridge it, and its band stays slim in the middle, whereas the filter’s band balloons.
The filter is causal: it needs no future, so it can run live. A brain-computer interface that moves a cursor from spikes must use a filter, since the future has not happened. The smoother needs the whole recording, so it belongs to offline analysis: cleaning up a trial’s trajectory for a figure, and, as the next chapter shows, the E-step of learning. A common middle path is a fixed-lag smoother, which waits a few bins before it commits and gets most of the gain.
For the full derivation and a line-by-line walkthrough, see our RTS smoother lesson and Kalman filter lesson. The forward-backward pair here is the continuous twin of the HMM’s forward and backward passes.
The symptom: smoothed paths look suspiciously perfect, and EM later returns tiny noise values. The measurement: compare the smoother’s band with the filter’s. If the two bands are nearly equal, the smoother gain J is near zero, which means the model has decoupled neighbours. The usual cause is an A that forgets too fast. The fix: check the fitted eigenvalues, and give the model a fair chance to keep memory.
Chapter 8
Alternate the filter-smoother with a regression, and watch the model fit itself to data it has never been given labels for
A teacher marks 200 exams but has lost the answer key. She guesses a key, grades with it, then notices which questions most students got “wrong” and rethinks the key. She grades again, and rethinks again. Each round the key and the grades agree a little better, and eventually the rounds stop changing anything. That loop of guess, grade, re-guess is the shape of EM.
So far we assumed we knew the parameters θ = {A, C, Q, R}. In practice you only have the neural data y. The hidden state x is never observed, so you cannot simply regress x on its past to find A. That is a chicken and egg problem: with the states you could find the parameters; with the parameters you could find the states.
The EM algorithm, from Lecture 16 (our EM for Gaussian mixtures lesson walks through the same loop), breaks the loop in two. The E-step fixes the parameters and computes the belief about the hidden variables given the data. The M-step fixes that belief and chooses the parameters that best explain it. Repeat. Each full round never lowers the log-likelihood, the log of the probability the model gives to your data, so the fit climbs until it levels out at a peak.
This is the summary slide’s E-step line: E-step: Kalman filter-smoother. For an LDS, the belief about the hidden states given all the data is exactly what the smoother computes. We do not need an approximation. The E-step outputs three kinds of numbers for each bin: the smoothed mean E[xt], the second moment E[xt xtT] = Pst + μst μsTt, and the lag-one cross moment E[xt xt−1T] = Pst Jt−1T + μst μsTt−1. These are the expected sufficient statistics: all the model needs to know about the unseen states.
Notice the second moment includes the covariance Ps, not just the mean squared. The states are uncertain, and the M-step must account for that uncertainty. Skipping it, by plugging in the smoothed means as if they were the truth, makes the noise estimates too small.
Look at what each parameter does and you see a regression. A predicts xt from xt−1. C predicts yt from xt. Q and R are the leftover residual spreads. If the states were known, you would solve each by least squares. Since they are not, you use the expected statistics in place of the products.
Q is the average squared residual of the dynamics regression, and R the average squared residual of the observation regression (usually kept diagonal). Both include the smoother’s uncertainty terms, which is why we stored the covariances.
Let one hidden number be tracked over 101 bins, so there are N = 100 consecutive pairs. Say the E-step gave these sums over the pairs: the cross moment sums to 88, the predecessor’s second moment sums to 100 and the state’s second moment sums to 100. Then anew = 88 / 100 = 0.88. The dynamics noise is qnew = (100 − 2 × 0.88 × 88 + 0.882 × 100) / 100 = (100 − 154.88 + 77.44) / 100 = 0.2256.
anew = 88 / 100 = 0.880 qnew = (100 − 154.88 + 77.44) / 100 = 0.226 (toy sums, for illustration)
The device runs the full loop on a scalar system: a hidden number with a, q and r unknown (the reading weight C is fixed at 1, which Chapter 9 explains). Start from a poor guess and press the button. The curve is the log-likelihood after each round, and it never goes down.
Left: the log-likelihood after each EM step. Right: the three parameters now (bars) against the values that made the data (ticks). Press Run 1 step a few times, then Run 20.
Illustrative toy: 200 bins simulated with a = 0.90, q = 0.19, r = 0.50 and a seeded random draw; the starting guess is a = 0.40, q = 0.80, r = 0.80. The E-step is the scalar Kalman filter and smoother, the M-step the formulas above, and the log-likelihood comes from the filter’s innovations. A finite record does not return the generating values exactly.
Two things to see. The log-likelihood jumps early and then flattens: the first rounds fix the big errors, and later ones polish. And the final parameters need not sit on the generating values. Two hundred noisy bins do not pin the dynamics noise q and the observation noise r apart exactly, because a bit more of one can mimic a bit less of the other. With more data the ticks and bars agree more closely.
EM climbs to a peak, but not always the highest peak. Real fits therefore start smart. A common recipe: run PCA (our PCA lesson, Lecture 3) on the neural data to get C, treat the projections as a first guess at the states, and regress them on their past to get A. Then let EM refine it. Run several starts and keep the one with the best log-likelihood.
The symptom: after many rounds, the fitted q is almost zero and the hidden states look like smooth curves with no wandering. The measurement: look at the fitted modulus of A, and at whether the log-likelihood is still creeping up by tiny amounts. The cause: the model has found that explaining everything as slow dynamics plus measurement noise scores well. The fix: compare the fit on held-out trials, keep the model with the better held-out likelihood, and consider a different latent dimension.
Chapter 9
See why the hidden axes can be rotated or stretched without changing a single prediction, and which numbers survive
Two mapmakers survey the same island. One puts north at the top and measures in miles. The other tilts her map 30 degrees and measures in kilometres. Their maps look different, and every distance between any two towns is the same. Nobody can say whose map is “the right one”, because the towns do not care. A latent state has the same freedom. It is a coordinate system we invented, and many coordinate systems explain the data equally well.
This matters the moment you fit an LDS and want to read the result. You find a hidden axis that rises when the monkey reaches left. Is that axis special? The model says no.
Pick any invertible n by n matrix M, and define a new hidden state x′ = M x. This relabels each hidden point with new coordinates, by stretching, rotating or shearing the axes. Now rewrite the model in the new coordinates. The dynamics become x′t = (M A M−1) x′t−1 + M εt, and the readings become yt = (C M−1) x′t + ηt. So the new parameters are A′ = M A M−1, C′ = C M−1 and Q′ = M Q MT, while R is untouched.
The reading is C′ x′ = C M−1 M x = C x, the same number as before. Every neural reading has the same probability under both parameter sets. The data cannot tell them apart, so the likelihood has a whole family of equal peaks. This is called non-identifiability: different parameters, identical predictions. For comparison, an ordinary regression has no such freedom.
Take A with rows (0.9, −0.2) and (0.2, 0.9), and C with one row (1.0, 0.5). Choose M = diag(2, 1), which stretches the first axis by 2. Entry (i, j) of M A M−1 is Aij times mi / mj, so A′ has rows (0.9, −0.4) and (0.1, 0.9). C′ = C M−1 = (0.5, 0.5). Start at x = (1, 0), so x′ = (2, 0). The original reading is 1.0 × 1 + 0.5 × 0 = 1.0. The new one is 0.5 × 2 + 0.5 × 0 = 1.0. Different matrices, the same neuron.
A quick check on A and A′: both have trace 1.8 and determinant 0.85, and these two numbers fix the eigenvalues. So the eigenvalues did not change.
A → A′ = M A M−1: entries change, eigenvalues stay (0.9 ± 0.2i). C → C′ = C M−1: (1.0, 0.5) → (0.5, 0.5), and every reading stays. (toy numbers)
Now play with it. Choose how much to rotate and stretch the hidden axes. The matrices change, and the predicted neuron traces, drawn once solid and once dashed, lie on top of each other.
Top: three neurons’ predicted traces under the original parameters (solid blue) and under the relabelled ones (dashed warm). Bottom: the matrix A before and after. Drag the rotation and the stretch.
Illustrative toy: A is the rotation-and-scale matrix with decay 0.95 and turn 0.30, C a fixed 3 by 2 matrix, 50 noise-free steps from (1.5, 0). The change of basis is M = (a rotation by your angle) times diag(your stretch, 1). The two sets of traces are computed separately with full matrix products, and the difference is measured, not assumed.
The solid and dashed lines never separate, while the entries of A′ wander. Look at the read-out: it reports the largest gap between the two sets of predictions, which is at the level of rounding error, and the eigenvalue moduli of A and A′, which agree.
Some quantities do not change under any M, and these are the ones to trust. The eigenvalues of A are safe: they set the speeds and spins of the dynamics. The subspace spanned by the columns of C is safe: it says which directions of neural activity carry the latent. The predicted neural activity and the log-likelihood are safe. What is not safe is any single axis or any single entry of A or C.
Practice handles the freedom by fixing a convention, for instance asking for C with orthonormal columns, or Q equal to the identity. A convention picks one map from the family, but it does not make that map special. If you want an axis to mean something, such as hand velocity, you must tie it to the behaviour by a separate step, for example by regressing the behaviour on the smoothed latent.
Three more limits travel with the model. First, linear: a state that follows a curved rule, such as one that saturates, is only approximated, and the fit may need extra latent dimensions to compensate. Second, Gaussian: spike counts break that assumption, and a transform or a Poisson version is the usual repair (Chapter 3). Third, time-invariant: A, C, Q and R are the same at every step. A system whose dynamics change with the task, for example between a rest and a reach, will not fit one A.
How many hidden numbers should there be? More always raises the training likelihood, so training fit cannot tell you. Compare on held-out trials, as Lecture 13 teaches, and stop where the held-out score stops rising. Compare also with factor analysis, which is the same observation model with no dynamics: an LDS is factor analysis whose latents are tied together in time.
The symptom: you fit the same data twice from different starts, and the matrices A and C look completely different. The measurement: compare the eigenvalues of A and the log-likelihood, not the entries. If those agree, nothing is wrong; you have met the family of equal fits. The fix: compare models only through basis-free numbers, and fix a convention before you plot axes.
Chapter 10
Review the model, the filter and the smoother in one place, with the numbers, a checklist, the core code and where to go next
You can now rebuild Lecture 22 from memory. A hidden state moves by a linear rule and a little noise. Neurons report a noisy linear mix of it. The Kalman filter tracks the state forward in real time, the Kalman smoother uses the whole record, and EM alternates the smoother with regression to learn every parameter. The lecture’s own summary slide lists the model, the settled spread, the E-step, the filter and the smoother.
A latent linear dynamical system has a hidden state xt = A xt−1 + B ut + εt and readings yt = C xt + ηt, with Gaussian noise of covariance Q and R. Its parameters are {A, C, Q, R} plus B for inputs. The settled spread of the state solves P = A P AT + Q. The Kalman filter computes P(xt | y1:t) by predicting with A and fusing each reading by the gain K. The smoother computes P(xt | y1:T) with a backward pass. Together they are the E-step of EM, and the M-step is a regression on expected statistics. The hidden axes are defined only up to a change of basis.
| What | Number or form | Why it matters |
|---|---|---|
| Dynamics equation | xt = A xt−1 + B ut + εt | The hidden state moves by a linear rule plus a kick |
| Observation equation | yt = C xt + ηt | Neurons report a noisy linear mix |
| Parameters | θ = {A, C, Q, R}, plus B | What EM must learn; n = 10, m = 90 gives 1,145 numbers |
| Settled covariance | P = A P AT + Q (a = 0.9, Q = 0.19 gives P = 1.00) | Needs every eigenvalue of A below 1 in modulus |
| Gaussian fusion | precisions add (1 + 1/3 = 1.333, so variance 0.75); K = 0.25 | The one move the filter repeats |
| Kalman filter | predict, then update; gain 0.5, then 0.373, then 0.304 in the limit | Forward pass, P(xt | y1:t), runs live |
| Kalman smoother | J = 0.756; variance 0.50 down to 0.373 | Backward pass, P(xt | y1:T), offline |
| EM | E-step: filter-smoother; M-step: regression; log-likelihood never falls | Learns the parameters without seeing the states |
| Change of basis | A′ = M A M−1, C′ = C M−1 | Same predictions; trust eigenvalues, not axes |
pythonimport numpy as np
from scipy.linalg import solve_discrete_lyapunov
def kalman_filter(y, A, C, Q, R, m0, V0):
T, n = len(y), len(m0)
mu, P, mu_p, P_p = [], [], [], []
m, V = m0, V0
for t in range(T):
if t > 0:
m, V = A @ m, A @ V @ A.T + Q # predict
mu_p.append(m); P_p.append(V)
S = C @ V @ C.T + R # innovation covariance
K = V @ C.T @ np.linalg.inv(S) # Kalman gain, n by m
m = m + K @ (y[t] - C @ m) # update the mean
V = (np.eye(n) - K @ C) @ V # update the covariance
mu.append(m); P.append(V)
return mu, P, mu_p, P_p
def rts_smoother(A, mu, P, mu_p, P_p):
T = len(mu)
ms, Vs = list(mu), list(P)
for t in range(T - 2, -1, -1):
J = P[t] @ A.T @ np.linalg.inv(P_p[t + 1]) # smoother gain
ms[t] = mu[t] + J @ (ms[t + 1] - mu_p[t + 1])
Vs[t] = P[t] + J @ (Vs[t + 1] - P_p[t + 1]) @ J.T
return ms, Vs
# settled spread of the hidden state: P = A P A^T + Q
P_inf = solve_discrete_lyapunov(A, Q)
# E-step of EM: forward pass, then backward pass
mu, P, mu_p, P_p = kalman_filter(y, A, C, Q, R, np.zeros(len(A)), P_inf)
ms, Vs = rts_smoother(A, mu, P, mu_p, P_p) # ms[t] = E[x_t | y_1..T]
The shapes: y is T×m, A is n×n, C is m×n, K is n×m and each mu[t] is length n. The filter returns the predicted values too, because the smoother needs them. I checked this code on a simulated 2-number state read by 20 neurons: the smoothed root mean square error was below the filtered one, and the smoothed covariance was below the filtered one.
An LDS is factor analysis with dynamics, and an HMM with a continuous state. Its filter is the linear-Gaussian case of Bayes filtering; when the dynamics or readings are curved, the extended and unscented filters take over. In a brain-computer interface, a Kalman filter is a standard decoder that turns recorded neural activity into cursor motion. Modern latent-variable models for neural data replace the linear steps by neural networks, but they keep the same two equations’ shape: a hidden state that evolves and a reading that reports it.
This lesson follows Lecture 22 of Statistical Modeling and Analysis of Neural Data (NEU 560), Princeton, Spring 2024, taught by Jonathan Pillow. The slides and course materials are on the course site. We re-teach the ideas in our own words and devices, and add the filter, smoother and EM details from Bishop’s Pattern Recognition and Machine Learning, chapter 13 (linear dynamical systems). The smoother is that of Rauch, Tung and Striebel (1965), and the filter that of Kalman (1960). All toy numbers on this page are labelled illustrative.
Now press Present or Teach and explain, from memory, how a hidden state, two noises and one gain turn jittery spikes into a smooth estimate. Then go back to the filter at the top and move the noise again.