A lost robot sees only a door, a window or a wall, and its wheels slip 1 move in 5. The Bayes filter still finds it: in this run, 0.90 on the right cell by step 10.
Press Step and watch the purple bars close in on the pink robot. Then switch to Wheels only or Camera only and see each clue fail alone. Then we build, piece by piece, the belief, the predict step and the update step. Last comes the assumption that lets 20 numbers stand for the whole past.
You need Bayes' rule and the idea that probabilities add up to 1. We build the rest from zero.
Illustrative toy, one seeded run on a loop of 20 cells. Doors are at 2, 5, 7, 12, 15, 18; windows at 8, 11, 14, 16. Each step commands one cell right: the robot moves 1 cell with chance 0.8, else stays or moves 2. The camera names the landmark right 9 times in 10. Before step 10 in this run, the camera misreads 3 times and the wheels slip 4 times. Wheels alone stay at 0.05 in every cell; the camera alone never goes above 0.21.
Chapter 0
Send twenty robots the same commands and watch them end up in different cells
A robot drives along a hallway that loops back on itself. The hallway has 20 cells, numbered 0 to 19. The robot has no GPS and cannot see itself from above. Where is it?
It has two clues. Its wheels count how far it drove. A camera tells it whether it stands next to a door, a window or a plain wall. Neither clue is enough alone.
Wheels slip. Tell the robot to move one cell, and 8 times in 10 it does. 1 time in 10 it stays put, and 1 time in 10 it rolls two cells. The counter never notices, so every slip stays in the count.
Twenty robots (pink) start in cell 0. Each press tells all of them to move one cell right. The yellow line is where the wheel counter says they are. The warm bars are the exact chance of each cell.
Illustrative: twenty seeded robots with the slip above. We compute the bars exactly; we do not count them.
After 10 moves the counter says cell 10. The exact chance that a robot is there is 0.29. Of these twenty, 6 made it. The spread grows with every move: its standard deviation is 1.4 cells after 10 moves and 2 cells after 20.
The camera has the opposite problem. It does not drift, but the hallway repeats itself. Six cells have a door, so a "door" reading leaves six places. And the camera is wrong 1 time in 10.
The Bayes filter combines the two clues. It keeps a probability for every cell. When the robot moves, it shifts those probabilities and blurs them by the slip. When the camera reads, it multiplies each cell by how well the reading fits it.
Symptom: a robot that trusts its wheel count turns into the wrong door.
Measure: send the same command many times and record where the robot ends.
Fix: carry a probability for every place, and correct it with a sensor.
Chapter 1
Shape a belief by hand and see that its numbers always add up to 1
The robot cannot know its cell. It can hold a belief: one probability for each of the 20 cells. Each number says how likely the robot is to be in that cell. The numbers are never negative, and they add up to 1.
With no information, every cell gets the same number, 1/20 = 0.05. That flat belief is the honest start. A belief can also have one sharp peak, or two peaks when two places fit what the robot has seen.
Pick a preset, then tap any cell to pile more belief onto it. The bars always rescale so they add up to 1.
Illustrative. "Saw a door" is the belief after one door reading from a flat start; "Two places" is the hero's belief after step 3.
Now give the parts names. Number the time steps t = 1, 2, 3, and so on. Call the robot's true cell at step t xt. Call the camera reading at step t zt and the move command ut. Write z1:t for every reading so far, and u1:t for every command.
Bel of x-t equals P of x-t given z one to t and u one to t.
For each cell, ask: given every reading z and every command u so far, how likely is the robot to be here? Store the 20 answers. That array is bel.
Before any reading, bel is 0.05 in every cell. After one "door" reading, bel is 0.148 in each of the six door cells and 0.008 in each of the other 14. The six door cells hold 0.885 together.
One number for how spread a belief is helps later. Entropy, in bits, is about how many yes-or-no questions you still need to find the cell. A flat belief has 4.32 bits, because 2 to the power 4.32 is 20. A sure belief has 0 bits. After one door reading, 3.24 bits.
Symptom: beliefs that add up to 0.7, or to 1.4.
Measure: sum the array after every step.
Fix: divide by the sum. Chapter 4 shows where that divide comes from.
Chapter 2
Average over every cell the robot could have started from, and watch certainty spread out
The robot is sure it is in cell 5. It moves one cell right. Where is it now?
Most likely in cell 6. But it stayed in 5 with chance 0.1, and rolled to 7 with chance 0.1. The new belief is 0.1, 0.8 and 0.1 on cells 5, 6 and 7. One certainty became three possibilities.
Call the command u. Call the chance of landing in cell x′ after starting in cell x P(x′ | x, u). This table is the motion model. Call the belief after the move, before the camera reads, the predicted belief, bel, said "bel-bar".
Bel-bar of x-prime equals the sum over x of P of x-prime given x and u, times bel of x.
To fill cell x′, visit every start cell x. Multiply its belief bel(x) by the chance P(x′ | x, u) of going from x to x′. Add the products. The total is bel-bar(x′).
Start sure in cell 5. Cell 6 gets 0.8 × 1.0 = 0.8; cells 5 and 7 get 0.1 each. Move again. Cell 7 gets 0.1 × 0.1 + 0.8 × 0.8 + 0.1 × 0.1 = 0.66, from cells 5, 6 and 7. Cells 6 and 8 get 0.16; cells 5 and 9 get 0.01.
This sum is the law of total probability. You do not know where the robot started, so you average over every start, weighted by its belief. Books also call it the Chapman–Kolmogorov equation. Here the motion model is the same in every cell, so the sum slides one small pattern, 0.1, 0.8, 0.1, along the hallway. A sliding weighted sum is a convolution.
The belief starts sure in cell 5. Each press moves the robot one cell right and gives the warm predicted belief. Raise the slip and move again.
Exact arithmetic. Slip s splits evenly: stay with chance s/2, move 2 cells with chance s/2, move 1 cell with chance 1 − s.
Every move spreads the belief. From certainty, entropy rises to 0.92 bits after one move, 2.55 bits after 10 and 4.29 bits after 200, close to the flat 4.32. Wheels alone lose the robot.
Symptom: the total belief falls below 1 with every move.
Measure: sum the predicted belief after each move.
Fix: each row of the motion model must add up to 1, and belief must not fall off the ends of the map.
Chapter 3
Hold one camera reading against all 20 cells and give each a score
The camera says "door". What does that tell the robot?
It depends on the cell. At a door, the camera says "door" 9 times in 10. At a window or a plain wall, it says "door" 1 time in 20. These numbers come from testing the camera, not from the hallway.
Call the reading z: wall, door or window. Call the chance of reading z when the robot is truly in cell x P(z | x). This is the sensor model. Seen as a score for each cell, it is also called the likelihood of that cell.
P of z given x equals 0.9 if z matches the landmark at x, and 0.05 if it does not.
Look up the landmark at cell x on the map. If the reading z names it, score the cell 0.9. If not, score it 0.05. Do this for all 20 cells.
Reading "door". Cells 2, 5, 7, 12, 15 and 18 score 0.9; the other 14 score 0.05. A door cell fits the reading 0.9 / 0.05 = 18 times better. The 20 scores add up to 6 × 0.9 + 14 × 0.05 = 6.1, not 1.
Pick a reading. Each blue bar is how well that reading fits the cell. Lower the hit rate and watch the fit flatten.
Illustrative camera. At a hit rate of 1/3 every reading is a coin toss among three names, and the bars go flat.
| Robot is at | reads "wall" | reads "door" | reads "window" |
|---|---|---|---|
| a wall | 0.90 | 0.05 | 0.05 |
| a door | 0.05 | 0.90 | 0.05 |
| a window | 0.05 | 0.05 | 0.90 |
Each row adds up to 1: it is a distribution over readings. A column is not: it is one score per cell. Read down the "door" column and you get the blue bars.
Symptom: a filter that ignores the camera, or one that a single misread throws off for good.
Measure: park the robot at known cells and count how often the camera is wrong.
Fix: put the measured rates into P(z | x). Never use exactly 0 or 1: a score of 0 rules a cell out forever.
Chapter 4
Weigh each cell's predicted belief by its score, then rescale so the beliefs add up to 1
The robot holds a predicted belief. The camera reads "door". Bayes' rule for many hypotheses, from Bayes' Rule chapter 7, does the rest. Each cell is a hypothesis.
Call the belief after the reading bel(x). Call the number that makes the 20 new beliefs add up to 1 η, said "eta".
Bel of x equals eta times P of z given x times bel-bar of x. Eta is one over the sum over x of P of z given x times bel-bar of x.
For each cell, multiply the predicted belief bel-bar(x) by the score P(z | x). Add the 20 products: the total is P(z), the chance of this reading. Divide each product by it. Dividing by P(z) is multiplying by η.
A flat prediction, 0.05 per cell, and the reading "door". A door cell gives 0.05 × 0.9 = 0.045; any other cell 0.05 × 0.05 = 0.0025. P(z) = 6 × 0.045 + 14 × 0.0025 = 0.305. So a door cell ends at 0.045 / 0.305 = 0.148, and any other at 0.008.
Warm bars: the predicted belief. Press Update. Each bar multiplies by its blue score. That leaves faint purple products that no longer add up to 1. Then they rescale into the purple belief.
Exact arithmetic with the hallway's sensor model, hit rate 0.9.
Now the case where the wheels and the camera disagree. After the move from cell 5, the prediction is 0.1, 0.8 and 0.1 on cells 5, 6 and 7. The camera says "door". Cells 5 and 7 have doors, cell 6 is a wall. The products are 0.09, 0.04 and 0.09, with total 0.22. The new belief is 0.41, 0.18 and 0.41.
The camera pulled the robot out of the cell the wheels liked best and split it between two doors. Had it read "wall", cell 6 would jump to 0.986. The update never invents a cell: a cell the prediction gave 0 stays at 0, whatever the camera says.
Symptom: the belief values shrink toward 0 at every step, then turn into NaN.
Measure: print the sum of the products before the divide. Without the divide, 0.05 to the power 249 rounds to exactly 0 in a 64-bit float.
Fix: divide by the sum at every step, or keep log-probabilities.
Chapter 5
Run the two steps in a loop, on a door that a robot can push open
Put the two steps in a loop. A command arrives: predict. A reading arrives: update. The new belief is the only thing the filter carries into the next pass. That is the whole algorithm.
python def bayes_filter(bel, u, z, motion, sensor, states): """One pass: predict with command u, then update with reading z.""" bel_bar = {x2: sum(motion(x2, x, u) * bel[x] for x in states) for x2 in states} joint = {x: sensor(z, x) * bel_bar[x] for x in states} p_z = sum(joint.values()) # P(z), the evidence return {x: joint[x] / p_z for x in states}
The same loop works for any hidden state, not only a cell. Probabilistic Robotics by Thrun, Burgard and Fox, chapter 2, uses a door that is open or closed. Its sensor says "open" 6 times in 10 when the door is open, and 2 times in 10 when it is closed. The robot can push: a push opens a closed door 8 times in 10, and an open door stays open.
Choose what the robot does and what its sensor says, then press Step. Warm: the belief after the command. Purple: after the reading. Try the book's run: do nothing and sense open, then push and sense open.
The numbers of the door example in Probabilistic Robotics, chapter 2. The belief starts at 0.5 open.
Run the book's two steps by hand. Start at 0.5 open. Do nothing, then sense "open": 0.6 × 0.5 = 0.3 against 0.2 × 0.5 = 0.1, so 0.3 / 0.4 = 0.75 open. Now push. The predicted belief in "open" is 1 × 0.75 + 0.8 × 0.25 = 0.95. Sense "open" again: 0.6 × 0.95 = 0.57 against 0.2 × 0.05 = 0.01. The door is open with probability 0.57 / 0.58 = 0.983.
Here the command changes the state itself, and the predict step is the same sum as in the hallway with two cells instead of 20.
Symptom: a belief that jumps too far, or lags one step behind the robot.
Measure: log every pass. Each one must hold one predict and then one update, in that order.
Fix: one command and one reading per pass. If no reading came, skip the update, never the predict.
Chapter 6
Derive both steps from one assumption, then break it with a poster that looks like a window
The loop stores 20 numbers, yet the list of readings grows without end. Why are 20 numbers enough? Because of one assumption about the world.
The Markov assumption says the current state holds everything about the past that matters for the future. Call the cell at step t−1 xt−1, and every cell before step t x0:t−1. The assumption is two statements, one for each model.
P of x-t given all past cells, readings and commands equals P of x-t given x-t-minus-one and u-t. And P of z-t given all cells, past readings and commands equals P of z-t given x-t.
To predict the next cell x-t, the last cell x-t-minus-one and the command u-t are enough. To predict a reading z-t, the current cell x-t is enough. Older cells and older readings add nothing once you know the current cell.
The robot is in cell 11 and moves once: it lands in cell 12 with chance 0.8, whatever it saw at cell 3. In cell 12 it reads "door" with chance 0.9, whatever it read the step before.
With these two lines, both steps follow from rules you already have.
So the old belief is a sufficient statistic: once you have it, the old readings add nothing. Memory stays at 20 numbers forever.
The assumption fails when something outside the state shapes the readings. A poster at cell 9, a plain wall, looks like a window to the camera, every time. The robot parks there and reads again and again.
The robot (pink) stands at cell 9, in front of the poster. Each press is one more "window" reading. Compare a filter that treats each reading as new evidence with one whose map knows the poster.
Illustrative. Flat start, no moves, hit rate 0.9. The real camera reads "window" at the poster every time.
Suppose the filter treats each "window" as fresh evidence. After three readings it puts 0.9993 on the four real windows, and 0.00004 on cell 9, where the robot is. Now put the poster in the map, so the filter expects cell 9 to look like a window. Now cell 9 holds 0.20 after three readings, as one of five window-like cells. That is honest.
Symptom: the belief grows sure while the robot stands still.
Measure: compare how fast entropy falls with and without motion.
Fix: add the hidden cause to the state or the map, or count repeated readings from a still robot once.
Chapter 7
Turn every knob, give the filter a wrong model, and move the robot behind its back
Everything so far, in one hallway. You set how good the camera is and how much the wheels slip. You can give the filter a wrong motion model. You can also pick the robot up and put it down 10 cells away.
Top: the hallway, the pink robot and its blue reading. Middle: the belief, warm after each move and purple after each reading. Bottom: the belief on the robot's true cell over time, with a yellow line at 0.5. Press Play, then Kidnap.
Illustrative toy, seeded. The first run matches the hero's. Changing a knob restarts the run with the same random numbers.
Start with the defaults: a camera right 9 times in 10, and wheels that slip 1 move in 5. Over 400 seeded runs from random start cells, the filter averages 0.57 on the true cell after 10 steps. After 20 steps it averages 0.66. The table gives step 20 for other settings.
| Camera hit rate | slip 0 | slip 0.2 | slip 0.4 |
|---|---|---|---|
| 0.60 | 0.59 | 0.14 | 0.10 |
| 0.75 | 0.95 | 0.37 | 0.23 |
| 0.90 | 1.00 | 0.66 | 0.48 |
| 0.99 | 1.00 | 0.83 | 0.69 |
Each reading must bring in more than each move blurs out. With perfect wheels, even a 60% camera reaches 0.59 by step 20. With slip 0.2, the same camera stays at 0.14, far from sure.
Now break the model. Tell the filter the wheels never slip while they slip 1 move in 5. At step 20 its average belief on the true cell falls from 0.66 to 0.35. Each real slip puts the robot in a cell the prediction gave almost nothing.
Then kidnap the robot: move it 10 cells while the filter is sure of the old cell. The new cell starts near 0, so the camera must outvote a confident, wrong belief. Over 400 runs, the plain filter needs a median of 19 steps to put 0.5 back on the true cell. Mixing 2% of a flat belief into every update cuts that to 8. The price: the belief can never pass 0.981, and before the kidnap it averages 0.63 instead of 0.69. Probabilistic Robotics calls this the kidnapped robot problem.
Symptom: after a bump or a lift, the robot stays sure of a cell it has left.
Measure: track how well readings fit the predicted belief. A long run of readings with low P(z) means the belief is wrong.
Fix: keep a small floor of flat belief, or reset to flat when the fit stays low.
Chapter 8
Store the same belief as a grid, a Gaussian or a cloud of particles, and see which one keeps two peaks
Everything so far stores one number per cell. That is the histogram filter, or grid filter. It holds any shape of belief, two peaks included. Its cost is the number of cells, which grows fast with the world.
Call the floor's two lengths Lx and Ly, the cell size Δ, said "delta", and the width of a heading bin Δθ.
N-cells equals L-x over delta, times L-y over delta, times 360 degrees over delta-theta.
Divide each side of the floor, L-x and L-y, by the cell size delta. Divide the full turn by the heading bin delta-theta. Multiply the three counts.
With made-up numbers: a warehouse 200 m by 100 m, 5 cm cells, 1° headings. 4,000 × 2,000 × 360 = 2.88 billion cells. At 4 bytes each, one belief takes 11.5 GB. At 50 cm and 10°, 2.88 million cells and 11.5 MB.
The Kalman filter shrinks the belief to a Gaussian: a mean and a variance, or a covariance in more dimensions. If the motion and the sensor are linear with Gaussian noise, both steps stay Gaussian and the filter is exact. Predict adds the motion noise to the variance. Update averages prediction and reading by their precisions, as in Bayes Estimation chapter 6.
The particle filter stores a few hundred samples, each one a guess of the state. Predict moves each sample with a random slip. Update weights each sample by its likelihood. Resampling copies the heavy samples and drops the light ones.
This is the hero's belief after step 3: two peaks, at cells 9 and 17. The pink mark is the robot. Pick a way to store it. For particles, change how many.
Illustrative. The Gaussian treats the hallway as a straight line and matches the grid's mean and spread. We draw the particles from the grid belief with a fixed seed.
A Gaussian with the grid's mean and spread centres on cell 12.1, with a standard deviation of 4.7 cells. Its peak sits where the grid says 0.002, and it gives the true cell 9 only 0.07 instead of 0.42. Fifty particles keep both peaks: 23 near cell 9 and 23 near cell 17.
| Filter | Stores | Exact when | Cost grows with |
|---|---|---|---|
| Histogram (grid) | one number per cell | the world is cut into cells | cells, which multiply with every dimension |
| Kalman | a mean and a covariance | models linear, noise Gaussian | the state's size, up to its cube for dense matrices |
| EKF, UKF | a mean and a covariance | only for linear models; good when bends are gentle | about the same as Kalman |
| Particle | weighted samples | in the limit of infinite samples | the number of samples |
The forward algorithm of a hidden Markov model is this same filter, on a discrete state with no commands.
Symptom: a Kalman filter that settles between two doors, in a cell the readings rule out.
Measure: run a grid filter on the same data and compare the shapes.
Fix: use a grid or particles while the belief has several peaks, and a Gaussian once it has one.
Chapter 9
Keep the failure table, the numbers and the code in one place
A Bayes filter keeps a belief: a probability for every state. A command shifts and blurs it, by averaging over every state the robot could have come from. A reading sharpens it, by multiplying each state by its likelihood and dividing by the total. Under the Markov assumption, that belief is all the memory the filter needs. Choose how to store it by the shape it takes: a grid for anything small, a Gaussian for one peak, particles for many.
| Failure | Symptom | Check that names it |
|---|---|---|
| Trusting the wheels alone | the count drifts from the truth | repeat a command, record where it ends |
| Leaky motion model | belief sums below 1 after a move | each row of P(x′ | x, u) sums to 1 |
| Likelihood read as a belief | "window" taken as "cell 11" | P(z | x) scores cells; it does not sum to 1 |
| Missing normaliser | values shrink to 0, then NaN | divide by P(z) every step |
| A score of exactly 0 | a cell dies and never returns | no 0 or 1 in the sensor model |
| Steps out of order | the belief lags the robot | one predict, then one update, per pass |
| Markov broken | sure while standing still | is a hidden cause shaping repeated readings? |
| Overconfident motion model | belief collapses after every slip | model slip against measured slip |
| Kidnapped robot | sure of a cell it has left | a long run of low P(z) |
| One Gaussian for two peaks | estimate between two doors | compare with a grid on the same data |
python import numpy as np N = 20 LANDMARK = np.zeros(N, int) # 0 wall, 1 door, 2 window LANDMARK[[2, 5, 7, 12, 15, 18]] = 1 LANDMARK[[8, 11, 14, 16]] = 2 def predict(bel, slip=0.2): """Move one cell right on the loop: stay, one or two cells.""" return slip / 2 * bel + (1 - slip) * np.roll(bel, 1) + slip / 2 * np.roll(bel, 2) def update(bel_bar, z, hit=0.9): """Weigh each cell by P(z | x), then divide by P(z).""" like = np.where(LANDMARK == z, hit, (1 - hit) / 2) joint = like * bel_bar return joint / joint.sum(), joint.sum() bel = np.full(N, 1 / N) bel, p_z = update(bel, 1) # read "door" print(round(p_z, 3), bel[2].round(3), bel[0].round(3)) # 0.305 0.148 0.008 spike = np.zeros(N); spike[5] = 1 pred = predict(spike) print(pred[4:9]) # [0. 0.1 0.8 0.1 0. ] post, _ = update(pred, 1) print(post[4:9].round(3)) # [0. 0.409 0.182 0.409 0. ]
We ran every line above with numpy; the comments are its output.
| Number | Value | Where it comes from |
|---|---|---|
| Chance of the counted cell after 10 moves | 0.29 | exact sum of 10 moves, pattern 0.1, 0.8, 0.1 |
| Flat belief, its entropy | 0.05, 4.32 bits | 1/20; log base 2 of 20 |
| Two moves from certainty, middle cell | 0.66 | 0.01 + 0.64 + 0.01 |
| "Door" from flat: P(z), door cell | 0.305, 0.148 | 0.045 / 0.305 |
| Wheels say 6, camera says door | 0.41, 0.18, 0.41 | 0.09, 0.04, 0.09 over 0.22 |
| Door example, after the push | 0.983 | 0.57 / 0.58, Probabilistic Robotics ch. 2 |
| Poster, three readings, independent | 0.00004 | belief on the true cell 9 |
| Default filter at step 20 | 0.66 | mean of 400 seeded runs |
| Kidnap recovery, plain and 2% floor | 19, 8 steps | median of 400 seeded runs |
| Warehouse grid, 5 cm and 1° | 2.88 billion | 4,000 × 2,000 × 360 |
Where it sits. Each update is Bayes' rule over many hypotheses, and with one fixed state it is the recursive estimate of Bayes Estimation. Make every belief a Gaussian and you have the Kalman filter; use samples and you have the particle filter. Keep the whole trajectory instead of the last cell, and take logs. The most likely path becomes the least-squares problem of VNAV 9 and the factor graphs of VNAV 13.
Now teach it: press Present or Teach and explain why a move blurs the belief and a reading sharpens it. Then go back to the lost robot, press Step three times, and predict which two cells the purple bars will favour before you look.