A Kalman filter is only as good as the noise you tell it. Make the target 10 times jumpier than its model says, and its error is 1.63. One gain, learned by gradient descent from 20 logged tracks, gets 0.99: the same as a filter told the truth.
Make the target jumpier and watch the textbook filter fall behind. Then we build, piece by piece, the filter as a computation graph, learned noise, BackpropKF, KalmanNet and differentiable particle filters.
You need the Kalman filter (Lesson 5) and the idea of a gradient. We build the rest from zero.
Lesson 20 of the series Sensor Fusion: Classical to Modern. The methods come from six papers, 2016 to 2022: Haarnoja, Jonschkowski, Karkus, Revach, Kloss and Corenflos with their co-authors. The devices and toy numbers are our own.
An illustrative toy: a random walk read by a sensor with noise variance 1, 200 steps. The textbook filter assumes process noise 1. The learned gain is one number fitted by gradient descent on 20 other logged tracks. The pink filter is told the true process noise.
Chapter 0
Tune a filter by hand for two kinds of ground, and find that no single setting wins both
A legged robot walks from a smooth floor onto loose gravel. Its Kalman filter fuses a step-by-step prediction with a noisy position reading. On the floor it tracks well. On the gravel it falls behind, and its variance still says it is sure.
Nothing in the filter broke. Lesson 5's filter needs four things you write by hand: how the state moves, how the sensor reads it, and two noise sizes. The process noise Q is how far the state can jump in one step beyond the model. The measurement noise R is the variance of each reading. On gravel, the true Q is larger than the one you wrote.
Both numbers set the Kalman gain, the trust dial between the prediction and the reading. Call the variance of the prediction P̄, the noise you assume for the reading R, and the gain K.
K equals P-bar, over P-bar plus R.
Add the prediction's variance P-bar to the reading's variance R. Divide P-bar by that total. The result K says how far the estimate moves toward the reading.
With made-up numbers: P̄ = 4 and the true R = 4, so K = 4 / 8 = 0.5. Write R = 0.25 by mistake and K = 4 / 4.25 = 0.94: the filter chases the noise. Write R = 100 and K = 0.038: it ignores a good sensor.
The left half is floor (true Q = 1), the right half gravel (true Q = 10). The blue band is the doubt the filter claims. Slide the Q you assume.
An illustrative toy: a random walk, 100 steps with Q = 1 then 100 with Q = 10, read with R = 1. The filter knows R and uses your Q for both halves.
Set Q = 1, right for the floor: the error is 0.82 on the floor and 1.29 on gravel. Set Q = 10, right for gravel: 0.99 and 0.95. Every setting gives one surface away. Engineers spend days on this, and the tuning breaks when the ground changes again.
This lesson keeps the filter's structure and learns the parts you cannot write. The structure you trust stays as fixed maths. The parts you do not know come from logged data, by gradient descent.
| Approach | Needs | Data | You can inspect |
|---|---|---|---|
| Hand-built filter | the full model and both noises | none | every quantity |
| Learned filter | the filter's structure | tens to hundreds of logged runs | the gain, the learned noise |
| Black-box network | nothing | the most | little |
Symptom: the filter tracks on one surface and lags on another, while its variance stays small.
Measure: look at the innovations, reading minus prediction. Long runs of one sign, larger than the filter predicts, mean Q is too small (Lesson 21 makes this a test).
Fix: retune Q for each regime, or learn it (Chapters 2 and 4).
Chapter 1
Push a tracking error backward through one update and let gradient descent move the gain
Every step of a Kalman filter is a multiply, an add or a divide. Each one is smooth: nudge an input a little and the output moves a little. So the whole filter is a computation graph, the same kind of object as a neural network.
That means backpropagation works through a filter: the chain rule, applied from the loss back to each input. Give the filter a loss, one number that says how wrong it was. The gradient of the loss says which way to move each part you want to learn.
Start with one update. Call the prediction x̄, the reading z and the gain K. The new estimate x̂ is:
x̂ = x̄ + K (z − x̄)
A logged run gives the true state x, and the loss is the squared error L = (x̂ − x)². How fast does L change when K moves?
The partial of L with respect to K equals two times x-hat minus x, times z minus x-bar.
Take the miss x-hat minus x and double it. Multiply by the innovation z minus x-bar. A negative result says a larger K lowers the loss.
With made-up numbers: x̄ = 10, z = 14, x = 13.5 and K = 0.5. Then x̂ = 12, the miss is −1.5, and ∂L/∂K = 2 × (−1.5) × 4 = −12. One step K ← K − η × (−12), with learning rate η = 0.02, gives K = 0.74.
Top: where each value sits. Bottom: the loss against K, with the purple tangent. Press Step to move K downhill once.
Illustrative numbers. The prediction stays at 10 and the learning rate at 0.02.
The second step gives x̂ = 12.96 and a gradient of −4.32, so K = 0.826. Each step multiplies the miss by 1 − 2η(z − x̄)² = 0.36. K settles at 0.875, where x̂ lands on the truth. No Q, R or P appeared anywhere.
A real filter runs many steps. The loss adds up over all of them, and each gradient flows back through every earlier update. Chapter 8 shows what that does over long runs.
Symptom: K jumps past the answer, further on each step.
Measure: the factor 1 − 2η(z − x̄)². Below −1 the steps grow. With η = 0.07 it is −1.24, and K goes 0.5, 1.34, 0.30, 1.59.
Fix: lower the learning rate. Here it must stay below 1 / (z − x̄)² = 0.0625.
Chapter 2
Fit the sensor's noise from the readings alone, by gradient descent on the likelihood
The smallest hybrid keeps all of Lesson 5's filter and learns only Q and R. The predict step, the gain formula and the update stay as written. Two numbers you used to tune by hand now come from data.
Chapter 1's loss needed the truth. This one needs only the readings. Before each reading, the filter predicts it and says how unsure it is. The innovation yt = zt − x̄t should have variance St = P̄t + R. If R is right, the innovations have exactly that spread.
The negative log-likelihood (NLL) scores how well the claimed spreads fit the innovations. Call the number of steps T and the average loss ℓ.
Ell equals one over T, times the sum over t of one half of, log S-t plus y-t squared over S-t.
For each step, add the log of the claimed spread S-t to the squared surprise y-t squared over S-t. Halve it and average. Too small an R makes surprises expensive. Too large an R makes the log term expensive.
With made-up numbers, one step with y = 3: S = 1 costs ½(0 + 9) = 4.50. S = 9 costs ½(2.20 + 1) = 1.60. S = 20 costs ½(3.00 + 0.45) = 1.72. For one surprise, the best S is y² = 9.
R must stay positive, so learn its logarithm ρ and use R = eρ. The gradient of ℓ flows back through every St and P̄t of the run, because R feeds every later step.
The curve is the loss for every R on this run. The dashed line is the true R. Press Learn R, or drag R and try from somewhere else.
An illustrative toy: 200 steps of a random walk with Q = 1, known to the filter, read by a sensor with true R = 4. Gradient descent on ln R with step size 1.5.
Start at R = 20. Gradient descent goes 20, 12.0, 8.0, 6.0, 5.0, and settles at 3.98 after 15 steps. The loss falls from 1.742 to 1.422, and the steady gain rises from 0.20 to 0.39. No step used the true position. The same gradient fits ln Q.
Symptom: the learned R runs to zero, or the loss turns into NaN.
Measure: log R during training. A step that makes R negative leaves ln S undefined.
Fix: learn ln R (for a matrix, a Cholesky factor), and cap the step size.
Chapter 3
Let a network read each image, report a reading and its own doubt, and train both through the filter
Sometimes the sensor is a camera and each reading is a picture. No formula turns pixels into a position. Haarnoja, Ajay, Levine and Abbeel (NeurIPS 2016) put a convolutional network, a network built for images, in front of a Kalman filter. They called the whole graph BackpropKF.
The network reads frame t and outputs two things: a reading zt and its covariance Rt. The filter fuses them as usual. The loss compares the filter's track with the logged truth, and the gradient flows back through the filter into the network's weights.
No frame has a label that says how unsure the network should be. The filter supplies that signal: on a blurred frame, a confident wrong reading drags the track off, the loss rises, and the gradient raises Rt.
The partial of x-hat with respect to R equals minus P-bar times z minus x-bar, over P-bar plus R, squared.
Raising R lowers the gain, so x-hat slides back toward x-bar. Multiply P-bar by the innovation and divide by the squared total doubt: that is the slide per unit of R. Times 2(x-hat minus x), it is the loss gradient.
With made-up numbers: truth 5.0, x̄ = 5.2, P̄ = 1, and on a blurred frame the network says z = 8.0. With R = 0.1, K = 0.909 and x̂ = 7.75, a miss of 2.75. Then ∂x̂/∂R = −2.8 / 1.21 = −2.31, and ∂L/∂R = 2 × 2.75 × (−2.31) = −12.7: raise R. With R = 25, x̂ = 5.31, a miss of 0.31.
In the shaded frames a distractor hides the target and the readings jump 3 units off. The warm strip is the R reported on each frame. Choose the network.
An illustrative toy: 80 frames of a slow random walk (Q = 0.02), clear readings with variance 0.25. R per frame uses 100 on hidden frames; One R is the best single value, found by search.
With R per frame, the error is 0.30. The best single R is 189, so the filter ignores the camera and coasts: error 0.60. An over-sure network gives 1.42. The paper saw the same: one learned R grows huge.
On the paper's task, a red disc hidden by distractor discs, BackpropKF reached an RMS error of 0.054. A one-R filter got 0.116 and an LSTM 0.141, each trained on 100 sequences.
Symptom: the track is fine on clear frames and jumps whenever the target is hidden.
Measure: plot Rt against the frames. A flat Rt means the network never learned to doubt.
Fix: train through the filter, with hidden frames in the data.
Chapter 4
Keep predict and update, let a small recurrent network output the gain, and compare it with the best gain
The gain needs Q, R and the covariance recursion, the parts you are least sure of. KalmanNet (Revach et al., 2022) keeps the predict step and the update x̂ = x̄ + K(z − x̄). A GRU, a small recurrent network, replaces only the gain computation.
Each step the GRU reads differences the filter already has, such as the innovation, and outputs the gain Kt. Its memory stands in for the covariance P. It trains on the squared error to logged true states by backpropagation through time, the chain rule run back over the steps.
What gain should it find? For a random walk and a fixed gain, the error has a closed form. Call the true process noise q, the sensor noise r, the error et and its long-run variance E:
et = (1 − K)(et−1 − wt) + K vt ⇒ E = (1 − K)²(E + q) + K² r
Here wt is the target's jump and vt the reading's noise. Solve for E:
E of K equals one minus K, squared, times q, plus K squared times r, all over K times two minus K.
A small K misses the jumps q; a large K lets in the noise r. Add the two and divide by K(2 − K) to get E. The K with the smallest E is the Kalman gain for the true q.
With made-up numbers: q = 10, r = 1, a target ten times jumpier than the model's q = 1. The model's gain is 0.618, so E = (0.146 × 10 + 0.382) / 0.854 = 2.16, an RMSE of 1.47. The best gain is 0.916, with E = 0.916 and an RMSE of 0.957.
The curve is the RMSE for every fixed gain. Blue is the gain the model computes from q = 1. Pink is the best. Set the true q and press Train.
Exact for a random walk with r = 1. Train runs gradient descent on the curve from K = 0.5; the 0.917 below came from 20 simulated tracks.
Gradient descent on the hero's 20 logged tracks found K = 0.917, without ever seeing q. KalmanNet's own tests rotated the true state-evolution matrix 10° or 20° away from the model. KalmanNet beat the model-based Kalman filter by 3 dB, half the mean squared error, and came close to a filter that knew the true matrix.
Symptom: the learned gain tracks in testing and lags when the robot speeds up.
Measure: plot Kt against speed or surface. A gain that never rises was never shown fast motion.
Fix: training data that covers the conditions (Chapter 6).
Chapter 5
See why a hard resample passes no gradient, and how a soft resample lets a biased one through
A particle filter carries a cloud of guesses. Each step it moves them with a motion model and weights them with a measurement model. Then it resamples: it draws a new cloud that copies heavy particles and drops light ones. To learn both models end to end, the gradient must pass all three steps.
Moving and weighting are smooth. Resampling is not: it picks whole particles by index, and every copy gets the same weight. Nudge a weight and the same particles survive, so the output does not move. Nudge it past a threshold and another particle survives, so the output jumps. A staircase has no useful slope.
Jonschkowski, Rastogi and Brock (RSS 2018) built a differentiable particle filter with learned models. Their gradient stops at resampling, after one loop iteration. Karkus, Hsu and Lee (CoRL 2018) proposed soft resampling. It draws from a blend of the weights and an even spread, then corrects with an importance weight. Call particle k's weight wk, the particle count N and the blend α.
W-prime-k equals w-k, over alpha times w-k plus one minus alpha over N.
Draw particles with chance alpha times w-k plus one minus alpha over N. Give each copy the weight w-k divided by that chance. Because w-k stays in the weight, the gradient reaches the measurement model.
With made-up numbers: N = 16, α = 0.5. A heavy particle with w = 0.20 has draw chance 0.10 + 0.031 = 0.131, and each copy weighs 0.20 / 0.131 = 1.52. A light one with w = 0.01 has chance 0.036, and each copy weighs 0.28. With α = 1 every copy weighs 1: hard resampling.
Top: 16 particles, bar height is weight, dots are surviving copies. Bottom: the estimate against the sensor offset θ. Pink is the exact weighted mean.
An illustrative toy: 16 fixed particles, a Gaussian likelihood of width 0.8 centred on θ, and systematic resampling with one fixed random offset. Slopes hold the survivors fixed, as backpropagation does.
At θ = 0.5 the weighted mean rises 0.494 per unit of θ. The hard gradient is 0. With α = 0.5 the soft gradient is 0.35, and 0.30 averaged over 2,000 random offsets: it flows, but biased low. Corenflos et al. (ICML 2021) showed the bias does not shrink with more particles. Their resampling uses entropy-regularized optimal transport: consistent gradients, at a cost of N² per step in training.
Symptom: the measurement model's loss never moves.
Measure: its gradient norm is exactly 0 after every resample.
Fix: soft or optimal-transport resampling, or skip resampling in training while particles stay near the truth (Karkus et al. found that works).
Chapter 6
Fit a gain on one kind of ground, drive it on others, and find where it beats the textbook filter and where it loses
Here is the whole bargain in one device. The textbook filter assumes q = 1. The learned filter fits its gain on 20 logged tracks from one kind of ground. Then you drive both on any ground you like.
Pick the ground the logs came from: the learned gain trains on them by gradient descent. Then slide the test ground. The curves give each filter's error on every ground. The oracle is told the true q every time, so it is the best any fixed gain can do.
Top: RMSE against the true q of the test ground, on a log axis. The teal tick marks where the logs came from. Bottom: the three gains at the test ground.
An illustrative toy with r = 1. Training is real: gradient descent on 20 simulated logs of 200 steps. The curves are the exact long-run RMSE of each fixed gain.
Train on rough logs. The gain lands on 0.914 and matches the oracle at q = 10: an error of 0.957, against 1.47 for the textbook filter. Now drive it on calm ground, q = 0.1. It scores 0.918, worse than the textbook filter's 0.681. Train on calm logs and drive on rough ground, and it scores 3.51 against 1.47.
The learned gain is excellent where its data came from. Away from that, a hand-built model can beat it. The textbook filter is the best only at its own q, but it is never far off near it.
Chapter 7
Scale both noises together, watch the track stay still while the stated doubt changes, and see which loss notices
Two losses train most differentiable filters. The squared error compares the estimate with the logged truth. The NLL of Chapter 2 also scores the variance the filter reports. They do not learn the same thing.
Multiply Q, R and the starting P by one factor c. Then P̄ also scales by c, and the gain does not change:
K = cP̄ / (cP̄ + cR) = P̄ / (P̄ + R)
So the track does not change, and neither does the squared error. Only the variance P that the filter states moves: it now claims c times the doubt. A loss that sees only the track cannot find c.
The check for honest doubt is the normalized estimation error squared (NEES), the test of Lesson 21. Call the error at step t et = x̂t − xt, the variance the filter states Pt, and the average ε̄.
Epsilon-bar equals one over T, times the sum over t of e-t squared over P-t.
Square each error e-t and divide it by the variance P-t the filter claimed. Average over the run. Far above 1, the filter is too sure. Far below 1, it is too unsure.
From the toy below: with c = 1, ε̄ = 0.91. With c = 0.1, the filter claims P = 0.062 and ε̄ = 9.1, so it claims to be about 3 times surer than it is (√9.1 = 3.0). With c = 10, ε̄ = 0.09.
The teal line is the estimate and the band is the doubt it claims. Slide c, which multiplies Q, R and the starting P together.
An illustrative toy: 200 steps of a random walk with true Q = 1 and R = 1. The band is ±2√P. The view shows steps 100 to 160.
The RMSE is 0.751 for every c. The NLL is 4.59 at c = 0.1, 1.01 at c = 1 and 1.69 at c = 10: lowest at the honest scale. A filter trained only on squared error has a free scale, so its variance means nothing. Kloss, Martius and Bohg (Autonomous Robots, 2021) recommend the NLL for learning accurate noise models, mixed with the squared error if training struggles.
Symptom: a good RMSE, but a planner that trusts the stated variance takes risks it should not.
Measure: NEES on held-out runs (Lesson 21).
Fix: train with the NLL, or a mix of the NLL and the squared error.
Chapter 8
Watch gradients die or explode through time, and list the other failures with a test for each
A learned filter fails in ways the textbook filter does not. Some show up in training, some only in the field. The first one comes from running the chain rule back through many steps.
The loss at step t depends on the estimate k steps earlier, through k updates. Take a scalar model that multiplies the state by a each step. Each update then multiplies the estimate by a(1 − K), and so does the gradient on its way back.
The partial of x-hat-t with respect to x-hat-t-minus-k equals a times one minus K, to the k.
Each step back, the gradient picks up one more factor of a times one minus K. Below 1, it dies away. Above 1, it grows without limit.
With made-up numbers: a = 1 and K = 0.618 give 0.382 per step, and 0.000066 after 10 steps: the far past teaches nothing. Early in training, a = 1.2 and K = 0.05 give 1.14 per step, and 189 after 40 steps: the gradient explodes.
Each bar is the factor the gradient carries k steps back, on a log axis. The line is 1. Change the dynamics a and the gain K.
Exact for a scalar filter with a fixed gain. Real filters multiply matrices, so the largest eigenvalue plays the part of a(1 − K).
A tuned filter is stable, so its own factor is below 1. Training still passes through bad gains on the way there. KalmanNet warms up on short, truncated windows before full backpropagation through time. Kloss et al. name stable training the main challenge of differentiable filters.
| Failure | Symptom | Test | Fix |
|---|---|---|---|
| Exploding gradient | the loss spikes to NaN | log the gradient norm | clip it; start with short windows |
| Vanishing gradient | slow effects are never learned | gradient against steps back | longer windows after a warm-up |
| Out of distribution | good in tests, poor on new ground | hold out whole conditions | logs that cover them; a textbook fallback |
| Dishonest doubt | good RMSE, NEES far from 1 | NEES and NIS (Lesson 21) | the NLL loss |
| Silent extrapolation | innovations larger than any in training | watch the innovation range at run time | alarm and switch to the textbook filter |
| Biased particle gradient | more particles, no better model | compare with optimal-transport resampling | optimal-transport resampling |
Symptom: training runs for an hour, then the loss jumps to infinity in one step.
Measure: the gradient norm per step, and a(1 − K) at the current parameters.
Fix: clip the gradient norm, lower the learning rate, and train on short windows first.
Chapter 9
Keep the methods, the numbers, the checks and the code in one place
A Kalman filter is a computation graph, so a loss can train any part of it. Keep the parts you trust as fixed maths, learn the parts you cannot write, and check the stated doubt as hard as the error.
| Method | What it learns | What stays | Reach for it when | Number to remember |
|---|---|---|---|---|
| Learned Q and R | the two noise sizes | the whole filter | the model is right, the noise unknown | toy: R from 20 to 3.98 (true 4) |
| BackpropKF | a network giving zt and Rt from images | the filter behind it | the sensor is a camera | red disc: 0.054 against 0.116 |
| KalmanNet | the gain Kt, from a GRU | predict and update | the model is off, Q and R unknown | 3 dB over the KF, rotated F |
| Differentiable PF | motion and measurement models | the particle loop | the belief has several peaks | about 80% less error than an LSTM |
| Soft resampling | nothing; it passes a gradient | resampling, blended | training a particle filter end to end | toy: slope 0.35 against 0.494 |
| Optimal transport | nothing; a consistent gradient | resampling, made smooth | the soft bias hurts | N² cost in training only |
pythonimport numpy as np def filter_loss_and_grad(K, z, x): # a fixed-gain filter on a random walk; forward-mode gradient of the MSE in K xh, d, se, dse = 0.0, 0.0, 0.0, 0.0 for zt, xt in zip(z, x): y = zt - xh # innovation d = (1 - K) * d + y # d xh / dK, carried through every step xh = xh + K * y # the same update as Lesson 5 se += (xh - xt) ** 2 dse += 2 * (xh - xt) * d return se / len(z), dse / len(z) def nll(R, z, Q=1.0): # Chapter 2's loss: only the readings are needed xh, P, total = 0.0, 1.0, 0.0 for zt in z: Pb = P + Q; S = Pb + R; y = zt - xh total += 0.5 * (np.log(S) + y * y / S) K = Pb / S; xh += K * y; P = (1 - K) * Pb return total / len(z) def soft_weights(w, alpha): # Chapter 5: draw with q, carry w / q so the gradient reaches w q = alpha * w + (1 - alpha) / len(w) return q, w / q
Now press Present or Teach. Explain from memory the gradient through one update, the NLL, the push on R, the best gain and the soft weight. Then go back to the hero, pick 100×, and say why the teal bar barely moves.