Introduction to Intelligent Systems
Sensing, filtering, seeing, searching, deciding, estimating and learning, and checking that it really works
What makes a machine intelligent rather than merely automatic? Eight chapters build the answer from parts you can test: a loop that senses, thinks and acts; filters that tame noise; images treated as arrays; search that plans a route; decisions that weigh costs under uncertainty; filters that fuse sensors into one belief; a neuron that learns from data; and evaluation honest enough to trust. No magic, just mathematics you can check.
Compiled and written by the Tactiverge team with AI assistance, from Tactiverge School lessons that were themselves written with AI assistance.
1. Sense, think, act
A thermostat reacts; a robot vacuum decides. The difference is not cleverness for its own sake but a loop that senses the world, chooses an action from rules or models, acts, and then senses again because the world has changed. This chapter separates automatic from intelligent behaviour, turns sensor readings into decisions with complete rule tables, and shows why real machines run several loops at different rates, fast inside slow.
Figure 1.1. Loops inside loops (described in words)
A sense, think, act loop drawn as three boxes with an arrow back from Act to Sense. The outer loop runs at 50 Hz, a period of 20 ms. A motor loop inside it runs at 1000 Hz, every 1 ms, so it takes 20 inner steps for each outer decision.
Explanation
1.1 Automatic or intelligent?
A music box plays the same tune perfectly every time. A robot vacuum never cleans your room the same way twice. Which one is smarter?
Automatic machines repeat
A music box, a toaster with a timer, or a wind-up toy does the same steps in the same order, whatever is happening around it. That is automatic. It can be precise and useful, but if the world changes, it carries on regardless.
Intelligent machines respond
An intelligent machine senses something about the world, decides what to do using rules, and acts. A robot vacuum feels a bump and turns. A night light measures darkness and switches on. Change the world and its behaviour changes too.
Smart is a spectrum
Engineers rarely mean 'thinks like a person'. They mean 'does the right thing in more situations'. A light that turns on at 7 pm is automatic. One that turns on when it gets dark is a little intelligent. One that also learns when you usually come home is more intelligent still.
Common mix-ups
Intelligent machines think like people.
✓ In engineering, an intelligent machine senses, follows rules and acts sensibly in changing situations. It doesn't need feelings or understanding.A better sensor makes a machine smarter.
✓ Sensors only measure. The intelligence is in the rules that turn measurements into actions.
1.2 Sense, think, act
A robot vacuum bumps a chair leg, backs off and turns. In that half second it did three different jobs. What were they?
Sense
Measure something about the world: a distance, a temperature, a colour, whether a button is pressed. A machine can only react to what it can measure.
Think
Compare the measurement with what you want and choose an action. At this level the thinking is usually a rule: if the wall is closer than 20 cm, stop. Rules can be simple and still produce clever-looking behaviour.
Act
Change something in the world: spin a motor, open a valve, sound a buzzer, light an LED. The parts that do this are called actuators.
Then do it again
Acting changes the world, so the next measurement is different. The loop goes round and round, often hundreds of times a second. That repetition is what lets a robot notice surprises and correct itself.
Common mix-ups
A robot senses once, makes a plan and follows it.
✓ Reliable robots sense again and again while they act, so they can react to changes.Only motors count as actuators.
✓ Anything that changes the world on the machine's command counts: valves, heaters, lights, speakers.
1.3 From readings to decisions
A sorting machine sees thousands of parts an hour and never gets bored. How does it decide where each one goes?
Thresholds
A threshold is a line you draw across a sensor's range: above it means yes, below it means no. Is it red? Reading > 65. Is it dark? Light < 30. Too hot? Temperature > 24 °C. One number becomes one clear answer a controller can act on.
Rule tables
With several yes/no answers, list every combination in a rule table. Three sensors (red? large? metal?) give 2 × 2 × 2 = 8 rows. For each row you choose an action: which bin. Writing every row stops you forgetting a case, a common cause of machines doing something silly.
Noise near the line
A reading close to the threshold can flip between yes and no just from noise. A thermostat might click on and off every few seconds. Fixes: average readings first, or use two thresholds: heater on below 19.5 °C, off above 20.5 °C. The gap between them is called hysteresis, and it stops the flicker.
Common mix-ups
Once you pick a threshold, decisions are always right.
✓ Noise near the threshold can still cause wrong calls. Averaging and hysteresis reduce them.You only need rules for the common cases.
✓ Machines meet rare cases too. A complete rule table gives every case a planned action.
1.4 Fast loops inside slow ones
A balancing robot corrects its motors a thousand times a second but decides where to go only once a second. Why not do everything at 1 kHz?
Rates follow the physics
Each loop should run several times faster than the quantity it controls can change. Motor current changes in microseconds to milliseconds, so current loops run at 10–20 kHz. Wheel speed changes in milliseconds (1 kHz). A robot's position on a map changes over tenths of a second (10–100 Hz). Goals change over seconds (1 Hz or less).
Cascaded loops
Layers are usually cascaded: the planner sends a path, a position loop turns it into speed targets, and a speed loop turns those into motor commands. Each inner loop treats its setpoint as constant between outer updates, which only works if the inner loop is much faster.
The cost of running fast
Running everything at the highest rate wastes processor time and energy, and heavy jobs such as vision may simply not finish in 1 ms. Splitting rates lets each job get the time it needs, often on different processors: a microcontroller for fast loops, a larger computer for perception and planning.
Common mix-ups
Faster is always better, so run every loop as fast as possible.
✓ Each loop needs a rate matched to its dynamics. Over-fast loops waste computing; heavy jobs may not even finish in time.The update rate is a software detail you can choose later.
✓ Rates decide processors, buses and stability, so they belong on the block diagram from the start.
Examples to try
Worked solutions are in the interactive chapter online.
Automatic or intelligent?: example 1
Is a microwave that runs for exactly 2 minutes automatic or intelligent? What would make it intelligent?
Sense, think, act: example 1
Split a smart greenhouse fan into sense, think and act.
From readings to decisions: example 1
A plant-watering rule: water if soil moisture < 30%. Readings over a minute: 31, 29, 32, 28, 30%. What goes wrong, and how would you fix it?
Fast loops inside slow ones: example 1
A planner runs at 5 Hz and a position loop at 200 Hz. How many position updates per plan, and what is the position loop's period?
Interactive figures, in words
Figure 1.2 from “Sense, think, act”
This robot's 'think' step is one rule. Slide the sensor reading towards the wall and watch the decision change. Each time you move the slider, you are doing one more turn of the loop.
The rule tester can be replaced by this description: the rule is 'IF distance < 20 cm THEN stop ELSE drive forward'. At 35 cm the condition is false so the robot drives; at 15 cm it is true so it stops; at exactly 20 cm, 20 < 20 is false, so it still drives.
Laboratory (online)
These run in a browser on the full site. Simulations are simplified educational models.
- Simulation OS: Greenhouse through a cold night (Simulation OS experiment)
Run the greenhouse heater with a simple threshold rule, then add hysteresis, and count how often the heater switches in each case.
Open online - Nexus: Intelligent greenhouse (Nexus project)
Wire a sensor, a rule and an actuator into a loop and describe what the system senses, decides and does.
Open online
Practice questions
Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.
1. Which of these machines is intelligent rather than just automatic?
- A clock that chimes every hour
- A garden sprinkler that runs from 6:00 to 6:20 every morning
- A sprinkler that waters only when a soil sensor reads dry
- A conveyor belt that always runs at the same speed
Check it in “Automatic or intelligent?”
2. Put these lights in order from least to most intelligent: (A) on at 7 pm daily, (B) on when it gets dark, (C) on when it's dark AND someone is in the room.
- A, B, C
- C, B, A
- B, A, C
Check it in “Automatic or intelligent?”
3. Why must the sense–think–act loop keep repeating?
- To use up the battery evenly
- Because acting changes the world, so there is always something new to measure
- Because sensors only work once
Check it in “Sense, think, act”
4. A robot runs its sense–think–act loop 50 times every second. How many times does it run the loop in 3 seconds?
Answer:
Check it in “Sense, think, act”
5. A machine uses four yes/no sensors. How many rows does a complete rule table need?
Answer:
Check it in “From readings to decisions”
6. A heater keeps clicking on and off every few seconds when the room is near 20 °C. Which fix works best?
- Use two thresholds: on below 19.5 °C, off above 20.5 °C
- Move the thermometer next to the heater
- Make the heater more powerful
Check it in “From readings to decisions”
7. Which job should run at the highest rate?
- Choosing the next delivery shelf
- Recognising objects in camera images
- Controlling motor current
Check it in “Fast loops inside slow ones”
8. Why must an inner speed loop be much faster than the position loop around it?
- So the position loop can treat the speed as following its command almost instantly
- Because speed is more important than position
- It doesn't matter which is faster
Check it in “Fast loops inside slow ones”
Engineering applications
Robot vacuums
A robot vacuum's fast loop keeps its wheels at the commanded speed, a middle loop avoids bumps and cliffs, and a slow loop plans which room to clean next. Each loop trusts the one inside it.
Smart irrigation
A watering controller with a soil sensor, a rain forecast and a rule table is a small intelligent system: it senses, weighs evidence and decides, rather than running on a fixed timer.
Summary
- Automatic machines follow a fixed sequence; intelligent ones choose actions from what they sense.
- The sense–think–act loop must repeat because acting changes the world.
- A rule table with every input combination written out leaves no case undecided; hysteresis stops chattering.
- Fast inner loops handle physics; slower outer loops handle plans, and each must be several times faster than the one around it.
Glossary
- Sense–think–act loop
- Most robots run a repeating cycle: read sensors, decide what to do, command actuators, then repeat, usually at a fixed rate.
- Closed-loop (feedback) control
- Closed-loop control measures the output, compares it with the target and adjusts the command to shrink the difference, over and over.
- On–off control with hysteresis
- On–off control switches the actuator fully on or off; hysteresis uses two thresholds, one to switch on and a different one to switch off, so the output does not chatter around a single value.
- Open-loop control
- Open-loop control sends commands without measuring the result: 'run the motor at 60 % for 2 seconds' and hope it went far enough.
Project: Specify a small intelligent machine
Choose a household machine you would like to make smarter. List its sensors, write a complete rule table for its main decision, and draw its loops with their rates. Explain which behaviour makes it intelligent rather than automatic.
Deliverables
- A sensor and actuator list
- A complete rule table
- A loop diagram with rates and periods
References
- Stuart Russell and Peter Norvig (2020). Artificial Intelligence: A Modern Approach, 4th edition. Pearson.
2. Noise and filtering
Every sensor reading is the truth plus noise, and an intelligent system that believes every reading will twitch at shadows. This chapter describes signals by amplitude, frequency and signal-to-noise ratio, then smooths them with three filters: the moving average, the exponential filter with one number of memory, and the median filter that ignores spikes. Each buys smoothness with delay, and the chapter shows how to choose the trade.
Figure 2.1. Smoothing costs delay (described in words)
Unit-step responses of two filters over 10 samples. A 5-sample moving average climbs in equal steps and reaches 1 after 5 samples. An exponential filter with α = 0.2 rises quickly then slowly: 0.672 after 5 samples and 0.893 after 10, never quite reaching 1.
Explanation
2.1 Signals: amplitude, frequency, period and SNR
A heartbeat, a wobbling arm and a humming motor all draw wiggly lines. Which three numbers describe each wiggle?
The sine wave
x(t) = A·sin(2πft + φ). Amplitude A is the swing from the middle to a peak (peak-to-peak is 2A). Frequency f is cycles per second, in hertz (Hz). Period T = 1/f is the time for one cycle. Phase φ shifts the wave in time. Most real signals are sums of sine waves at different frequencies.
Frequency tells you the source
A motor at 3000 rpm turns 50 times a second, so it shakes its mount at 50 Hz and its multiples. A walking robot's body bobs at its step rate. Knowing the frequency of the signal you want, and of the noise you don't, is the starting point for choosing a sample rate and a filter.
Signal-to-noise ratio
SNR compares the size of the signal with the size of the noise. Using RMS values (a sine's RMS is A/√2): SNR = RMS signal ÷ RMS noise, often quoted in decibels as 20·log₁₀(that ratio). 20 dB means the signal is 10× the noise; 0 dB means they are equal, and the signal is hard to see in a single look.
Common mix-ups
Amplitude is the distance from the lowest point to the highest.
✓ That is peak-to-peak, which is twice the amplitude.A signal with lower SNR is a weaker signal.
✓ SNR is a ratio: a strong signal with even stronger noise has low SNR.
2.2 The moving average and the noise–lag trade-off
Average the last 20 readings and the jitter melts away. So why does the robot now brake late?
How it works
A moving average of window k outputs the mean of the most recent k readings: yₙ = (xₙ + xₙ₋₁ + … + xₙ₋ₖ₊₁) ÷ k. Each new reading pushes the oldest out. It is cheap: keep a running sum, add the new value, subtract the one leaving.
Noise falls like √k
If the noise in each reading is independent with standard deviation σ, averaging k of them leaves about σ/√k. A window of 4 halves the noise; 16 quarters it. Noise that is not independent (a slow drift, a vibration at a steady frequency) is reduced less, or not at all.
Lag grows like k
The output describes the average of the last k samples, centred about (k − 1)/2 samples in the past. After a sudden change it takes k samples to catch up fully. At 100 samples a second, a 21-sample window responds about 0.1 s late, which at 2 m/s is 20 cm.
Common mix-ups
A bigger window is always better because it is smoother.
✓ Every extra sample of smoothing is extra delay; the right window depends on how fast the signal really changes.A moving average removes all noise eventually.
✓ It reduces independent noise by √k and leaves slow drifts and bias untouched.
2.3 The exponential filter: one number of memory
A filter that remembers just one number can still 'remember' every reading it has ever seen. How?
One line of code
y = y + alpha * (x - y). The output moves a fraction α of the way towards each new reading. α = 1 copies the input (no filtering); α near 0 barely moves (heavy smoothing). Only one number, y, is stored.
Fading memory
Unrolled, the EMA is a weighted average of all past readings, with weights shrinking by a factor (1 − α) per step. Recent readings matter most; old ones fade but never quite disappear. That gives a smooth response with a quick initial reaction to a change.
Choosing α
Smaller α: less noise, more lag. A rough match to a k-sample moving average is α ≈ 2/(k + 1). If readings arrive every Δt seconds, the filter's time constant is about Δt/α; changes much faster than that are smoothed away.
Start-up and units
Initialise y with the first reading, not zero, or the output will spend many steps climbing from nothing. If the sample rate changes, α must change too to keep the same time constant.
Derivation: Unrolling the exponential filter
Start from yₙ = yₙ₋₁ + α(xₙ − yₙ₋₁) = αxₙ + (1 − α)yₙ₋₁.
Substitute the same rule for yₙ₋₁: yₙ = αxₙ + (1 − α)[αxₙ₋₁ + (1 − α)yₙ₋₂].
Keep going: yₙ = αxₙ + α(1 − α)xₙ₋₁ + α(1 − α)²xₙ₋₂ + α(1 − α)³xₙ₋₃ + …
Each older reading's weight is (1 − α) times the next newer one's: a geometric sequence. The weights add to α × 1/(1 − (1 − α)) = 1, so the output is a true weighted average.
Old readings never quite vanish, but they fade: after m steps a reading's weight has shrunk by (1 − α)ᵐ. With α = 0.2, after 10 steps it is 0.8¹⁰ ≈ 0.11 of its starting weight.
For a unit step the output after m samples is 1 − (1 − α)ᵐ. It reaches 90% when (1 − α)ᵐ = 0.1, so m = ln(0.1)/ln(1 − α): about 10.3 samples for α = 0.2.
For independent noise σ, the output's noise is σ·√(α/(2 − α)). α = 0.2 gives about 0.33σ, similar to a 9-sample moving average (σ/3). The two are roughly matched when k ≈ 2/α − 1.
Common mix-ups
An EMA forgets readings older than some window.
✓ Every past reading keeps a (shrinking) weight; there is no hard edge.α is a fixed property of the filter regardless of sample rate.
✓ The same α at a faster sample rate gives a shorter time constant; adjust α when you change the rate.
2.4 Spikes, median filters and filtering inside a controller
One glitch reading of 85 °C in a greenhouse at 18 °C. An average says 24 °C. What does the plant actually feel?
The median ignores outliers
A median filter outputs the middle value of the last k readings. A spike shorter than half the window lands at one end of the sorted list and is ignored, while real steps still pass through (after a delay of about half the window). Averages, by contrast, spread a spike's error over the whole window.
Filters live inside loops
In a feedback loop the controller acts on the filtered reading. Lag in the filter means the controller sees the world late: it keeps heating after the target is reached and overshoots. A filter that looks perfect on a recorded log can make a live loop oscillate.
Smoothing versus hysteresis
An on/off thermostat near its setpoint chatters as noise crosses the threshold back and forth. Heavy smoothing reduces chatter but adds lag. Hysteresis (switch on below one temperature, off above a higher one) stops chatter without lag, because noise smaller than the gap cannot cross both thresholds.
Common mix-ups
Every filter is a kind of average.
✓ The median is not an average; it is a ranking, which is why it can ignore outliers that averages can't.If a filter makes the plot look nicer, the controller will work better.
✓ Inside a loop, lag can make control worse even when the trace looks smoother.
Examples to try
Worked solutions are in the interactive chapter online.
Signals: amplitude, frequency, period and SNR: example 1
x(t) = 0.3·sin(2π·25t) V with noise σ = 0.05 V. Find T, peak-to-peak and SNR in dB.
The moving average and the noise–lag trade-off: example 1
Readings: 12, 15, 11, 18, 14. Window k = 3. What is the latest output?
The exponential filter: one number of memory: example 1
α = 0.5, y starts at 10. Readings 20, 20, 20. Outputs?
Spikes, median filters and filtering inside a controller: example 1
A 3-sample median over readings 5, 5, 40, 6, 6. Outputs from the third reading onward?
Interactive figures, in words
Figure 2.2 from “Signals: amplitude, frequency, period and SNR”
With sampling off, change amplitude and frequency and watch the period marker. Set f = 4 Hz and count the cycles in one second. Then add noise: at what σ does the wave become hard to see with A = 1? Note the SNR at that point.
The signal scope draws A·sin(2πft) over one second. With A = 1 and f = 4 Hz there are four full cycles; the green markers show the amplitude and one 250 ms period. Adding noise σ makes the trace fuzzy; at σ = 0.7 the SNR is about 0 dB and the wave is hard to pick out by eye.
Figure 2.3 from “The moving average and the noise–lag trade-off”
Use the Step signal and hide the EMA and median. Try windows of 1, 5, 15 and 25. For each, write down the 'noise left' and the 'lag' from the readout. Plot the two numbers against each other in your notes: what shape does the trade-off make?
The filter tuner plots 120 noisy samples of a step from 0 to 1 at sample 40. A moving average with k = 1 follows the noise exactly; with k = 5 noise drops by about √5 and the step takes about 5 samples to rise; with k = 25 the line is very smooth but takes about 23 samples to reach 90% of the step.
Laboratory (online)
These run in a browser on the full site. Simulations are simplified educational models.
- Simulation OS: Repeated distance measurements (Simulation OS experiment)
Increase the sensor noise and find the moving-average length that keeps the error under 1 cm, then note the delay it adds.
Open online - BUILD: Smart greenhouse, level 3 (BUILD level)
Add a filter to the greenhouse's temperature reading and check that the heater still reacts in time to a cold draught.
Open online
Practice questions
Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.
1. A signal's RMS is 100 times its noise RMS. What is the SNR in decibels?
Answer: dB
Check it in “Signals: amplitude, frequency, period and SNR”
2. Two sensors give the same signal; sensor B's SNR is 6 dB higher. What does that mean?
- B's signal is 6 times bigger
- B's noise is about half of A's, relative to the signal
- B samples 6 times faster
Check it in “Signals: amplitude, frequency, period and SNR”
3. Raw noise is σ = 6 mm. Roughly what noise remains after a 9-sample moving average (independent noise)?
Answer: mm
Check it in “The moving average and the noise–lag trade-off”
4. An obstacle sensor must react within 0.05 s at 100 samples/s. Which window is the largest you could use?
- k = 5
- k = 11
- k = 21
Check it in “The moving average and the noise–lag trade-off”
5. With α = 0.25, what weight does the reading from 2 steps ago carry in the current output?
Answer:
Check it in “The exponential filter: one number of memory”
6. A temperature EMA starts with y = 0 °C, but the room is 21 °C. What happens?
- Nothing: the first reading fixes it
- The output climbs slowly from 0 and reports far too cold for a while
- The filter becomes unstable
Check it in “The exponential filter: one number of memory”
7. A 5-sample median filter faces a glitch that lasts 4 samples. What happens?
- It is removed completely
- It gets through, because it fills most of the window
- The filter crashes
Check it in “Spikes, median filters and filtering inside a controller”
8. Adding a heavy filter to a heater's temperature reading most likely causes…
- faster warm-up
- more overshoot, because the controller sees changes late
- lower energy use, always
Check it in “Spikes, median filters and filtering inside a controller”
Engineering applications
Obstacle sensors
An ultrasonic sensor occasionally reports a wild echo. A short median filter removes the spike without the delay a long average would add, so the robot still brakes in time.
Battery gauges
A phone's battery percentage is a heavily filtered estimate. Strong filtering hides the jumps caused by changing load, at the price of reacting slowly when the battery really drops.
Summary
- Signal-to-noise ratio compares signal and noise power; in decibels, 20·log10 of the RMS ratio.
- A k-sample moving average cuts random noise by about √k and delays the signal by about (k − 1)/2 samples.
- The exponential filter y ← y + α(x − y) needs one stored number; small α smooths more and lags more.
- Median filters reject short spikes that would drag an average; inside a control loop, every filter adds lag.
Glossary
- Low-pass filter (moving average and EMA)
- A low-pass filter lets slow changes through and attenuates fast ones. In firmware the simplest are the moving average and the exponential moving average.
- Frequency and period
- Frequency is how many cycles happen per second; the period is the time for one cycle. Each is the reciprocal of the other.
- Logarithms and decibels
- A logarithm answers 'what power gives this number?'. Decibels use logarithms to express ratios: 10 log10 for power ratios and 20 log10 for amplitude ratios.
- Standard deviation
- Standard deviation measures how spread out values are around their mean: the square root of the average squared distance from the mean.
Project: Choose a filter against a deadline
A robot must react to an obstacle within 0.1 s, and its sensor runs at 50 Hz with occasional spikes. Compare a moving average, an exponential filter and a median filter on simulated readings, and pick the one that meets the deadline with the least noise.
Deliverables
- Simulated readings with stated noise and spike rate
- Noise and delay for each filter
- The choice, with the deadline check
References
- Sebastian Thrun et al. (2005). Probabilistic Robotics. MIT Press.
3. Machine vision
A camera image is a grid of numbers, and every vision algorithm is arithmetic on that grid. This chapter builds a small vision pipeline from first principles: store and index pixels, threshold a picture into a mask, slide a kernel across the image to blur or sharpen, find edges with the Sobel operator, and group pixels into objects whose area and centre you can measure. Every step can be checked by hand on a 3 × 3 patch.
Figure 3.1. Sobel on one patch (described in words)
A 3 by 3 patch of pixels with values 20 and 100, brighter towards the lower right, beside the Sobel x and Sobel y kernels. Multiplying and summing gives Gx = 320 and Gy = 160, so the gradient magnitude is √(320² + 160²) ≈ 357.8: a strong edge.
Explanation
3.1 Images are arrays of numbers
To a robot, your face is a grid of about two million numbers. Which number is your nose?
A grid of samples
A camera sensor is an array of light-measuring cells. Each one integrates light during the exposure and is converted to a number: the image is sampled in space (pixels) and quantised in brightness (usually 8 bits, 0–255). A greyscale image is a 2D array img[row][col]; row 0 is at the top.
Colour is three arrays
A colour image stores three channels, red, green and blue, so each pixel is a triple like (230, 40, 35) for a red-ish part. Many cameras actually measure one colour per cell through a mosaic of filters and fill in the other two by interpolation.
Size and cost
Memory = width × height × channels × bytes per channel. Processing time grows the same way, so robots often shrink images (downsample), convert to greyscale, or process only a region of interest. Downsampling an image is sampling again, so fine stripes can alias into false patterns, called moiré.
Same lessons as sensors
Each pixel is a sensor reading with noise, bias (a dark offset), limited range (saturated white areas lose detail) and resolution. Everything from weeks 19–23 applies, now in two dimensions.
Common mix-ups
A camera records what the eye sees.
✓ It records numbers: sampled, quantised, noisy and clipped, through a lens and a colour filter. Vision algorithms see only those numbers.Coordinates in images work like maths graphs, with y going up.
✓ Image rows usually count down from the top; mixing the conventions flips results.
3.2 Thresholding: from picture to mask
Draw one line through the brightness scale and every pixel becomes 'object' or 'not object'. Where should the line go?
A threshold is a rule
mask[r][c] = 1 if img[r][c] ≥ T, else 0. The result is a binary mask: object pixels and background pixels. Everything later, from counting objects to measuring them, works on this mask, so mistakes here spread through the whole pipeline.
Let the histogram choose
A histogram of pixel values for a well-lit scene often has two humps: background and object. A good threshold sits in the valley between them. Automatic methods such as Otsu's choose T to make the two groups as internally similar as possible, which usually lands in that valley.
When one threshold fails
Noise makes the humps overlap, so some pixels are always misclassified. Uneven lighting shifts brightness across the image, so a threshold right on the left is wrong on the right. Fixes: control the lighting, smooth before thresholding, or use an adaptive threshold computed from each region's neighbourhood.
Common mix-ups
There is always a perfect threshold if you search hard enough.
✓ When the value ranges of object and background overlap, every threshold makes some mistakes; you can only choose which ones.Thresholds tuned on one image work everywhere.
✓ Lighting, camera settings and surfaces change; test thresholds on images you didn't tune on.
3.3 Kernels: the moving average goes 2D
Nine numbers in a 3×3 grid can blur a photo, sharpen it or find its edges. How can so few numbers do so much?
Slide, multiply, add
To filter an image, place the kernel over each pixel in turn, multiply each kernel weight by the pixel beneath it, add the nine products, and write the result into a new image at that position. Use a fresh output image: overwriting as you go corrupts the neighbours you still need.
Blur is averaging in 2D
The box blur averages each 3×3 neighbourhood, so independent pixel noise drops by about 3. Like the moving average, it costs sharpness: edges spread over several pixels. A Gaussian kernel weights the centre more than the corners, which blurs more gently for the same noise reduction.
Edges and ranges
At the border the kernel overhangs the image. Common fixes: repeat the nearest pixel (used in the diagram), mirror the image, or skip the border. Outputs can fall outside 0–255 (sharpening, edge kernels), so compute in a wider number type and clip or rescale only for display.
Derivation: Applying a kernel to one pixel
Take the 3×3 neighbourhood centred on the pixel, values p(i, j) for i, j ∈ {−1, 0, 1}.
Take the kernel weights k(i, j) in the same layout.
Output = Σᵢ Σⱼ k(i, j) · p(i, j): nine products, added. (Strict mathematical convolution flips the kernel first, using k(−i, −j); for symmetric kernels like the blur it makes no difference.)
Box blur: all k = 1/9, so the output is the mean of the nine pixels: a 2D moving average. Noise falls by about √9 = 3.
Example patch rows [10, 20, 30] [40, 50, 60] [70, 80, 90] with a box blur: sum = 450, output = 450 ÷ 9 = 50.
Sharpen [[0, −1, 0], [−1, 5, −1], [0, −1, 0]] = identity plus (centre − neighbours). On that patch: 5×50 − (20 + 40 + 60 + 80) = 250 − 200 = 50, unchanged on a smooth ramp; at an edge it exaggerates the difference.
Weights summing to 1 keep average brightness; weights summing to 0 (edge kernels) give 0 on flat regions.
Common mix-ups
Blurring removes noise without losing anything.
✓ It averages noise down and also smears real edges; it is the image version of the noise–lag trade-off.Kernel outputs always stay between 0 and 255.
✓ Kernels with negative weights or sums above 1 can go outside the range; keep the true values and clip only for display.
3.4 Edge detection with Sobel
Outlines are where brightness changes fastest. How do you measure 'change' in a grid of numbers?
Edges are gradients
Along a row, a sharp jump in brightness is a large difference between neighbouring pixels: a discrete derivative. Sobel x [[−1, 0, 1], [−2, 0, 2], [−1, 0, 1]] subtracts the left column from the right, giving extra weight to the middle row. Large positive or negative values mark vertical edges; Sobel y does the same for horizontal edges.
Strength and direction
Combine the two responses into the gradient magnitude √(Gx² + Gy²): how strong the edge is, whatever its direction. The angle atan2(Gy, Gx) gives the direction brightness increases. Threshold the magnitude to get an edge map.
Noise is the enemy
Differences amplify noise: two noisy neighbours differ even on a flat surface. Sobel's three-row design already averages a little; blurring first (often with a Gaussian) helps more. It is the image version of the warning that differentiating noisy data makes it noisier.
Common mix-ups
Edge detectors find objects.
✓ They find brightness changes: shadows, reflections and texture produce edges too. Deciding which edges belong to objects is a later step.A negative Sobel value means no edge.
✓ The sign gives the direction of the change; the size gives its strength.
3.5 Finding and measuring objects
A mask says which pixels are 'part'. But how many parts are there, and how big is each one?
Connected components
Scan the mask. When you meet an object pixel that has no label, give it a new label and flood outward: put it in a queue, and repeatedly take a pixel out and add its unlabelled object neighbours. When the queue empties, that whole blob is labelled. Continue the scan for the next blob.
Measuring blobs
For each blob: area is its pixel count; centroid is the mean row and mean column of its pixels; bounding box is the min and max row and column. With a known camera scale (mm per pixel) these become real sizes and positions a gripper can use.
Noise makes fake objects
Single noisy pixels above the threshold become tiny one-pixel 'objects', and a speck of shadow can split one object in two. Pipelines remove blobs below a minimum area, smooth or clean the mask first, and check counts against ground truth rather than trusting them.
Common mix-ups
Number of blobs = number of objects.
✓ Noise adds specks, touching objects merge, and shadows split objects. Counts must be checked against ground truth.The centroid is always inside the object.
✓ For a C or ring shape the centroid lies in the gap, which matters if a gripper aims for it.
Examples to try
Worked solutions are in the interactive chapter online.
Images are arrays of numbers: example 1
A greyscale camera is 1280 × 720 at 8 bits, 60 fps. What is the raw data rate?
Thresholding: from picture to mask: example 1
Background pixels range 30–90; object pixels range 150–220. Suggest T and justify.
Kernels: the moving average goes 2D: example 1
Apply Sobel x [[−1, 0, 1], [−2, 0, 2], [−1, 0, 1]] to the patch [10, 10, 80] [10, 10, 80] [10, 10, 80].
Edge detection with Sobel: example 1
At a pixel, Gx = 120 and Gy = −50. Find the edge strength.
Finding and measuring objects: example 1
A blob's pixels are at (row, col) (1,1), (1,2), (2,1), (2,2), (3,2). Area and centroid?
Interactive figures, in words
Figure 3.2 from “Images are arrays of numbers”
Choose the Bright square, then the Gradient. Click pixels to read their values: where is (row 1, column 1)? Which way do column numbers grow? Find the darkest and brightest pixel in the Noisy bar and explain why its 'flat' regions aren't flat.
The pixel diagram shows an 8 × 8 image as a grid of numbered squares. The Bright square image has value 200 in the central 4 × 4 block and 40 elsewhere; the Gradient rises by 30 per column from 20 to 230; the Noisy bar has a brighter band in columns 4 and 5 with random variation of up to ±45 and one bright speck.
Laboratory (online)
These run in a browser on the full site. Simulations are simplified educational models.
- Simulation OS: Sorting conveyor sensors (Simulation OS experiment)
Change the colour threshold and the belt speed, and record how many parts are sorted wrongly at each setting.
Open online - Code Lab (Studio)
Apply a box blur and a Sobel kernel to a small greyscale array by hand-written loops, and check one output pixel by hand.
Open online
Practice questions
Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.
1. How many bytes is a 320 × 240 RGB image at 8 bits per channel?
Answer: bytes
Check it in “Images are arrays of numbers”
2. A bright window shows as a block of pixels all exactly 255. What does that tell you?
- The window is exactly at brightness 255
- Those pixels are saturated: the true brightness is at least that high and detail is lost
- The camera is broken
Check it in “Images are arrays of numbers”
3. Parts on the left of a conveyor are lit twice as brightly as on the right. A single threshold…
- works fine if chosen carefully
- will tend to miss dark-side parts or over-detect bright-side background
- becomes more accurate
Check it in “Thresholding: from picture to mask”
4. A pixel histogram has humps centred at 50 and 180, with very few pixels between 100 and 130. Where should T go?
- At 50
- In the valley, around 115
- At 180
Check it in “Thresholding: from picture to mask”
5. A kernel's weights add up to 2. Applied to a flat grey region of 100, what does it output?
- 100
- 200
- 0
Check it in “Kernels: the moving average goes 2D”
6. Sobel y responds strongly but Sobel x is near zero. The edge is…
- vertical
- horizontal
- diagonal
Check it in “Edge detection with Sobel”
7. Edge detection on a noisy image finds edges everywhere. What should you try first?
- Lower the edge threshold
- Blur the image slightly before detecting edges
- Use a bigger image
Check it in “Edge detection with Sobel”
8. Two touching coins are counted as one object. Which statement is true?
- Switching to 4-connectivity always fixes it
- Labelling cannot separate objects that genuinely touch in the mask; you need another cue such as shape, size or edges
- Raise the minimum area
Check it in “Finding and measuring objects”
Engineering applications
Inspection lines
A factory camera thresholds each part against a backlight, counts the blobs and measures their area. A part whose area is outside tolerance is pushed off the belt.
Lane keeping
Driver-assistance cameras look for strong edges in the lower part of the image, where lane markings should be. Filtering noise before edge detection keeps shadows from looking like lines.
Summary
- A greyscale image is a 2D array; a colour image adds a third dimension for channels.
- Thresholding turns an image into a mask; uneven lighting breaks a single global threshold.
- Convolution slides a kernel over the image; weights summing to 1 preserve brightness.
- Sobel kernels estimate gradients; the magnitude √(Gx² + Gy²) marks edges, and blurring first suppresses noise.
Glossary
- Bits and bytes
- A bit is a single binary digit, 0 or 1. A byte is 8 bits. n bits can represent 2^n different values.
- ADC resolution
- An n-bit analogue-to-digital converter splits its reference voltage into 2^n steps; one step, the least significant bit, is the smallest change it can detect.
- Calibration
- Calibration compares an instrument's readings with known references and builds a correction, often an offset and a gain, so that future readings are accurate.
Project: Count and measure the parts
Create a small synthetic image of parts on a belt (a grid of numbers is enough). Threshold it, find connected objects, and report each one's area and centre. Then add noise and uneven lighting, and show what breaks and how you fixed it.
Deliverables
- The synthetic image and its threshold
- Object areas and centres before and after noise
- The fix and its evidence
References
- Richard Szeliski (2022). Computer Vision: Algorithms and Applications, 2nd edition. Springer.
4. Search and planning
Planning means looking ahead before acting. On a map divided into cells, a plan is a path, and search algorithms find it systematically. This chapter starts with planning a route by hand, uses a queue to make breadth-first search find the fewest moves, adds costs so Dijkstra's algorithm finds the cheapest path, and ends with problems such as visiting many places in the best order, where exact answers become impossibly slow and good heuristics take over.
Figure 4.1. Breadth-first search, cell by cell (described in words)
A 5 by 4 grid with walls. Breadth-first search from the top-left cell writes each free cell's distance in moves: 0, 1, 2, 3 along the top row, then around the walls, reaching the bottom-right goal in 7 moves. Wall cells hold no number.
Explanation
4.1 Planning a route before you move
Rover drivers on Earth plan a whole day of driving in one go, then hit send. How do they make sure it doesn't end in a crater?
A plan is a sequence
A route plan is a list of moves from start to goal that avoids every obstacle on the map. Writing it is like writing an algorithm, except the 'bugs' are walls and craters.
Comparing routes
Several routes may work. Engineers compare them: shorter (fewer moves, less energy), safer (further from hazards), or easier to check (passing landmarks the robot can see). The shortest route isn't always the best.
Plans need checkpoints
Real wheels slip and maps are imperfect, so a plan alone is open-loop. Robots add checkpoints: stop, measure where you really are, correct, continue. Planning ahead plus checking along the way combines the best of both.
Common mix-ups
A good plan doesn't need sensors.
✓ Plans are open-loop. Sensors and checkpoints catch slips and surprises.The shortest route is always best.
✓ Safety, energy and how easy it is to check position matter too.
4.2 Breadth-first search: a queue explores a map
Put a robot in a maze and flood it outwards one step at a time. Why does the first time the flood touches the goal give the shortest route?
The frontier is a queue
Start with the start cell in a queue. Repeatedly take the oldest cell, and add each unvisited free neighbour to the back. Because cells come out in the order they went in, every cell 1 move away is processed before any cell 2 moves away, and so on.
Visited set and came-from dict
Mark a cell visited when you add it to the queue, so it is never queued twice. Record came_from[neighbour] = current. When you reach the goal, follow came_from back to the start and reverse: that's the path.
Guarantees and limits
BFS always finds a path with the fewest moves if one exists, and reports failure after visiting every reachable cell if not. It ignores terrain cost: a short path through mud beats a long path on tarmac. Fixing that is Dijkstra's job in the term project.
Common mix-ups
BFS finds the cheapest route.
✓ It finds the route with the fewest moves. With terrain costs you need a cost-aware planner such as Dijkstra.Search algorithms 'see' the whole map at once.
✓ They only ever look at the neighbours of the cell they are expanding; the map knowledge comes from the order they expand cells.
4.3 Project: plan a path that counts the cost
BFS finds the fewest moves, straight through the mud. Your rover's battery would rather go round. How does the planner learn to care?
From queue to priority queue
BFS takes the oldest cell; Dijkstra takes the cheapest-so-far cell. Python's heapq keeps a list as a priority queue: heappush(pq, (cost, cell)) and heappop(pq) returns the smallest cost in O(log n). When a cell is popped, its cost is final.
Relax the neighbours
For each neighbour, the candidate cost is cost[cell] + step_cost(neighbour). If that beats the best known cost, record it, set came_from, and push it. Old, worse entries may stay in the heap; skip them when popped if the cell is already finished.
Project structure
grid.py (a GridMap class with neighbours and cost), planners.py (bfs and dijkstra as functions taking a map), experiment.py (timing and counting), test_planners.py (corridor, detour, unreachable goal, uniform-cost map where both agree). Each planner returns the path, its cost and the number of cells expanded.
Common mix-ups
Dijkstra is just a slower BFS.
✓ It solves a different problem: cheapest route under varying costs. On uniform costs it agrees with BFS.The fewest-moves path is the best path.
✓ Best depends on the cost you care about: energy, time, risk. Put that cost in the map.
4.4 When exact answers are out of reach
A delivery van must visit 20 shops. Trying every route would take a fast computer about two years. How do real route planners answer in a second?
Tractable means polynomial
A problem is usually called tractable if some algorithm solves it in O(n^k) time for a fixed k. Sorting, shortest paths (Dijkstra) and linear systems are tractable. Problems whose best known algorithms take 2ⁿ or n! time become impossible to solve exactly beyond a few dozen items, whatever the hardware.
P, NP and NP-hard, informally
P: problems solvable in polynomial time. NP: problems where a proposed answer can be checked in polynomial time (is this route shorter than 500 km? add up its legs). NP-hard: at least as hard as every NP problem; a fast algorithm for one would give fast algorithms for all. Nobody has proved P ≠ NP, but no one has found a polynomial algorithm for an NP-hard problem either, so engineers plan as if none exists.
Heuristics and approximations
A heuristic (nearest neighbour, greedy packing, simulated annealing) is fast but has no promise about quality. An approximation algorithm comes with a proof: for travelling-salesperson maps that obey the triangle inequality, Christofides' algorithm is never worse than 1.5× optimal. Either way, measure the gap on cases small enough to solve exactly, as the explorer does.
Common mix-ups
NP means 'not polynomial'.
✓ It means 'nondeterministic polynomial': solutions are checkable in polynomial time. P is inside NP.If a problem is NP-hard, engineers cannot solve it.
✓ They solve large instances well with heuristics, approximations and solvers, and small ones exactly.
Examples to try
Worked solutions are in the interactive chapter online.
Planning a route before you move: example 1
On the grid robot, compare route A (up 2, east 4, up 2) with route B (east 1 first). Which is valid?
Breadth-first search: a queue explores a map: example 1
BFS on a text map, returning the path as a list of cells.
Project: plan a path that counts the cost: example 1
Dijkstra on a cost grid (0 = wall), returning path, cost and cells expanded.
When exact answers are out of reach: example 1
How many distinct round trips through 12 cities, ignoring direction?
When exact answers are out of reach: example 2
A greedy route is 112 km and the exact best is 100 km. Report the heuristic's quality.
Interactive figures, in words
Figure 4.2 from “Planning a route before you move”
Plan the entire route to the flag before you press anything, writing it on paper. Then enter it and press Run all. Did it work first time? Find the shortest safe route you can.
The grid robot can be replaced by squared paper: draw a 6-by-6 grid with walls at (1, 1), (2, 1), (3, 1), (3, 3) and (2, 4), start at (0, 0) facing north and the flag at (4, 4). The shortest safe route goes up 2, east 4, up 2: Forward, Forward, Turn right, Forward ×4, Turn left, Forward, Forward.
Figure 4.3 from “Breadth-first search: a queue explores a map”
Keep Breadth-first search selected and step through the first 20 expansions. Notice the 'rings' of equal move count. Then wall off the goal completely and watch what BFS does. Finally, add walls to make the path as long as you can.
The planner shows a 7 × 10 grid with a start on the left and a goal on the right, a wall in column 5 rows 1 to 5, and a rough patch. BFS expands cells in rings of increasing move count and returns a fewest-moves path around the end of the wall. Walling off the goal makes BFS expand every reachable cell and report no path.
Figure 4.4 from “When exact answers are out of reach”
Start at 4 cities and add one at a time up to 9, watching 'tours tried'. On several random maps, compare the greedy nearest-neighbour route with the exact best. How far off is greedy at its worst?
The explorer draws 4 to 9 random cities with two routes: the exact best tour (found by trying all (n−1)!/2 tours) and the greedy nearest-neighbour tour. A table reports tours tried, both lengths and the percentage gap; at 20 cities brute force would need about 6×10¹⁶ tours.
Laboratory (online)
These run in a browser on the full site. Simulations are simplified educational models.
- Nexus: Autonomous rover (Nexus project)
Plan a rover route around obstacles and compare the number of moves with the shortest path found by breadth-first search.
Open online - Code Lab (Studio)
Implement breadth-first search on a small grid with a queue, then change one cell's cost and switch to Dijkstra's algorithm.
Open online
Practice questions
Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.
1. On an open grid with no walls, what's the fewest Forward moves to get from (0, 0) to (3, 5)?
Answer:
Check it in “Planning a route before you move”
2. Route A is 10 moves and passes right beside a crater. Route B is 12 moves and stays well clear. Which would a careful engineer pick?
- A, it's shorter
- B, it's safer
- Neither
Check it in “Planning a route before you move”
3. What would change if BFS used a stack (pop the newest cell) instead of a queue?
- Nothing
- It would become depth-first search: it still explores, but the first path found need not be the shortest
- It would find shorter paths
- It would crash
Check it in “Breadth-first search: a queue explores a map”
4. Why mark a cell visited when it is ADDED to the queue, rather than when it is taken out?
- It looks neater
- Otherwise the same cell can be queued many times by different neighbours, wasting time and memory
- Python requires it
- So the path is reversed
Check it in “Breadth-first search: a queue explores a map”
5. On a map where every free cell costs 1, how do BFS and Dijkstra compare?
- Dijkstra finds cheaper paths
- Both find paths with the same cost (fewest moves); BFS avoids the heap's log factor
- BFS finds cheaper paths
- Dijkstra fails on uniform costs
Check it in “Project: plan a path that counts the cost”
6. Why must Dijkstra's step costs be non-negative?
- heapq can't store negative numbers
- A finished cell's cost is assumed final; a negative step later could make a cheaper route to it
- Negative numbers are slower
- Python forbids them in tuples
Check it in “Project: plan a path that counts the cost”
7. How many distinct round trips (direction ignored) through 8 cities?
Answer:
Check it in “When exact answers are out of reach”
8. Your greedy scheduler beats random scheduling on every test. What should the report claim?
- It is optimal
- It is better than random on these tests; its gap to optimal is measured on small cases where the optimum can be computed
- NP-hard problems cannot be evaluated
- Nothing until P vs NP is solved
Check it in “When exact answers are out of reach”
Engineering applications
Warehouse robots
Warehouse robots plan on a grid of floor cells. Costs on busy aisles steer them onto quieter routes, so the cheapest path is often longer than the shortest one.
Delivery rounds
Ordering twenty delivery stops perfectly is out of reach, but a greedy route improved by swapping pairs of stops is usually within a few per cent of the best, which is what route planners use.
Summary
- A plan on a grid is a path; search explores possibilities in a systematic order.
- Breadth-first search uses a queue, so it reaches every cell first by a fewest-moves path.
- Dijkstra's algorithm uses a priority queue and finds cheapest paths when every step cost is non-negative.
- Some problems grow exponentially; heuristics give good answers fast but must be reported honestly as approximate.
Glossary
- Odometry
- Odometry estimates a robot's position and heading by adding up how far its wheels have turned since a known start.
- Differential drive
- A differential-drive robot has two independently driven wheels on one axle; it steers by turning them at different speeds.
- Coordinate frame
- A coordinate frame is an origin plus a set of axes used to describe positions and directions. Robots use several: world, base, each joint, sensors and the tool.
Project: Plan, then price, a route
Draw a 10 by 10 map with walls and a few expensive cells such as sand. Find the fewest-moves path with breadth-first search and the cheapest path with Dijkstra's algorithm. Report both paths, their lengths and costs, and when you would choose each.
Deliverables
- The map with costs
- Both paths with length and cost
- A one-paragraph comparison
References
- Edsger W. Dijkstra (1959). "A Note on Two Problems in Connexion with Graphs". Numerische Mathematik 1, 269–271.
- Peter E. Hart et al. (1968). "A Formal Basis for the Heuristic Determination of Minimum Cost Paths". IEEE Transactions on Systems Science and Cybernetics 4(2), 100–107.
- Stuart Russell and Peter Norvig (2020). Artificial Intelligence: A Modern Approach, 4th edition. Pearson.
5. Decisions under uncertainty
A detector that says 'fault' is sometimes wrong, and an intelligent system must act anyway. This chapter counts mistakes with a confusion matrix, turns counts into precision and recall, and moves the detection threshold to trade one kind of error for the other. Bayes' rule then updates beliefs from evidence while respecting base rates, and expected value turns beliefs and costs into a decision.
Figure 5.1. Counting a detector's mistakes (described in words)
A confusion matrix for 1000 parts, 50 of them faulty. The detector catches 45 faulty parts and misses 5; it wrongly flags 30 good parts and passes 920. Precision is 45 ÷ 75 = 0.6 and recall is 45 ÷ 50 = 0.9.
Explanation
5.1 Confusion matrices, precision and recall
A defect detector is '95% accurate'. It might still miss every faulty part. How?
Four outcomes
With 'faulty' as the positive class: TP faulty and flagged; FN faulty but passed (a miss); FP good but flagged (a false alarm); TN good and passed. The confusion matrix lays these out as a 2×2 table of counts, rows for the truth and columns for the decision.
Precision and recall
Precision = TP ÷ (TP + FP): when it says faulty, how often is it right? Low precision wastes good parts. Recall = TP ÷ (TP + FN): of the faulty parts, how many does it catch? Low recall lets faults through. Accuracy = (TP + TN) ÷ total, which is dominated by the common class.
The threshold trade-off
Lowering the threshold flags more parts: recall rises and precision usually falls. Raising it does the opposite. Where to set it is not a maths question but an engineering one: what does each kind of mistake cost? Next lessons put numbers on that.
Common mix-ups
High accuracy means a good detector.
✓ When positives are rare, a detector can be highly accurate and still miss most of them. Report precision and recall.There is one correct threshold.
✓ The best threshold depends on the costs of each mistake, which depend on the application.
5.2 Expected value: deciding when you can't be sure
A part is 15% likely to be faulty. Ship it, scrap it or check it again? There's a calculation for that.
Expected value
For an action with possible outcomes, expected cost = Σ (probability of outcome × cost of outcome). Shipping a part that is faulty with probability p: p × (return cost) + (1 − p) × 0. Compute it for every action and choose the smallest. It is the average cost per decision over many similar decisions.
Thresholds from costs
Ship beats scrap while p × C_miss < C_scrap, so the decision threshold is p* = C_scrap ÷ C_miss. With £20 and £200 that is 10%: scrap anything more than 10% likely to be faulty. This is how a probability from Bayes' rule becomes an action, and why the 'right' detector threshold depends on costs.
The value of a second look
Re-inspection costs something but removes uncertainty: expected cost = C_check + p × C_scrap (scrap only if it really is faulty). It wins in the middle range of p, where you are genuinely unsure, and loses when you're already nearly certain either way.
What averages hide
Expected value treats a 1% chance of a £10,000 disaster like a certain £100 loss. When outcomes include injury or irreversible harm, engineers add constraints (never ship above some risk, whatever the average) instead of just minimising expected cost.
Common mix-ups
If something is more likely good than bad, treat it as good.
✓ When the costs of mistakes are unequal, the best action can be the 'unlikely' one.Expected value predicts what will happen this time.
✓ It is a long-run average; any single decision can turn out better or worse.
5.3 Bayes' rule for sensor readings
The hazard detector beeps. It catches 90% of real hazards and false-alarms only 5% of the time. Is the rock really dangerous? Probably less likely than you think.
The rule
P(H | E) = P(E | H)·P(H) / P(E), with P(E) = Σ P(E | Hᵢ)P(Hᵢ) over all hypotheses. Prior P(H): belief before the reading. Likelihood P(E | H): how probable the reading is if H is true. Posterior P(H | E): belief after.
Base rates matter
A good sensor on a rare event still gives many false alarms. With a 1% prior, even a 99%-accurate detector with a 1% false-alarm rate gives a posterior of only 50%. Ignoring the prior is the base-rate fallacy.
Updating repeatedly
Today's posterior is tomorrow's prior. Two independent readings multiply their likelihoods. After two alarms from independent detectors in the example, P(hazard) rises from 0.67 to about 0.97. Independence is crucial: two looks by the same camera at the same shadow are not independent evidence.
Common mix-ups
P(E | H) and P(H | E) are the same thing.
✓ They can be wildly different: a 90% hit rate does not make 90% of alarms real.More readings always mean more certainty.
✓ Only if they are independent. Correlated readings repeat the same mistake.
5.4 Updating a belief on a grid
Instead of 'hazard or not', what if the unknown can be any number between 0 and 1? Split it into 21 slices and let the data reshape them.
The grid recipe
- Choose grid values p₁…p_m. 2. Assign prior weights π(pⱼ) summing to 1. 3. For the data, compute the likelihood L(pⱼ) = pⱼᵏ(1 − pⱼ)ⁿ⁻ᵏ. 4. Multiply: πⱼ·Lⱼ. 5. Normalise by the sum. That is the posterior: a full distribution over the unknown.
Summaries
The MAP (maximum a posteriori) is the highest bar. The posterior mean Σ pⱼ·postⱼ balances the bars. A credible probability such as P(p > 0.5 | data) is the sum of bars above 0.5: a direct answer to 'how sure are we the camera is better than a coin?'
Prior versus data
With a flat prior, the posterior is the normalised likelihood and its peak is the MLE k/n. Informative priors matter when data are scarce and fade as n grows. A grid is simple and exact for one or two parameters, but the number of cells explodes in high dimensions: that is why filters use Gaussians instead.
Common mix-ups
A Bayesian answer is just a single best number.
✓ It is a whole distribution; MAP, mean and credible probabilities are summaries chosen for the question.Priors make Bayesian results arbitrary.
✓ Priors matter with little data and fade with more. Stating them openly is more honest than hiding assumptions.
Examples to try
Worked solutions are in the interactive chapter online.
Confusion matrices, precision and recall: example 1
TP = 40, FP = 10, FN = 20, TN = 930. Find precision, recall and accuracy.
Expected value: deciding when you can't be sure: example 1
p = 30%, miss £200, scrap £20, re-inspect £8. Which action?
Bayes' rule for sensor readings: example 1
Prior 0.02, hit rate 0.95, false-alarm rate 0.02. Posterior after one alarm?
Updating a belief on a grid: example 1
Three hypotheses for p: 0.2, 0.5, 0.8, equal prior. One success observed. Posterior?
Interactive figures, in words
Figure 5.2 from “Confusion matrices, precision and recall”
On the tuning batch, slide the threshold from 0 to 100 and watch the four boxes. Find a threshold with recall at least 90%, then one with precision at least 90%. Can you get both at once? Write down the threshold you'd pick for a brake-part line and for a cheap plastic clip.
Sixty parts are drawn on a score strip: faulty parts as triangles that tend to score high, good parts as circles that tend to score low, with overlap in the middle. A threshold line splits them into flagged and passed. The table shows TP, FN, FP and TN; at a threshold of 50 on the tuning batch most faulty parts are flagged and a handful of good parts are wrongly flagged.
Figure 5.3 from “Expected value: deciding when you can't be sure”
With the default costs, sweep p from 0 to 100% and note where the best action changes. Read the break-even points from the chart and check them by hand. Now make re-inspection free, then expensive. When is checking again worth it?
The chart plots expected cost against the probability of a fault for three actions: shipping (a line rising from £0 to £200), scrapping (flat at £20) and re-inspecting (rising gently from £8 to £28). With the defaults, shipping is cheapest below about 4%, re-inspecting between about 4% and 60%, and scrapping above about 60%.
Figure 5.4 from “Updating a belief on a grid”
Pick 'Probably good'. Add one success and one failure: note the posterior mean. Now add 20 more in a 50:50 ratio. The prior's pull fades. Repeat with 'Probably poor' and check both posteriors converge.
The grid shows 21 bars for the posterior plus prior and likelihood lines. The readout lists the data as ticks and crosses and states MAP, posterior mean, P(p > 0.5) and k/n.
Laboratory (online)
These run in a browser on the full site. Simulations are simplified educational models.
- Simulation OS: Sorting conveyor sensors (Simulation OS experiment)
Raise and lower the detection threshold, fill in a confusion matrix at each setting and plot precision against recall.
Open online - BUILD: Sorting machine, level 5 (BUILD level)
Choose a threshold for the sorting machine by weighing the cost of a missed fault against the cost of scrapping a good part.
Open online
Practice questions
Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.
1. You lower the detection threshold. What usually happens?
- Recall rises, precision falls
- Precision rises, recall falls
- Both rise
Check it in “Confusion matrices, precision and recall”
2. For an airport bag scanner, which matters most?
- Precision
- Recall
- Accuracy
Check it in “Confusion matrices, precision and recall”
3. p = 20%, scrap cost £25, re-inspection £6 (assumed perfect; scrap only if faulty). What is the expected cost of re-inspecting, in pounds?
Answer: £
Check it in “Expected value: deciding when you can't be sure”
4. A robot's choice has a 0.1% chance of injuring someone. Why isn't expected cost alone the right tool?
- Because 0.1% is too small to matter
- Because some outcomes are unacceptable whatever the average, so they need hard limits
- Because expected value can't handle small probabilities
Check it in “Expected value: deciding when you can't be sure”
5. Prior P(H) = 0.2. P(E | H) = 0.8, P(E | not H) = 0.1. What is P(H | E)?
Answer:
Check it in “Bayes' rule for sensor readings”
6. A dust-storm alarm is 99% sensitive and has a 1% false-alarm rate, but storms occur on only 1% of sols. After an alarm, P(storm) is about…
- 99%
- 50%
- 1%
- 90%
Check it in “Bayes' rule for sensor readings”
7. With a flat prior, where is the posterior's peak?
- At the maximum-likelihood estimate
- At 0.5 always
- At the posterior mean
- Nowhere: a flat prior gives a flat posterior
Check it in “Updating a belief on a grid”
8. Why do robots rarely use plain grids to estimate 6-D pose (3 position + 3 orientation)?
- The number of cells grows exponentially with dimension
- Bayes' rule fails in 6-D
- Grids cannot represent uncertainty
- Priors cannot be defined in 6-D
Check it in “Updating a belief on a grid”
Engineering applications
Security scanners
Airport scanners are tuned for very high recall: missing a threat costs far more than a false alarm, so many harmless bags are searched by hand to make sure almost nothing dangerous passes.
Predictive maintenance
A vibration alarm for rare faults will mostly flag healthy machines unless its false-alarm rate is tiny. Bayes' rule with the true base rate tells maintenance teams how much to trust each alarm.
Summary
- A confusion matrix counts true and false positives and negatives; precision = TP/(TP + FP), recall = TP/(TP + FN).
- Lowering a threshold usually raises recall and lowers precision; the costs of each error decide the setting.
- Bayes' rule updates a prior with evidence; ignoring the base rate is the commonest mistake.
- Expected value weighs outcomes by probability and cost; some outcomes, like harm to people, are constraints, not costs.
Glossary
- Random and systematic error
- Random errors scatter readings unpredictably above and below the true value; systematic errors shift every reading the same way.
- Accuracy, precision and resolution
- Accuracy is how close a measurement is to the true value; precision is how close repeated measurements are to each other; resolution is the smallest change an instrument can show.
- Repeated trials
- Repeating a measurement or test several times shows how much results vary and lets you average out random error.
Project: Set the threshold, defend the choice
For a simulated detector with a known fault rate, tabulate the confusion matrix at five thresholds. Assign stated costs to each error, compute the expected cost of each threshold, and choose one. Say how the choice would change if faults became ten times rarer.
Deliverables
- Confusion matrices at each threshold
- Expected cost per threshold with stated costs
- The choice and the base-rate sensitivity
References
- Stuart Russell and Peter Norvig (2020). Artificial Intelligence: A Modern Approach, 4th edition. Pearson.
- Sebastian Thrun et al. (2005). Probabilistic Robotics. MIT Press.
6. State estimation and sensor fusion
No single sensor tells a robot where it is. Wheels drift, cameras drop frames, gyros wander. Fusion combines them so the estimate is better than any one. This chapter weights readings by their reliability, blends a fast drifting sensor with a slow absolute one in a complementary filter, and builds the Kalman filter's predict–update cycle, whose gain is exactly the weight that makes the combined variance smallest.
Figure 6.1. Two beliefs make a sharper one (described in words)
Two Gaussian beliefs about a position: 10 cm with σ = 1 cm and 11 cm with σ = 2 cm. Inverse-variance weights are 0.8 and 0.2, so the fused estimate is 10.2 cm with σ ≈ 0.894 cm, narrower than either sensor alone.
Explanation
6.1 Inverse-variance weighting
Two sensors measure the same distance. One is twice as precise. Should you trust it twice as much? Four times? All the way?
The recipe
x̂ = (z₁/σ₁² + z₂/σ₂²)/(1/σ₁² + 1/σ₂²) and σ_f = 1/√(1/σ₁² + 1/σ₂²). The fused value sits between the readings, closer to the more precise one; the fused σ is smaller than the smaller σ. Two equal sensors give σ/√2.
The fine print
It assumes both readings are unbiased, independent and have correctly known σ. A biased sensor drags the fused value with full confidence. Correlated errors (two cameras with the same calibration fault) give less improvement than the formula promises.
A consistency check
If the readings disagree by much more than √(σ₁² + σ₂²), something is wrong: a fault, a bias, a wrong σ. Real systems test the difference before fusing and reject outliers. In Kalman language this is innovation gating.
Derivation: Why inverse-variance weights are optimal
Blend two independent unbiased readings: x̂ = w·z₁ + (1 − w)·z₂. It is unbiased for any w.
Its variance is V(w) = w²σ₁² + (1 − w)²σ₂² (no cross term, by independence).
Minimise: dV/dw = 2wσ₁² − 2(1 − w)σ₂² = 0 ⇒ w = σ₂²/(σ₁² + σ₂²) = (1/σ₁²)/(1/σ₁² + 1/σ₂²).
d²V/dw² = 2(σ₁² + σ₂²) > 0, so this is a minimum.
Substitute back: V_min = σ₁²σ₂²/(σ₁² + σ₂²), i.e. 1/σ_f² = 1/σ₁² + 1/σ₂². For n sensors, weights ∝ 1/σᵢ² and precisions add.
Common mix-ups
Fusing with a worse sensor makes the result worse.
✓ With correct σ's and independent, unbiased errors, adding any sensor can only help (its weight shrinks as it gets worse).Twice as precise means twice the weight.
✓ Weight goes with 1/σ², so twice as precise means four times the weight.
6.2 The complementary filter
A gyro is smooth but drifts. An accelerometer never drifts but jitters. Could you keep the best half of each?
Two paths that add to one
θ[k] = α(θ[k−1] + ω·Δt) + (1 − α)·θ_acc. The gyro path (integrate rate) is effectively high-passed: good for fast changes. The accelerometer path is low-passed: good for the slow, long-term level. Because the two filters add to exactly one, the true signal passes through unchanged.
Choosing α
The crossover time constant is τ = αΔt/(1 − α). With α = 0.98 and Δt = 0.01 s, τ = 0.49 s: changes faster than about half a second come from the gyro, slower ones from the accelerometer. Pick τ longer than the accelerometer's jitter but shorter than the time the gyro takes to drift noticeably.
Complementary versus Kalman
The complementary filter uses a fixed blend. A Kalman filter computes its gain from Q and R and can add the gyro bias as a state and estimate it, so the drift is removed rather than just pulled back. In steady state, a scalar Kalman filter with constant gain behaves much like a well-tuned complementary filter.
Common mix-ups
The complementary filter averages the two sensors.
✓ It splits them by frequency: gyro for fast changes, accelerometer for slow ones.A bigger α is always better because the gyro is smoother.
✓ Bigger α means a longer τ and more bias error. The best α balances drift against jitter.
6.3 The predict–update cycle
Drive a metre: your uncertainty grows. See a landmark: it shrinks. Repeat forever. That rhythm is the whole idea of a filter.
Predict
Push the estimate through the model: x⁻ = x + u (here, the commanded move) and P⁻ = P + Q. Q is the variance the model adds each step: wheel slip, gusts, anything unmodelled. Prediction always increases uncertainty.
Update
When a measurement z with variance R arrives, compute the innovation z − x⁻, the gain K = P⁻/(P⁻ + R), then x = x⁻ + K(z − x⁻) and P = (1 − K)P⁻. This is the conjugate normal update from week 13 with the prediction as prior.
Checking a filter honestly
In simulation you know the truth, so measure RMSE of x − x_true. Also check consistency: about 95% of errors should fall within ±2√P. If the truth often leaves the band, the filter is overconfident (Q or R too small); if it never comes close to the edge, it is too cautious.
Common mix-ups
A low RMSE proves the filter is right.
✓ It must also be consistent: its own σ should match its actual errors, or downstream decisions will be over- or under-cautious.The update step can increase uncertainty.
✓ For a correct linear-Gaussian model P = (1 − K)P⁻ is always smaller than P⁻. A surprising measurement moves x a lot, but P still shrinks.
6.4 The Kalman gain as the variance-minimising weight
Why P/(P + R)? Not a guess, not a rule of thumb: it is the only weight that makes the error as small as possible.
Reading the gain
K → 1 when R ≪ P⁻: trust the sensor, x ≈ z. K → 0 when R ≫ P⁻: trust the prediction, ignore the reading. K is not a tuning knob you set; it is computed from the variances you believe. What you tune are Q and R.
Steady state
With constant Q and R the variance stops changing. For the random-walk model x[k+1] = x[k] + u + w, the prior variance converges to P⁻∞ = (Q + √(Q² + 4QR))/2. With Q = 0.3, R = 2: P⁻∞ ≈ 0.939, K∞ ≈ 0.319. Many embedded filters precompute this constant gain.
In more dimensions
For vector states, K = P⁻Hᵀ(HP⁻Hᵀ + R)⁻¹ and P = (I − KH)P⁻, where H maps the state to what the sensor sees. The scalar case is H = 1. The same minimum-variance argument, done with matrices, gives the same structure.
Derivation: The scalar Kalman gain
Update rule: x = x⁻ + K(z − x⁻) = (1 − K)x⁻ + Kz. Prediction error e⁻ has variance P⁻; measurement error v has variance R; they are independent.
Posterior error e = (1 − K)e⁻ + K·v (the true x cancels because both terms are unbiased).
Its variance: P(K) = (1 − K)²P⁻ + K²R.
Minimise: dP/dK = −2(1 − K)P⁻ + 2KR = 0 ⇒ K = P⁻/(P⁻ + R).
Substitute back: P = (1 − K)P⁻ = P⁻R/(P⁻ + R), i.e. 1/P = 1/P⁻ + 1/R: inverse-variance weighting, again.
Common mix-ups
K is a gain you tune by hand.
✓ K is computed from P⁻ and R. You tune the noise models Q and R; the gain follows.The Kalman filter is a different idea from averaging.
✓ Its update is inverse-variance weighting of the prediction and the measurement.
Examples to try
Worked solutions are in the interactive chapter online.
Inverse-variance weighting: example 1
Readings 10 (σ = 3) and 13 (σ = 2). Fuse them.
The complementary filter: example 1
α = 0.98, Δt = 0.01 s. Time constant? Steady-state tilt error from a 0.5 °/s gyro bias?
The predict–update cycle: example 1
x = 0, P = 1 m². Drive u = 1 m with Q = 0.25 m². Fix z = 1.6 m with R = 0.5 m². Predict and update.
The Kalman gain as the variance-minimising weight: example 1
Q = 0.3, R = 2. Find the steady-state prior variance, gain and posterior variance.
Interactive figures, in words
Figure 6.2 from “Inverse-variance weighting”
Set σ₁ = 1, σ₂ = 2. Drag your weight w from 0 to 1 and watch the lower curve: the blend's σ dips to a minimum. Find it by hand, then press 'snap' to check. Repeat with equal σ's: where is the minimum now, and what is the fused σ?
The fusion diagram plots both sensor curves, your blend and the optimal fusion, plus a curve of blend σ against weight with its minimum marked. The readout gives the optimal weight, fused value and σ, and how far your chosen weight is from optimal.
Figure 6.3 from “The predict–update cycle”
Step predict → update ten times in clear skies and watch the band settle to a steady width. Reset, switch on dust, and step again: note how wide the band gets during the gaps. Check after each update that the green truth line stays inside the ±2σ band most of the time.
The Kalman stepper plots truth, landmark fixes and the estimate with a ±2σ band over 20 steps. Each button press updates a text readout with the estimate, σ, truth, error and gain.
Laboratory (online)
These run in a browser on the full site. Simulations are simplified educational models.
- Simulation OS: Two-sensor fusion (Simulation OS experiment)
Switch between the complementary and Kalman filters, add camera dropouts and compare the position error of each.
Open online - Playground: Sensor fusion (Playground lab)
Change the claimed noise of one sensor and watch how the fused estimate shifts its trust.
Open online
Practice questions
Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.
1. Sensor σ's are 2 m and 4 m. What weight does the 2 m sensor get?
Answer:
Check it in “Inverse-variance weighting”
2. Sensor B has a hidden +5 m bias but claims σ = 0.5 m; sensor A is unbiased with σ = 2 m. The fused estimate will be…
- Close to B, and wrong by nearly 5 m, with a small reported σ
- Close to the truth
- Exactly halfway
- Rejected automatically
Check it in “Inverse-variance weighting”
3. A complementary filter runs at Δt = 0.005 s with α = 0.99. What is its time constant τ, in seconds?
Answer: s
Check it in “The complementary filter”
4. What happens if α = 1?
- Pure gyro integration: drift is never corrected
- Pure accelerometer: very noisy
- Perfect fusion
- The filter stops updating
Check it in “The complementary filter”
5. A filter has P = 0.4 m² after an update. Q = 0.3 m² per step. With no fixes for 6 steps, what is P, in m²?
Answer: m²
Check it in “The predict–update cycle”
6. In simulation, the true position leaves the filter's ±2σ band on 40% of steps. The most likely problem is…
- Q and/or R are set too small: the filter is overconfident
- Q and R are too large
- The filter is working perfectly
- The truth is wrong
Check it in “The predict–update cycle”
7. A filter is told R = 0 (a perfect sensor). What does it do at each update?
- Sets x = z exactly and P = 0
- Ignores the measurement
- Averages x⁻ and z
- Crashes
Check it in “The Kalman gain as the variance-minimising weight”
8. P⁻ = 4 m², R = 1 m². What is the posterior variance P, in m²?
Answer: m²
Check it in “The Kalman gain as the variance-minimising weight”
Engineering applications
Drones holding level
A drone fuses a gyro, which is smooth but drifts, with an accelerometer, which is noisy but knows where down is. A complementary filter gives a steady attitude estimate hundreds of times a second.
Phones finding themselves
A phone's location blends satellite fixes, Wi-Fi and motion sensors. When the satellite signal is lost indoors, the motion prediction carries the estimate until a fix returns.
Summary
- Weight independent readings by 1/σ²; the fused variance is smaller than any single one.
- A biased sensor that claims to be precise will drag a fused estimate off; weights are only as honest as the noise models.
- A complementary filter trusts a fast sensor at short time scales and a slow one at long time scales.
- The Kalman filter predicts with a model, then updates with a measurement using the variance-minimising gain.
Glossary
- IMU (inertial measurement unit)
- An IMU combines an accelerometer, which measures acceleration including gravity, and a gyroscope, which measures angular velocity; some add a magnetometer.
- Encoder counts and resolution
- A rotary encoder reports rotation as a count of ticks. Its resolution is the number of counts per revolution (CPR), often four times the pulses per revolution with quadrature decoding.
- Odometry
- Odometry estimates a robot's position and heading by adding up how far its wheels have turned since a known start.
- Random and systematic error
- Random errors scatter readings unpredictably above and below the true value; systematic errors shift every reading the same way.
Project: Where is the rover?
Using the rover or two-sensor simulation, estimate position with dead reckoning alone, then with fusion. Tune the filter's noise settings, state them, and report the error over a full route, including during sensor dropouts.
Deliverables
- The filter settings and their justification
- Error over the route for each method
- Behaviour during dropouts and one limitation
References
- Rudolf E. Kalman (1960). "A New Approach to Linear Filtering and Prediction Problems". Journal of Basic Engineering 82(1), 35–45.
- Sebastian Thrun et al. (2005). Probabilistic Robotics. MIT Press.
7. Learning from data
Sometimes the rule is easier to learn than to write. A perceptron weighs its inputs, adds a bias and draws one straight line between two classes. Gradient descent adjusts the weights a little at a time to shrink the error. This chapter trains a single neuron by hand, shows why one line cannot solve every problem, checks a model fairly with cross-validation, and asks whether the result fits in a small device's memory, time and energy.
Figure 7.1. One neuron, one line (described in words)
A perceptron with weights 1 and 1 and bias −1.5 draws the line x1 + x2 = 1.5 across the unit square. The points (0, 0), (0, 1) and (1, 0) give z below zero and output 0; only (1, 1), with z = 0.5, gives 1, so the neuron computes AND.
Explanation
7.1 The perceptron: one neuron draws one line
The first learning machine, built in 1958, could tell shapes apart by nudging a few numbers. What exactly was it nudging, and what could it never learn?
Weighted sum, bias, step
A perceptron takes inputs x₁, x₂, … and computes z = w₁x₁ + w₂x₂ + … + b. The weights say how much each input matters (and in which direction); the bias b shifts the result. A step function then decides: output 1 if z ≥ 0, else 0. With w = (2, 1) and b = −6, the input (3, 1) gives z = 6 + 1 − 6 = 1, so output 1; the input (1, 2) gives z = −2, so output 0.
The decision boundary is a line
The output switches where z = 0: for two inputs, w₁x₁ + w₂x₂ + b = 0 is a straight line. With w = (2, 1), b = −6 it is 2x₁ + x₂ = 6, through (3, 0) and (0, 6). The weight vector points across the line towards the class-1 side; scaling all weights and bias together changes nothing about the line. Changing b slides the line without turning it.
Learning by fixing mistakes
The perceptron rule looks at one example at a time. If it is right, nothing changes. If it is wrong, each weight moves by η(t − y)xᵢ and the bias by η(t − y), where t is the target, y the output and η the learning rate. A missed 1 (t − y = +1) adds the input to the weights, raising z for that input next time; a false 1 subtracts it. If a separating line exists, this is guaranteed to find one.
The XOR wall
XOR labels (0, 0) and (1, 1) as one class and (0, 1) and (1, 0) as the other. No straight line separates them, so a single perceptron keeps getting at least one point wrong forever. Adding a hidden layer of neurons fixes this: two lines combined can carve out the diagonal pair. That insight, and a way to train hidden layers, is what turned perceptrons into neural networks.
Common mix-ups
A perceptron can learn any pattern if you train it long enough.
✓ It can only learn patterns a straight line (a hyperplane) separates. XOR needs a hidden layer.The perceptron rule changes the weights after every example.
✓ It changes them only when the example is misclassified; correct answers leave the weights alone.Bigger weights mean a better classifier.
✓ Multiplying all weights and the bias by the same positive number leaves the boundary exactly where it was.
7.2 Gradient descent on a one-neuron network
A network with millions of weights learns by asking one question of each weight: “if I nudge you, does the error go up or down?” How is that question answered?
A smooth neuron and its loss
Replace the hard step with the sigmoid σ(z) = 1/(1 + e^(−z)), which glides from 0 to 1. One neuron computes y = σ(wx + b). To measure how wrong it is on an example with target t, use the squared-error loss L = ½(y − t)². The ½ is only there to cancel a 2 when we differentiate. Training means choosing w and b to make L small across the data.
Blame by the chain rule
L depends on w only through z and y, so ∂L/∂w = (∂L/∂y)(∂y/∂z)(∂z/∂w) = (y − t) · y(1 − y) · x. Each factor has a meaning: how wrong the output is, how sensitive the sigmoid is at this point (at most 0.25, at z = 0), and how big the input was. A zero input gets no blame. The same idea, repeated backwards through layers, is backpropagation.
One step downhill
Gradient descent updates w ← w − η·∂L/∂w: move against the gradient, scaled by the learning rate η. Take w = 0.5, b = 0, x = 2, t = 1. Then z = 1, y ≈ 0.7311, ∂L/∂w ≈ (−0.2689)(0.1966)(2) ≈ −0.1058. With η = 1, w becomes ≈ 0.6058 and the loss falls from ≈ 0.0362 to ≈ 0.0263. Negative gradient, so w went up.
Choosing the learning rate
For the bowl L(w) = (w − 3)², each step multiplies the distance from the minimum by (1 − 2η). With η = 0.1 the distance shrinks by 0.8 per step: safe but slow. η = 0.5 lands exactly on the minimum. Between 0.5 and 1 it overshoots but still settles; above 1 the distance grows every step and training diverges. Real loss surfaces are not perfect bowls, which is why η is tuned and often decreased over time.
Derivation: ∂L/∂w for one sigmoid neuron
Define z = wx + b, y = σ(z) = 1/(1 + e^(−z)), and L = ½(y − t)².
Outer link: ∂L/∂y = (y − t), because the ½ cancels the 2 from differentiating a square.
Middle link: dσ/dz = e^(−z)/(1 + e^(−z))² = σ(z)·(1 − σ(z)) = y(1 − y).
Inner link: ∂z/∂w = x (and ∂z/∂b = 1).
Multiply the links (chain rule): ∂L/∂w = (y − t) · y(1 − y) · x, and ∂L/∂b = (y − t) · y(1 − y).
Update: w ← w − η(y − t)y(1 − y)x. Check with numbers: w = 0.5, b = 0, x = 2, t = 1 gives ∂L/∂w ≈ −0.1058; η = 1 gives w ≈ 0.6058, and the loss drops from ≈ 0.0362 to ≈ 0.0263.
Common mix-ups
The gradient points towards the minimum.
✓ It points uphill, in the direction of steepest increase. Gradient descent steps the opposite way.A larger learning rate always trains faster.
✓ Beyond a limit set by the curvature (η > 1 for (w − 3)²) the steps overshoot and training diverges.Backpropagation is a different algorithm from the chain rule.
✓ It is the chain rule applied layer by layer, reusing each layer's partial results.
7.3 Cross-validation: grading a model fairly
Your classifier scores 97% on your data, then 71% on the device in the field. Which number was lying, and how could you have known before shipping?
Why one split is not enough
Testing on the data you trained on rewards memorising: an overfitted model scores brilliantly and fails in the field. A single held-out split is honest but noisy, especially with little data: which examples happened to land in the test set can swing the score by several per cent. k-fold cross-validation reduces that luck by repeating the split k times.
The k-fold recipe
Shuffle (unless order matters), then cut the data into k equal folds. For each fold in turn: train a fresh model on the other k − 1 folds, test it on this one, record the score. With 1000 examples and k = 5, each model trains on 800 and is tested on 200. Report the mean of the k scores and their spread (standard deviation or range). Common choices are k = 5 or 10.
Reading the spread
Fold scores of 82, 85, 79, 88 and 81% have mean 83.0% and sample standard deviation about 3.5 points. That spread is part of the result: a rival model scoring 84% is not clearly better. A large spread means the model is sensitive to which data it sees, often a sign of too little data or of a few unusual examples clustered in one fold.
Leakage and the final test
Leakage is test information sneaking into training: normalising with statistics computed on all the data before splitting, near-duplicate recordings in different folds, or shuffling time-series so the model trains on the future. Do every preprocessing step inside each fold, and split by recording session or device, not by row. Use cross-validation to choose models; keep a separate test set you touch once, at the very end.
Common mix-ups
Cross-validation replaces a final test set.
✓ It is for choosing between models and settings. Keep a separate test set untouched until the end, or your choices quietly overfit the CV score.A higher mean CV score always means a better model.
✓ Compare against the spread: a 1-point gain inside a 3.5-point standard deviation is not convincing evidence.Shuffling rows is always safe.
✓ For time series or repeated recordings, shuffling leaks the future or near-duplicates into training; split by time, session or device.
7.4 Fitting a model into memory, time and energy
A smartwatch must recognise a gesture in 20 ms, using under 1 mJ, with 64 KB of RAM. Can your model do it? Work it out before you build it.
The budget table
Write one row per resource: flash (weights + code), RAM (peak activations + buffers + stack), latency (MACs ÷ MAC rate + overheads) and energy (MAC energy + memory energy + idle energy). Each has a limit from the product requirement. The design is feasible only if every row fits, with a margin.
Energy per inference
E ≈ MACs × e_MAC + bytes moved × e_byte + P_idle × time. Because e_byte can be tens to hundreds of times e_MAC (depending on which memory), a model with fewer weight reads can beat one with fewer MACs. Reusing data already in registers or SRAM is the key trick of efficient accelerators.
Which knob?
Too big for flash: quantise or prune. Too big for RAM: process in smaller tiles, or choose layers with smaller activations. Too slow: fewer MACs, SIMD instructions or an accelerator. Too much energy: reduce data movement, then MACs, then duty-cycle the device. Each change must be re-checked against accuracy on held-out data.
Common mix-ups
Fewer MACs always means less energy.
✓ Memory traffic often costs more than arithmetic; a model with more MACs but more data reuse can use less energy.If it fits in flash, it fits.
✓ RAM for activations, latency and energy are separate budgets that must each be met.
Examples to try
Worked solutions are in the interactive chapter online.
The perceptron: one neuron draws one line: example 1
w = (1, −2), b = 3. Classify the input (4, 1).
The perceptron: one neuron draws one line: example 2
The perceptron above wrongly outputs 1 for (4, 1), whose target is 0. Apply one update with η = 0.5.
Gradient descent on a one-neuron network: example 1
For L(w) = (w − 3)², start at w = 5 with η = 0.25. Take one step.
Gradient descent on a one-neuron network: example 2
A sigmoid neuron has z = 0. What is σ'(z), and why does it matter?
Cross-validation: grading a model fairly: example 1
A dataset has 500 examples and you use 10-fold cross-validation. How many examples does each model train on and test on?
Cross-validation: grading a model fairly: example 2
Fold accuracies are 82, 85, 79, 88 and 81%. Report the result properly.
Fitting a model into memory, time and energy: example 1
Budget check: 32,128 MACs and 32 KB of int8 weights; 1 MAC/cycle at 48 MHz; 3 pJ/MAC; 25 pJ/byte from flash. Latency and energy?
Interactive figures, in words
Figure 7.2 from “The perceptron: one neuron draws one line”
Use the separable dataset with η = 0.5 and press “Show next example” repeatedly. Watch the line jump only when a point is misclassified. Then switch to the XOR pattern and run several full passes: does it ever settle?
The perceptron diagram plots six points on a 0–5 grid: class 0 (circles) at (1, 1), (2, 1) and (1, 3); class 1 (squares) at (3, 4), (4, 2) and (4, 4). Weights start at zero. Each step shows one example; if it is misclassified the weights and bias change by η(t − y)x and the decision line moves. The readout gives the weights, the bias and how many points are misclassified; on this set it reaches zero. On the XOR set ((1, 1) and (4, 4) class 0; (1, 4) and (4, 1) class 1) at least one point is always wrong.
Figure 7.3 from “Gradient descent on a one-neuron network”
Start at w₀ = −1. Take steps with η = 0.1, then 0.5, then 0.9, then 1.05. For each, count steps until the readout says converged, or note when it never does.
The gradient-descent diagram plots the loss L(w) = (w − 3)² + 1 as a U-shaped curve with its lowest point at w = 3. Each press of Take one step moves w by −η × 2(w − 3) and marks the new point. From w₀ = −1: with η = 0.1 the points creep towards 3; with η = 0.5 the first step lands exactly on 3; with η = 0.9 they zig-zag across the minimum but settle; with η = 1.05 each zig-zag is wider and the readout warns that training is diverging.
Figure 7.4 from “Cross-validation: grading a model fairly”
Choose k = 2, then 4, then 6. Click through the held-out folds. How do the fold accuracies, their mean and their spread change as k grows?
The k-fold diagram shows 24 labelled readings as a row of boxes numbered by fold (example i belongs to fold i mod k); the held-out fold is filled in. For each fold a threshold classifier is trained on the other folds (threshold halfway between the two class means) and tested on the held-out fold. A list gives each fold's training size, test size and accuracy, and the readout reports the mean accuracy, its standard deviation and its range for k = 2, 3, 4 or 6.
Laboratory (online)
These run in a browser on the full site. Simulations are simplified educational models.
- Equation Lab: Optimisation (Equation Lab exploration)
Run gradient descent with three learning rates and find the largest one that still converges.
Open online - Code Lab (Studio)
Train a single perceptron on the AND truth table with the update rule, then try XOR and record what happens.
Open online
Practice questions
Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.
1. A perceptron has w₁ = 1, w₂ = −2 and b = 3. What is z for the input (x₁, x₂) = (4, 1)?
Answer:
Check it in “The perceptron: one neuron draws one line”
2. You increase a perceptron's bias b and leave the weights alone. What happens to its decision line?
- It rotates
- It slides parallel to itself
- It bends
Check it in “The perceptron: one neuron draws one line”
3. Why can a single perceptron never classify all four XOR points correctly?
- The learning rate is too small
- No straight line separates the two classes
- It needs more training passes
Check it in “The perceptron: one neuron draws one line”
4. For L(w) = (w − 3)², start at w = 5 with learning rate η = 0.25. What is w after one gradient-descent step?
Answer:
Check it in “Gradient descent on a one-neuron network”
5. During training the loss jumps around and then grows larger every epoch. What is the most likely cause?
- The learning rate is too small
- The learning rate is too large
- There is too much training data
Check it in “Gradient descent on a one-neuron network”
6. Which of these causes data leakage in cross-validation?
- Using k = 10 instead of k = 5
- Scaling features with the mean and spread of the whole dataset before splitting into folds
- Reporting the standard deviation of fold scores
Check it in “Cross-validation: grading a model fairly”
7. Fold accuracies are 90, 72, 88, 91 and 74%. What should you report?
- 91%, the best fold
- The mean, 83%, with its large spread
- 90%, the first fold
Check it in “Cross-validation: grading a model fairly”
8. Your model's weights fit in flash, but one layer's input and output activations together exceed RAM. What is the most direct fix?
- Quantise the weights further
- Process the layer in tiles, or redesign it with smaller activations
- Raise the clock
- Train for longer
Check it in “Fitting a model into memory, time and energy”
Engineering applications
Keyword spotting
A smart speaker's wake-word detector is a small network running all the time on a low-power chip. It must fit in a few hundred kilobytes and draw only milliwatts.
Gesture recognition
A wristband can learn the motion pattern of a tap or a wave from labelled examples. Cross-validation across different people shows whether it will work for someone new.
Summary
- A perceptron outputs 1 when w·x + b > 0: one straight boundary between two classes.
- One line can separate AND but not XOR; hidden layers combine several lines.
- Gradient descent steps against the gradient; too large a learning rate makes the loss grow.
- Cross-validation rotates the held-out fold; any information leaking from test data into training invalidates it.
- A model for a device must fit its flash, RAM, time and energy budgets, not just reach an accuracy.
Glossary
- Truth table
- A truth table lists the output of a logic function for every possible combination of its inputs; n inputs need 2^n rows.
- AND gate
- An AND gate outputs 1 only when all of its inputs are 1.
- XOR gate
- An XOR gate outputs 1 when its inputs are different and 0 when they are the same.
Project: Train a neuron, then grade it fairly
Create or choose a small two-feature data set (for example, ripe or unripe fruit from colour and firmness readings you simulate). Train a perceptron, evaluate it with 5-fold cross-validation, and report the mean accuracy, its spread and one failure case.
Deliverables
- The data set and how it was made
- Training curve and final weights
- Cross-validated accuracy with spread and a failure case
References
- Frank Rosenblatt (1958). "The Perceptron: A Probabilistic Model for Information Storage and Organization in the Brain". Psychological Review 65(6), 386–408.
- Ian Goodfellow et al. (2016). Deep Learning. MIT Press.
- Trevor Hastie et al. (2009). The Elements of Statistical Learning, 2nd edition. Springer.
8. Evaluating intelligent systems honestly
An intelligent system is only as good as the evidence that it works. This chapter treats evaluation as part of design: choose the metric before testing, keep test data untouched until the end, compare against a fair baseline, take the system apart with ablations to see which piece earns its place, and describe failure modes in words someone can act on. A result that survives all of that is worth reporting.
Figure 8.1. Five folds, five honest tests (described in words)
Five-fold cross-validation of 400 examples drawn as a 5 by 5 grid. In each round one fold of 80 examples, shown tinted, is held out for validation while the model trains on the other 320. Every example is used for validation exactly once.
Explanation
8.1 Designing a perception pipeline
Sense, filter, segment, measure, decide. Which stage of the pipeline fails first when the lights flicker?
Stages and interfaces
Write the pipeline as boxes: sense (camera or sensor, sample rate) → condition (filter, calibrate) → segment (threshold, colour rule) → measure (label, area, position) → decide (rule, threshold from costs). For each stage state its input, output, units and parameters. That list is your design, and also your debugging map.
One question at a time
A good investigation asks a focused question, changes one variable, holds the others fixed, repeats runs to see the spread, and chooses its metric (recall, precision, throughput) before looking at results. Record everything, including runs that look wrong.
Planning the term project
The project, 'Count the parts, honestly', needs: a set of images with hand-counted ground truth; separate tuning and test images; at least three conditions (normal, changed lighting, added noise or occlusion); a metric per condition; and one mitigation tried and measured. Plan the data before writing code.
Common mix-ups
If the final number looks right, every stage works.
✓ Errors can cancel. Check stage outputs too, especially under changed conditions.Tuning on the test images is fine if you're careful.
✓ Any tuning on test data makes the test optimistic. Keep test images untouched until the end.
8.2 Evaluating honestly: held-out tests and failure modes
Your threshold scores 98% on the images you tuned it on. On new images it scores 81%. Which number goes in the report?
Tune on one set, test on another
Split data before you start: a tuning (or training) set for choosing parameters and a test set touched once, at the end. Any decision made by looking at test results, even choosing between two thresholds, leaks information and inflates the score. With little data, keep at least a small test set sacred.
Report by condition, with counts
Give precision and recall for each condition (normal, dim, noisy, occluded), with the underlying TP/FP/FN counts and the number of items. 'Recall 90% (27 of 30)' tells a reader how much to trust it; '90%' alone does not. Say how ground truth was obtained.
Failure modes are findings
A failure mode is a describable situation where the system goes wrong: touching parts merge, glare saturates pixels, shadows split objects. Show an example, explain the cause using this term's ideas, try one mitigation, and measure it on the test set. A report that hides its failures is less useful, and less trustworthy, than one that explains them.
Common mix-ups
Reporting the tuning-set score is fine if it's labelled.
✓ Label it, but the headline must be the held-out test score; the tuning score describes how well you fitted, not how well it works.Failures make a project look bad.
✓ Well-explained, measured failures show you understand the system and help others avoid them.
8.3 Benchmarking computer systems fairly
Your new code is '30% faster' on your laptop. Run it again and it's 5% slower. Which number goes in the report?
Protocol first
Fix the workload (inputs, sizes, a standard suite if one exists), the system (hardware, OS, compiler and flags, versions), conditions (power mode, temperature, background load) and the procedure: warm-up runs discarded, N timed repeats, randomised or interleaved order between the systems being compared. Write it down before running, as in Term 2's pre-registration.
Metrics
Primary metric: the one your claim rests on, chosen in advance (for example p99 latency). Secondary: throughput, energy per task, peak memory, accuracy. For distributions, report median and tail percentiles, not just the mean. Use execution time, not MIPS or GHz, as the Iron Law warns.
Uncertainty and comparison
Repeat runs vary. Report the spread (standard deviation or interquartile range) and a confidence interval for the difference between systems, from paired or interleaved runs. A 3% gain with a ±5% interval is not a demonstrated gain.
Trade-offs
Many systems win on one metric and lose on another: faster but hungrier, smaller but less accurate. A design is Pareto-optimal if nothing beats it on every metric at once. Show the front and say which point your requirement selects.
Common mix-ups
One run is enough if the computer is fast.
✓ Run-to-run variation is often several percent; repeats and intervals are essential.The mean latency is the right summary.
✓ For deadlines and user experience, tails (p95, p99, max) matter more.
8.4 Ablations: which part made it better?
Your new design is 40% faster. It has a bigger cache, a new predictor and a compiler flag. Which one did the work?
One change at a time
Start from the full system and remove (or start from the baseline and add) one component per run, holding everything else fixed: same inputs, same metric, same conditions. The difference from the reference attributes performance to that component.
Interactions
Components can interact: a bigger cache may make a prefetcher less useful, or a predictor may matter only with a deep pipeline. A full factorial design (every combination; 2ⁿ runs for n on/off components) reveals interactions; with many components, test the most plausible pairs.
Explain, don't just tabulate
Tie each effect to a mechanism. 'Two-way associativity removed the conflict misses because a[i] and b[i] share index bits' is a finding; '2-way is 4× better' is only a number. Mechanism-level explanations generalise to new workloads; raw numbers may not.
Common mix-ups
If the full system is better, every component must be helping.
✓ Some may do nothing or even hurt; only ablations show it.Ablating each component once is enough.
✓ Components can interact; check plausible combinations and report uncertainty on each effect.
Examples to try
Worked solutions are in the interactive chapter online.
Designing a perception pipeline: example 1
Write a one-line research question and method for the sorting machine.
Evaluating honestly: held-out tests and failure modes: example 1
Test results: normal light TP 28, FN 2, FP 1; dim light TP 19, FN 11, FP 0. Summarise.
Benchmarking computer systems fairly: example 1
Ten paired runs of old vs new code give time differences (old − new) with mean 1.2 ms and standard deviation 2.0 ms. Is the new code faster?
Ablations: which part made it better?: example 1
Simulator misses for the colliding arrays: baseline (direct-mapped, 16 B) 16; 2-way only 4; 32 B blocks only 2; both 2. Main effects and interaction?
Interactive figures, in words
Figure 8.2 from “Evaluating honestly: held-out tests and failure modes”
On the tuning batch, find the threshold with the highest accuracy and write down precision and recall. Switch to the fresh test batch without moving the slider. What changed? Is there a threshold that does well on both, and how would you have found it without peeking?
The confusion-matrix diagram has a tuning batch and a fresh test batch of 60 simulated parts each. A threshold chosen to maximise accuracy on the tuning batch usually gives a slightly different, often lower, accuracy, precision and recall on the test batch, because the two batches' random overlap differs.
Figure 8.3 from “Ablations: which part made it better?”
Baseline: 'Two arrays that collide', direct-mapped, 16 B blocks. Record the misses. Now change only associativity, then only block size (back to direct-mapped), then both. Fill a 2×2 table of misses. Then read the note under the simulator: what else changes when the block size changes with 8 lines fixed?
With 'Two arrays that collide' (16 reads): direct-mapped with 16 B blocks gives 16 misses; 2-way gives 4; direct-mapped with 32 B blocks gives 2, because the 8-line cache doubles in size; 2-way with 32 B blocks also gives 2.
Laboratory (online)
These run in a browser on the full site. Simulations are simplified educational models.
- Nexus: Automated sorting (Nexus project)
Run the sorting system with and without one sensor and report the change in errors as an ablation, with repeats.
Open online - Simulation OS: Two-sensor fusion (Simulation OS experiment)
Compare the fused estimate against a camera-only baseline on the same seeds, and report the difference rather than two averages.
Open online
Practice questions
Questions only. Each one is answered in its Lite lesson online, where it is checked on our server.
1. Which change would make a belt-speed comparison unfair?
- Using the same test batch for every speed
- Re-tuning the thresholds separately at each speed without saying so
- Repeating each speed three times
Check it in “Designing a perception pipeline”
2. Why choose the metric before running the tests?
- It saves time
- So you can't pick, after the fact, whichever metric makes your favourite setting look best
- Metrics change during testing
Check it in “Designing a perception pipeline”
3. Your parts counter is wrong only in dim images. The threshold mask looks fine in bright images but patchy in dim ones. Which stage should you fix first?
- The decision rule
- Segmentation (thresholding) or the lighting before it
- Labelling
Check it in “Designing a perception pipeline”
4. You compare two thresholds on the test set and report the better one's score. What is wrong?
- Nothing
- Choosing on the test set makes it part of tuning, so the reported score is optimistic
- You should have compared three
Check it in “Evaluating honestly: held-out tests and failure modes”
5. Which failure-mode statement is most useful?
- 'It sometimes doesn't work.'
- 'In 6 of 10 dim images, parts below brightness 90 were missed; adaptive thresholding cut misses to 2 of 10.'
- 'Dim images are hard for computers.'
Check it in “Evaluating honestly: held-out tests and failure modes”
6. Why discard warm-up runs?
- To hide slow results
- Because first runs include one-off costs (cold caches, loading, JIT compilation) not present in steady state
- To make the numbers smaller
- Because the first run is always wrong
Check it in “Benchmarking computer systems fairly”
7. Which is an ablation?
- Comparing your system with a competitor's
- Removing one component of your system at a time and measuring the change
- Running the full system ten times
- Tuning all parameters together
Check it in “Ablations: which part made it better?”
8. Doubling the L1 cache cut run time by 20%. Which follow-up best explains it from first principles?
- Report '20% faster' and stop
- Measure the miss rate before and after and check whether AMAT × accesses per instruction accounts for the CPI change
- Try a third cache size and pick the best
- Measure clock frequency
Check it in “Ablations: which part made it better?”
Engineering applications
Self-driving test reports
Serious evaluations of driving software report performance by condition (night, rain, junctions), not one overall score, because an average can hide the situation where the system fails.
Model cards
Teams publishing a trained model increasingly document its intended use, the data it was tested on and where it performs poorly, so that others do not use it outside its evidence.
Summary
- Choose the metric and the decision rule before running the tests.
- Test data stays untouched until the end; tuning on it turns a test into training.
- Compare against a fair baseline on the same inputs, and report the difference with its uncertainty.
- Ablations remove one component at a time to show which part caused the gain.
- Failure modes should be specific: the condition, the effect and how often it happens.
Glossary
- Baselines and control conditions
- A baseline is the reference condition a new idea is compared with, such as the existing design or a simple method, tested in the same way.
- Outliers and honest data
- An outlier is a reading far from the rest. It may be a genuine effect or a fault; either way it must be investigated and reported, and any exclusion rule decided before seeing the results.
- Stating limitations
- A limitations section states plainly what your work cannot show: the conditions you did not test, the size of your sample, the assumptions in your models and the sources of uncertainty you could not remove.
- Repeated trials
- Repeating a measurement or test several times shows how much results vary and lets you average out random error.
Project: An evaluation plan before the results
For a perception or fusion system from this book, write an evaluation plan: the metric, the baseline, the held-out data, one ablation and the decision rule. Then run it in simulation and report the result against the plan, including any deviation.
Deliverables
- The dated evaluation plan
- Results against the baseline with uncertainty
- One ablation and a specific failure mode
References
- Trevor Hastie et al. (2009). The Elements of Statistical Learning, 2nd edition. Springer.
- Stuart Russell and Peter Norvig (2020). Artificial Intelligence: A Modern Approach, 4th edition. Pearson.
Known limitations
- Not yet tested by a person using a screen reader; only automated structure checks have run.
- Some interactive lesson diagrams need a pointer or keyboard and a recent browser; their text alternatives carry the same idea without the interaction.
- Mathematics is written as plain text (for example x^2 and sqrt(x)), like the School lessons, not typeset notation.