Part 3: Machine learning Lesson 14 of 20 in this part
Thinking in probabilities
What you will learn. Update a belief with Bayes' rule, read a small Bayesian network, explain how a Markov chain Monte Carlo sampler explores a distribution, and follow a one-number Kalman filter.
Before this lesson: Measuring models honestly. Already know these? Carry on.
In plain words
Most models give one answer. A probabilistic model says how sure it is, and updates as evidence arrives. The rule for updating is Bayes' rule: start with a prior belief, multiply by how well each possibility explains the new evidence, and divide so that the beliefs add up to one again. It answers questions like: if a medical test is positive, how likely is the disease? The answer is often much lower than people expect, because most positive results come from the many healthy people. A Bayesian network draws the causes and effects as a diagram with a table of chances at each node, and lets you ask "given this, how likely is that?". When the maths is too hard to do exactly, Markov chain Monte Carlo (MCMC) wanders through the possible answers, spending more time where they are more likely, and the visits form a picture of the distribution. Variational inference instead fits a simple shape to the distribution. A Kalman filter is Bayes' rule for a moving thing: it combines a prediction with a noisy measurement and says how uncertain it still is.
Prior
- What you believed before
- For example how common a disease is
Posterior
- What you believe after the evidence
- Updated by how well each option explains it
The prior is what you believed. The posterior is what you believe after the evidence.
- InputPropose a nearby new valueA small random step
- ProcessCompare how well the new value explains the dataThe ratio of likelihoods
- ModelMove if better, or sometimes if worseOtherwise stay put
- OutputRecord the position and repeatThe visits form the posterior
The sampler needs only ratios of likelihoods, not the hard normalising constant.
Exact (enumeration)
- Adds up every possibility
- Gives exact answers, slow for big networks
Sampling (MCMC)
- Draws many examples from the distribution
- Approximate but works for huge models
Use exact methods when they are feasible, and sampling when they are not.
- InputStart with an estimate and its uncertaintyWhere we think it is, and how sure
- ProcessCompute the gain from the two uncertaintiesBig gain when the estimate is vague
- ModelMove the estimate towards the measurementBy the gain times the surprise
- OutputShrink the uncertaintyThe new estimate is more certain
The gain decides how much to trust the measurement against the current estimate.
Real-world example
A hospital screens for a rare disease. The test finds the disease in 90% of people who have it, and wrongly flags 5% of people who do not. Only 1 in 100 people has the disease. A patient tests positive. Most people guess the chance of disease is about 90%. Bayes' rule says it is closer to 15%, because the many healthy people produce more false alarms than the few sick people produce true positives. The hospital therefore follows every positive with a second, more accurate test. A navigation unit in a car uses a Kalman filter in the same spirit: it combines a prediction of where the car is with each noisy GPS reading.
How it works
- Bayes' rule. For each possibility, multiply its prior by the chance of the evidence under it. Divide each result by the total so they add up to one.
- Networks. Each node has a table of chances given its parents. To answer a question, add up the joint chance of every combination consistent with the evidence, then divide.
- MCMC. Start anywhere. Propose a nearby value. Move to it if its likelihood is higher, and otherwise move with a chance equal to the ratio of likelihoods. After a warm-up, the visits are samples from the posterior.
- Kalman filter. For one number, the gain is the current uncertainty divided by that uncertainty plus the measurement's uncertainty. The estimate moves by the gain times the surprise, and the uncertainty shrinks by the same factor.
- Related tools. Bayesian optimisation chooses the next setting to try by modelling what it has seen, and is popular for tuning expensive models. Probabilistic programming languages let you write a model and ask for its posterior.
Live simulation
A positive test is evidence, not proof. The numbers behind it are easiest to see as counts of people.
The question. Why does a positive result from a good test often still mean "probably fine"?
What to watch
- Out of 10,000 people, the first bar splits them into ill and healthy. The second bar shows only those with a positive test.
- When the illness is rare, a small false-alarm rate on a large healthy group can produce more false alarms than true cases.
- A second independent positive test changes the odds again.
This simulation needs JavaScript, which is switched off or not loaded. The lists above say what it shows, and the example programs below print the same kind of numbers.
Try this
- Make the illness rare (1% or less) and see the chance of illness after a positive test drop below 20%.
- Starting from an illness that affects at least 5% of people, switch on the second positive test and bring the chance of illness to 90% or more.
What this leaves out. Made-up percentages, whole-person counts, and the assumption that the two tests are independent. Real tests are often not independent of each other, and the chance of illness for a particular person depends on more than the average rate.
Python program that prints the same headline numbers: examples/sim-ai/ai.py.
Python example
Python: example run The example programme behind this lesson's quoted output ran on 2026-11-19 (Python 3.12.10). 1 code block in the lesson passed a syntax check, 1 also ran on their own.
Three demonstrations: enumeration in a small Bayesian network, a Metropolis sampler for a coin that showed 7 heads in 10 flips, and a Kalman filter with five noisy measurements of one number. A small repeatable random generator makes the numbers repeat.
"""Thinking in probabilities: a small Bayesian network, a Metropolis (MCMC) sampler for a coin, and a one-number Kalman filter.
Run: python bayes.py
"""
import math
# 1. A tiny Bayesian network: rain, sprinkler, wet grass. What is the chance of rain, given the grass is wet?
p_rain = 0.2
p_spr = {True: 0.01, False: 0.4} # sprinkler on, given rain / no rain
p_wet = {(True, True): 0.99, (True, False): 0.8, (False, True): 0.9, (False, False): 0.0} # wet, given (rain, sprinkler)
joint = {}
for rain in (True, False):
for spr in (True, False):
pr = (p_rain if rain else 1 - p_rain) * (p_spr[rain] if spr else 1 - p_spr[rain]) * p_wet[(rain, spr)]
joint[(rain, spr)] = pr
p_w = sum(joint.values())
print("chance the grass is wet: %.4f chance of rain given wet grass: %.4f" % (p_w, sum(v for (r, s), v in joint.items() if r) / p_w))
# 2. Metropolis sampler for a coin's chance of heads after 7 heads in 10 flips, starting from a flat prior
state = 2024
def rnd():
global state
state = (1103515245 * state + 12345) % (2 ** 31)
return state / 2 ** 31
like = lambda p: p ** 7 * (1 - p) ** 3
p, samples = 0.5, []
for step in range(20000):
q = p + (rnd() - 0.5) * 0.3 # propose a nearby value
if 0 < q < 1 and rnd() < like(q) / like(p): # accept if likelier, or sometimes if less likely
p = q
if step >= 2000:
samples.append(p)
mean = sum(samples) / len(samples)
sd = math.sqrt(sum((s - mean) ** 2 for s in samples) / len(samples))
print("MCMC posterior mean %.3f, spread %.3f (exact answer: mean 0.667, spread 0.131)" % (mean, sd))
# 3. Kalman filter for one unknown number, measured five times with noise of variance 1
est, var = 0.0, 100.0 # a vague starting guess
print("measurement estimate uncertainty (variance)")
for z in (5.1, 4.8, 5.3, 4.9, 5.0):
gain = var / (var + 1.0) # how much to trust the new measurement
est, var = est + gain * (z - est), (1 - gain) * var
print("%11.1f %8.3f %12.3f" % (z, est, var))chance the grass is wet: 0.4484 chance of rain given wet grass: 0.3577
MCMC posterior mean 0.664, spread 0.132 (exact answer: mean 0.667, spread 0.131)
measurement estimate uncertainty (variance)
5.1 5.050 0.990
4.8 4.925 0.498
5.3 5.050 0.332
4.9 5.012 0.249
5.0 5.010 0.200The network gives 0.4484 for wet grass and 0.3577 for rain given wet grass, as in the hand calculation. The sampler's posterior mean is 0.664 against an exact 0.667, and its spread 0.132 against an exact 0.131, so 20000 steps gave a good picture. The Kalman estimate settles near 5.0 and its uncertainty falls from 0.990 to 0.200 over five measurements.
.NET (C#) example
C#: compiled and run The C# sample compiled on 2026-11-19 with .NET SDK 10.0.400 (no extra packages). It also ran to the end without error.
Enumeration, Metropolis sampling and a Kalman filter written from scratch in C#, with no packages, printing the same output. For larger probabilistic models in .NET, Microsoft's Infer.NET library was built for this purpose; this guide did not run it, so the code here is plain C#.
// A tiny Bayesian network by enumeration, a Metropolis sampler and a Kalman filter, from scratch.
// Same output as bayes.py. No packages.
double pRain = 0.2;
var pSpr = new Dictionary<bool, double> { [true] = 0.01, [false] = 0.4 }; // sprinkler on, given rain / no rain
var pWet = new Dictionary<(bool, bool), double> { [(true, true)] = 0.99, [(true, false)] = 0.8, [(false, true)] = 0.9, [(false, false)] = 0.0 };
double pW = 0, pRainAndWet = 0;
foreach (bool rain in new[] { true, false })
foreach (bool spr in new[] { true, false })
{
double pr = (rain ? pRain : 1 - pRain) * (spr ? pSpr[rain] : 1 - pSpr[rain]) * pWet[(rain, spr)];
pW += pr; if (rain) pRainAndWet += pr;
}
Console.WriteLine($"chance the grass is wet: {pW:F4} chance of rain given wet grass: {pRainAndWet / pW:F4}");
// Metropolis sampler for a coin's chance of heads after 7 heads in 10 flips, starting from a flat prior
long state = 2024;
double Rnd() { state = (1103515245L * state + 12345) % (1L << 31); return state / (double)(1L << 31); }
double Like(double p) => Math.Pow(p, 7) * Math.Pow(1 - p, 3);
double pc = 0.5; var samples = new List<double>();
for (int step = 0; step < 20000; step++)
{
double q = pc + (Rnd() - 0.5) * 0.3; // propose a nearby value
if (q > 0 && q < 1 && Rnd() < Like(q) / Like(pc)) pc = q; // accept if likelier, or sometimes if less likely
if (step >= 2000) samples.Add(pc);
}
double mean = samples.Average();
double sd = Math.Sqrt(samples.Sum(s => (s - mean) * (s - mean)) / samples.Count);
Console.WriteLine($"MCMC posterior mean {mean:F3}, spread {sd:F3} (exact answer: mean 0.667, spread 0.131)");
// Kalman filter for one unknown number, measured five times with noise of variance 1
double est = 0.0, variance = 100.0; // a vague starting guess
Console.WriteLine("measurement estimate uncertainty (variance)");
foreach (double m in new[] { 5.1, 4.8, 5.3, 4.9, 5.0 })
{
double gain = variance / (variance + 1.0); // how much to trust the new measurement
est += gain * (m - est); variance = (1 - gain) * variance;
Console.WriteLine($"{m,11:F1} {est,8:F3} {variance,12:F3}");
}Maths behind it
- Conditional probability and Bayes' rule (probability)
- Joint probability by multiplying along a network (probability)
- Ratios of likelihoods (algebra)
- Weighted averages: the Kalman gain (algebra)
Common mistakes
- Ignoring how common the thing is (the prior) when reading a test result.
- Treating the Metropolis samples before warm-up as if they were from the posterior.
- Running a sampler once and trusting it. Check by starting from different places.
- Believing a network's arrows prove causation. They are your assumptions.
- Setting a Kalman filter's noise values at random instead of from what you know of the sensor.
Quick check
A rare disease has a test that is right 90% of the time, yet a positive result means only about a 15% chance of disease. Why?
Show answer
Healthy people vastly outnumber sick people, so even a small false-alarm rate produces more false positives than the true positives from the few sick people.
What does Metropolis sampling need from the model?
Show answer
Only the ratio of likelihoods between two values, which avoids the hard step of normalising the distribution.
In a Kalman filter, what happens to the gain as the uncertainty shrinks?
Show answer
It falls, so each new measurement moves the estimate less.
Why use sampling instead of exact enumeration for a large network?
Show answer
Adding up every combination becomes impossibly large, while sampling gives an approximate answer from many drawn examples.
Completion
Evidence of completion. Bayes' rule worked for a test with its false alarms, a probability of rain given wet grass from a small network, and the estimate and uncertainty after each measurement of a Kalman filter.
Saved in this browser only. Reading and exercise are ticked separately because they are different achievements. A tick records your own work; it is not a test result. See all progress.