A drone flies into smoke. A hand-built filter loses its features and drifts. A network alone keeps reading but jitters and lies. Over 100 toy runs, the filter misses by 4.4 m and the network by 1.7 m. The hybrid of the two misses by 0.7 m.
Pick an estimator and drag the smoke. Watch the error inside the shaded zone. Then we build the hybrid piece by piece, from the filter as a layer to the gate that catches a lie.
You need the Kalman filter's predict and update and what a neural network learns. We rebuild the bridge from both sides.
The capstone of the VNAV series on Engineermaxxing. Before it: Robust SLAM Frontiers. The classical half in depth: The Kalman Filter.
Illustrative toy, 1-D, 140 steps. Smoke hides the hand-picked features over that share of the zone; the network's read gets noisier and sometimes confidently wrong. The 100-run averages use seeds 1 to 100 of this same simulation.
Chapter 0
See why a written-down filter and a trained network fail in opposite ways
A drone flies through a warehouse with a camera and an IMU. Then smoke rolls in and a long blank wall slides past. There are no corners to track. The drone must still know where it is.
The estimation side writes the physics down. It defines a state, a motion model and a sensor model. Then it runs a Kalman filter: a loop that predicts the state and corrects it with each measurement. It needs little data and reports its own doubt. But it trusts its model. With no features, it coasts on the prediction and drifts.
The learning side trains a network on many frames with known poses. The network reads shading and learned priors, so it keeps giving an answer in smoke. But it has no built-in doubt and no memory of the last frame. It jitters, and sometimes it is wrong with full confidence.
| Side | Strength | Failure in smoke |
|---|---|---|
| Estimation | Physics, memory, a calibrated variance, little data | No measurements, so it coasts and drifts |
| Learning | Reads raw pixels, learns priors no one can write | Jitters frame to frame, lies with confidence |
Each side's strength covers the other's failure. The rest of this lesson is a ladder. On each rung you keep the parts you can write down and learn only the part you cannot.
Each box is one part of a filter. Teal boxes are parts you write down; purple boxes are parts you learn. Pick a rung and see what changes colour and what you keep.
A map of this lesson, not a measurement. Each rung is one chapter.
Chapter 1
Run one Kalman cycle by hand and see that every step is a smooth function
A deep learning framework sees a model as a computational graph: a chain of smooth operations that gradients flow back through. A Kalman filter is already such a chain. It only adds, multiplies and divides.
Take the 1-D case. The state is one number, the drone's position along a corridor. The filter carries a belief: a mean μ ("mu") and a variance P. One cycle has two steps.
Predict. A command u moves the drone. The world adds surprise with variance Q, the process noise. The predicted mean and variance get a hat:
μ̂ = μ + u P̂ = P + Q
Update. A sensor reads z, with measurement noise variance R. How far should the belief move toward z? The Kalman gain K answers. It compares the two doubts.
K equals P-hat, divided by P-hat plus R.
Add the model's doubt P-hat to the sensor's doubt R. K is the model's share of that total. A big R makes K small, so the filter ignores the sensor.
With made-up numbers: P-hat = 3 m² and R = 5 m². K = 3 / (3 + 5) = 0.375.
mu equals mu-hat, plus K times the quantity z minus mu-hat.
Find the gap y between the measurement z and the prediction mu-hat. Move mu-hat by the share K of that gap. The result is mu.
With made-up numbers: mu-hat = 3 m, z = 5 m, K = 0.375. The gap is 2 m, so mu = 3 + 0.375 × 2 = 3.75 m.
The full cycle, every number shown: start at μ = 0, P = 1, command u = 3, Q = 2. Predict gives μ̂ = 3 and P̂ = 3. The sensor says z = 5 with R = 5. Then K = 0.375, μ = 3.75, and the new variance is (1 − K) × P̂ = 1.875. That is smaller than both 3 and 5: fusing two doubts sharpens the belief.
Teal is the prediction, orange the measurement, blue the fused belief. Drag R and z. Watch K, the trust slider, move.
The prediction is fixed at mu-hat = 3, P-hat = 3, the hand example above.
Each line is a sum, a product or one division by P̂ + R, which is always above zero. So the cycle is a smooth map from (μ, P, u, z, Q, R) to the new (μ, P). That map is a layer. Stack it, put a loss on its output, and backprop gives the gradient of the loss with respect to Q and R.
Failure. Symptom: autograd returns NaN gradients. Measure: log P̂ + R each step; it hit zero or went negative because the optimizer pushed a raw R below zero. Fix: learn log R and use R = elog R, which is always positive.
Chapter 2
Replace hand-tuning with a loss, a chain rule and a step downhill
Your filter works in the lab and fails in the field. So you nudge Q and R by hand. Too big an R and the filter is sluggish. Too small and it chases noise.
A differentiable filter turns this into training. Record trajectories with ground truth. Run the filter over them. Add up the squared error between each estimate and the truth. Backprop that loss to Q and R and take a step. The gradient must flow back through every step of the loop, so this is backpropagation through time (BPTT), the same algorithm that trains an RNN.
Start with one step so the gradient is not magic. Call the truth x and the squared error L = (μ − x)². The chain rule splits the gradient in two:
d-L by d-R equals two times mu minus x, times d-mu by d-R.
Ask two questions and multiply the answers. How much does the loss L move when mu moves? How much does mu move when R moves? Then step R against the sign of the product.
From Chapter 1: mu = 3.75, truth x = 4, mu-hat = 3, P-hat = 3, y = 2, R = 5. The first factor is 2 × (3.75 − 4) = −0.5. The second is −3 × 2 / 8² = −0.094. The product is +0.047, so lower R. One step of size 10 gives R = 4.53, mu = 3.80, and the loss falls from 0.0625 to 0.041.
The sign makes sense. The truth (4) sits nearer the measurement (5) than the prediction (3). So the filter should trust the sensor more: shrink R, grow K.
The curve is the trajectory loss for every R. The yellow ball is the filter's current R. Set a bad start, press Train, and watch it roll downhill toward the dashed true R.
Illustrative toy: 20 random-walk trajectories of 100 steps, true Q = 1 and true R = 4. Gradient descent on log R with the exact forward-mode gradient. It settles near 4.3, not 4.0, because 20 trajectories are a finite sample.
pythonimport torch log_R = torch.tensor(3.2, requires_grad=True) # R = e^3.2 = 25, a bad start opt = torch.optim.Adam([log_R], lr=0.05) for epoch in range(200): loss = 0.0 for z_seq, x_seq in trajectories: # z_seq, x_seq: tensors of shape (T,) mu, P, R = torch.tensor(0.), torch.tensor(1.), log_R.exp() for z, x in zip(z_seq, x_seq): # unroll the filter: BPTT P_hat = P + Q K = P_hat / (P_hat + R) mu = mu + K * (z - mu) P = (1 - K) * P_hat loss = loss + (mu - x) ** 2 opt.zero_grad(); loss.backward(); opt.step() print(log_R.exp()) # near the true sensor variance
Failure. Symptom: the learned R is good on the training logs and bad on a new day. Measure: compare the loss on held-out trajectories. Fix: train on logs from every condition you will fly in. Two numbers cannot learn weather they never saw.
Chapter 3
Learn the sensor model from images and let the network set R for each frame
The drone must track a box on a shelf from camera images. No one can write an equation from pixels to the box's position. So we learn that piece, the observation model, and keep the rest.
Backprop KF (Haarnoja, Ajay, Levine and Abbeel, 2016) did this. A convolutional network looks at each image and outputs two things: a pseudo-measurement z and a covariance R for that measurement. Both feed a standard Kalman update. The whole graph trains end to end on the state error.
The data flow: image (H, W, 3) → CNN → z (d,) and R (d, d) → Kalman update. On a sharp frame the network gives a small R. On a smoky frame it gives a large R, K falls toward zero, and the filter coasts on its prediction. The network says "I am not sure" in the one language the filter reads: a variance. An R that changes with the input is called heteroscedastic.
Drag the image from sharp to smoke. The network's read (orange) gets worse. Compare a learned R with a fixed one and watch where the blue belief lands.
Illustrative toy: the network's error spread grows from 0.5 m (sharp) to 4 m (full smoke). Its learned R is that spread squared, as a well-trained network would report.
How does a network learn to report an honest R? Train it on the negative log-likelihood (NLL) of the truth under its own bell curve. Call the network's read z, its reported variance R, and the truth x.
NLL equals one half the log of two pi R, plus z minus x squared, over two R.
Charge the network for its error, divided by the doubt R it claimed. Also charge it for the doubt itself. The two charges balance where R equals the average squared error: an honest R.
With made-up numbers: on smoky frames the squared error averages 9 m². Claim R = 1: 0.92 + 4.50 = 5.42. Claim R = 100: 3.22 + 0.05 = 3.27. Claim R = 9: 2.02 + 0.50 = 2.52, the lowest. Training pushes R to 9.
pythonclass LearnedObs(nn.Module): # image (B, 3, H, W) -> z (B, 1), log R (B, 1) def __init__(self): super().__init__() self.cnn = nn.Sequential(nn.Conv2d(3, 16, 3), nn.ReLU(), nn.AdaptiveAvgPool2d(1), nn.Flatten()) self.head_z, self.head_logR = nn.Linear(16, 1), nn.Linear(16, 1) def forward(self, img): f = self.cnn(img) return self.head_z(f), self.head_logR(f) z, log_R = obs_net(frame) # a new R for every frame K = P_hat / (P_hat + log_R.exp()) # small on a bad frame: the filter ignores it mu = mu_hat + K * (z - mu_hat)
Failure. Symptom: one bad frame yanks the whole track. Measure: plot the reported R next to the actual error per frame; R stays flat while the error spikes. Fix: report R per frame, trained on the NLL or end to end through the filter.
Differentiable particle filters (Jonschkowski, Rastogi and Brock, 2018) apply the same idea to the particle filter. They learn the motion model and a measurement model that scores each particle, and train them through the filter's own steps.
Chapter 4
Keep the predict and update, and let a small recurrent network choose K
A gust shoves the drone 10 m sideways. The motion model never predicted gusts. The filter has a small Q, so it reads the big innovation as sensor noise and barely moves. Raise Q and the filter catches gusts, but then it chases noise in calm air. One fixed Q cannot serve both.
The gain formula of Chapter 1 is optimal only when the model and the noise statistics are right. KalmanNet (Revach and others, 2022) keeps the filter's flow. It replaces the gain computation with a small recurrent network (a GRU), so it needs no Q and no R. The update keeps its shape:
x-t equals x-hat-t plus K-t times y-t.
Predict x-hat-t with the physics. Measure the surprise y-t. Ask the network for a gain K-t from what it has seen lately. Move the prediction by K-t times the surprise.
With made-up numbers: a filter with Q = 0.1 and R = 1 settles at a fixed gain of 0.27. After a 10 m jump it still misses by 10 × 0.735 = 2.1 m five steps later. A gain of 0.9 on the jump step cuts the miss to 1 m at once.
The paper feeds the GRU differences it can compute: the change in measurement, the innovation, and the last two state updates. It trains end to end on the state's squared error with BPTT. With the true linear model it reaches the same error as the Kalman filter, the best possible. With a wrong model it beats filters that use the wrong model.
The dashed line jumps where the model expects none. Teal is the fixed gain; purple adapts. The lower strip shows each gain. Drag the jump size.
Illustrative toy, sensor noise 1 m. The purple gain is a hand-written rule that stands in for a trained GRU. It raises K when the innovation is far outside its usual size, and returns to 0.27 when calm.
pythonclass GainNet(nn.Module): # a sketch of the KalmanNet idea, 1 state, 1 measurement def __init__(self): super().__init__() self.gru, self.toK = nn.GRUCell(2, 32), nn.Linear(32, 1) def step(self, x, dx_last, h, z, f, hobs): x_hat = f(x) # known physics y = z - hobs(x_hat) # innovation h = self.gru(torch.cat([y, dx_last], -1), h) K = self.toK(h) # learned gain: no Q, no R, no inverse x_new = x_hat + K * y # the same update shape return x_new, x_new - x_hat, h
Failure. Symptom: the learned gain reacts to a single outlier as if it were a jump. Measure: count gain spikes on frames where the truth did not move. Fix: train on data that has both outliers and jumps, so the network learns their different signatures.
Chapter 5
See attention as a weighted average of past measurements, and train it with a teacher
So far the code still had a predict step and an update step. Now drop both. Feed a transformer a sequence of noisy reads and train it to output the true state. Nobody writes a filter. The forward pass becomes one.
A filter maps the history of measurements to a belief about now. Attention maps a sequence to a weighted mix of its items. Call the past reads z1 to zt and the attention weights wi, which are positive and add to 1.
x-hat-t equals the sum over i of w-i times z-i.
Give each past read z-i a weight w-i. Trust recent and clean reads more. Multiply and add. The weighted average is the estimate x-hat-t.
With made-up numbers: reads 4.0, 5.2 and 4.6 m with weights 0.2, 0.3 and 0.5. x-hat = 0.8 + 1.56 + 2.3 = 4.66 m.
For a still target, a Kalman filter with a flat start gives the plain average of the reads, and its spread falls as 1/√n. A transformer trained on still targets learns equal weights and does the same. With noise of 2 m, 16 reads give a spread of 2/√16 = 0.5 m.
Orange dots are reads. Purple bars are the attention weights. The blue line and pink band are the estimate and its spread. Drag the context length, then make the target move.
Illustrative toy, noise 2 m. The weights stand in for what attention learns: equal for a still target, tilted toward recent reads for a moving one.
Is this exact? Goel and Bartlett (2023) built a causal transformer whose softmax attention is a Gaussian-kernel weighted average of the past. They proved it tracks the Kalman filter's output within a small error. So the classical filter can live inside the architecture.
How do you train such a model? A common recipe uses a teacher that sees privileged data, such as the true state in simulation. A student sees only the noisy reads and must match the teacher's output. To match it, the student must infer the hidden state from the history. That is filtering, learned.
Failure. Symptom: confident, smooth, wrong estimates in a new building. Measure: check the error on data unlike the training set. Fix: wrap the model in a check it cannot fool, the gate of Chapter 8.
Chapter 6
Let a network perceive and let geometry decide, joined by a confidence weight
Many modern SLAM and odometry systems split the work in two. A learned front-end turns pixels into measurements. A classical back-end turns measurements into poses and a map.
The motive is the blank wall. A hand-crafted front-end tracks corners and blobs. On a blank wall, glass or fog it finds none, and the back-end starves. A learned depth model gives a depth for every pixel, even on a wall with no texture. The stereo model FoundationStereo (Wen and others, 2025) is one example.
Each dot is one measurement the back-end can use; its brightness is its confidence. Drag the texture down and switch the front-end.
Illustrative toy. The 20-constraint minimum is a made-up stand-in for "enough to fix a pose". Learned depth on the blank wall gets a lower confidence in this toy.
The back-end does not hand those depths to another network. It solves a weighted least squares problem: find the pose and map that fit all measurements best, each weighted by its confidence. Call each measurement mi, its confidence ci (one over its variance), and the unknown x.
J of x equals the sum over i of c-i times m-i minus x, squared.
For a guess x, square each miss to measurement m-i and scale it by its confidence c-i. Add them up. Move x until the total J is smallest. For one unknown, that x is the confidence-weighted average of the measurements.
With made-up numbers: one depth read says 3.0 m with c = 4; another says 3.6 m with c = 0.25. Then x = (4 × 3.0 + 0.25 × 3.6) / 4.25 = 3.04 m. The confident read wins. This is the Kalman fusion of Chapter 1 again.
| Stage | Shape | Learned? |
|---|---|---|
| Stereo pair | 2 × (H, W, 3) | input |
| Depth model | depth (H, W) | yes, frozen: you inherit it |
| Unproject | points (H·W, 3) | no: camera geometry |
| Factor graph | poses + map | no: weighted least squares |
The seam is a feature. You can swap in a better depth model next year without touching the back-end. And the back-end checks consistency across frames, so it can catch a depth that every other frame disagrees with.
Failure. Symptom: one glossy floor bends the whole map. Measure: plot residuals per measurement; a few are huge. Fix: give low weight to low-confidence pixels, use a robust cost, or gate them (Chapter 8).
Chapter 7
Fly a loop through a smoke zone and switch the estimator live
A robot flies a loop in 2-D. Inside the shaded circle, its network reads get noisier, drop out, and sometimes lie with confidence. Pick a stack, then turn the world against it.
| Stack | What it does | Chapter |
|---|---|---|
| Fixed KF | One R tuned for clean air. Trusts every read. | 1 |
| Learned R | Takes the network's per-frame R, so it rides the model through noise. | 2, 3 |
| Hybrid + gate | Learned R plus a chi-square gate that drops reads that cannot be true. | 3, 8 |
| Window | Averages the last 8 reads. A stand-in for an implicit filter: no model, no variance. | 5 |
Dashed is the true path. Orange dots are reads; red rings are confident lies. The blue line is your stack, with its doubt ellipse. Push the sliders and switch stacks.
Illustrative toy: a 260-step loop, read noise 0.15 m outside the zone. Lies are the share of zone reads that miss by 1.6 to 3.2 m while claiming clean-air noise. Each bar is the error inside the zone, averaged over 20 seeded runs of this simulation.
Things to try. Set lies to 0, smoke high and dropout low, then flip between Fixed KF and Learned R. The fixed filter chases the noisy reads. Learned R swells its doubt and rides the motion model through. That is Chapter 3 in motion.
Now raise dropout. Every filter coasts on its prediction, and its ellipse grows. The window has no model to coast on, so it drifts toward old reads. Last, raise the lies and watch the red rings with the Hybrid stack. The gate drops them and the line stays on the path. Learned R alone accepts them, because the lie came with a small R.
In clean air all four bars are close. On easy data the architecture barely matters, which is why clean benchmarks mislead. The bars part in the smoke. No stack wins everywhere, but the hybrid degrades the most gracefully.
Chapter 8
Measure each surprise in standard deviations and drop the ones no honest sensor makes
A learned depth model sees a scene unlike its training data. It returns a smooth, confident, wrong answer with no error flag. The network cannot catch this itself. The filter can, because it has a prediction and knows how big a miss to expect.
Each read gives an innovation y: its miss from the prediction. The filter also knows the innovation covariance S: how big a miss to expect in each direction. Divide the miss by that spread to count it in standard deviations.
d squared equals y-transpose, times S-inverse, times y.
Take the miss y. When S is diagonal, square each part of y and divide it by the variance S gives that direction. Add the parts. If d squared is above a threshold, drop the read.
With made-up numbers: S = diag(0.04, 0.04) m². An honest read misses by y = (0.2, 0.1): d² = (0.04 + 0.01) / 0.04 = 1.25. A lie misses by (1.4, 0): d² = 1.96 / 0.04 = 49. With the threshold 5.99, keep the first and drop the second.
Where does 5.99 come from? For an honest 2-D read, d² follows a chi-square distribution with 2 degrees of freedom. Only 5% of honest reads land above 5.99. So the gate keeps 95% of the truth and drops anything far stranger.
Pink dots are honest reads; red dots are confident lies. The gate keeps everything left of the line. Drag the threshold and count the cost on each side.
Illustrative toy: 300 honest reads drawn from the 2-degree chi-square, and 30 lies that miss by 2 to 9 standard deviations. The expected share kept is 1 − e−g/2 for a 2-D gate.
| Read size | Gate at 95% | Gate at 99% |
|---|---|---|
| 1 number | 3.84 | 6.63 |
| 2 numbers | 5.99 | 9.21 |
| 3 numbers | 7.81 | 11.34 |
Failure. Symptom: after a big real jump, the gate drops every read and the track never returns. This is gate lockout. Measure: count rejections in a row. Fix: after a few in a row, inflate the filter's variance so the gate opens. The hero and showcase hybrids do this after 3.
The gate depends on an honest S. If the learned R is overconfident, S is too small and honest reads get dropped. Check calibration on held-out data first; Debugging and Consistency shows how.
Chapter 9
Choose a rung for your problem, and keep the core in one page of code
For any estimation problem, ask two questions. What can I write down? What must I learn? Write down the geometry, the dynamics, the shape of the update and the consistency check. Learn the rest: the noise, the perception, the gain. Then wrap the learned parts in a check that can catch them when they lie.
| Your situation | Reach for | Why |
|---|---|---|
| Good model, little data, need a guarantee | Kalman filter or EKF | Optimal when its assumptions hold; needs no training data. |
| Known structure, Q and R unknown | Differentiable filter | Learns a few numbers; keeps the variance. |
| Model mismatch, odd noise | KalmanNet | Learns the gain; keeps the predict step. |
| Raw images, no written sensor model | Learned observation model | The CNN gives z and a per-frame R. |
| Hard perception, need a consistent map | Learned front-end, classical back-end | Geometry weighs and gates the learner. |
| Huge data, can live without a guarantee | Transformer estimator | Learns priors no filter encodes; recalibrate and gate it. |
| Term | One line | Number on this page |
|---|---|---|
| Kalman gain K | P-hat / (P-hat + R): the trust slider. | 3 / 8 = 0.375 |
| d-L by d-R | How the loss moves with R; step against it. | +0.047, so lower R |
| NLL | Error over doubt, plus the price of doubt. | best at R = 9 when the error is 9 |
| Fixed-gain lag | A fixed K lets a jump decay slowly. | 2.1 m left after 5 steps |
| Averaging spread | n equal reads shrink doubt by √n. | 2 / √16 = 0.5 m |
| Weighted fusion | Confidence-weighted average of reads. | 3.04 m |
| Chi-square gate | Drop reads with d squared above it. | 5.99 for 2-D at 95% |
pythonimport numpy as np def hybrid_step(mu, P, u, Q, z, R_net, gate=3.84, misses=0): """One 1-D cycle: written-down predict, learned R, chi-square gate.""" mu_hat, P_hat = mu + u, P + Q # physics you can write down if z is None: # dropout: coast return mu_hat, P_hat, misses S = P_hat + R_net # R_net: the network's per-frame variance y = z - mu_hat # innovation if y * y / S > gate: # a lie no honest sensor tells misses += 1 if misses >= 3: P_hat *= 8; misses = 0 # avoid gate lockout return mu_hat, P_hat, misses K = P_hat / S # trust slider return mu_hat + K * y, (1 - K) * P_hat, 0 print(hybrid_step(0., 1., 3., 2., 5., 5.)) # (3.75, 1.875, 0): Chapter 1 by hand
Now press Present or Teach and climb the ladder from memory, from a learned R to the gate. Then go back to the drone and say why the hybrid survives the smoke.
The capstone of the VNAV series on Engineermaxxing. The methods follow the papers above. Every toy number on this page says illustrative, and a seeded script checked each worked number.