Three flips, three heads. Counting says the coin always lands heads. A flat prior says 0.80, and puts the bias between 0.40 and 0.99 with 95% probability. After 200 flips, both say 0.60.
Drag the flips slider and watch the purple curve close in on the pink truth. Change the prior and see what a hunch is worth. Then we build, piece by piece, the likelihood, the posterior, conjugate priors, one best number and a range you can bet on.
You need Bayes' rule and the idea of a probability distribution. We build the rest from zero.
Illustrative coin with true bias 0.60. The 200 flips are one fixed sequence drawn with numpy (seed 433): the first 3 are heads, the first 10 hold 7 heads. Curves and ranges are exact Beta posteriors.
Chapter 0
Hand a coin to twenty people, let each flip it three times, and count how many walk away certain
You flip a coin three times. It lands heads three times. How often does this coin land heads?
The count says 3 out of 3: always. Nobody believes that. Three flips are few, and most coins are close to fair. You held a belief before you flipped, and the count throws it away.
Each row is one person and their three flips. Their report lands on the line below: the share of heads they saw. Press the button for twenty more people. Then turn on the Bayes report.
Illustrative coin with true bias 0.60; flips come from a fixed pseudo-random stream, so the same button presses give the same people. The Bayes report is the posterior mean with a flat prior, (heads + 1) / 5, from Chapter 2.
Here the true coin lands heads 60% of the time. Three heads in a row happen with probability 0.6 × 0.6 × 0.6 = 0.216. So about 1 person in 5 reports "always heads". Three tails happen with probability 0.43 = 0.064, so about 1 in 16 reports "never heads". Both are certain, and both are wrong.
The unknown here is a parameter: a fixed number that sets how the data come out. The coin's chance of heads is its bias, written θ and said "theta". You never see θ. You see flips, and each flip is a noisy clue. Estimation turns the clues into a statement about θ.
Bayesian estimation works in two steps. First, it combines a belief about θ with the data into a whole curve: how plausible each value of θ is now. Then, if you need one number, it reads that number off the curve with a rule that matches what a mistake costs you.
Symptom: an estimate of exactly 0 or exactly 1 from a handful of trials.
Measure: count the trials behind it. Three flips cannot rule out a fair coin.
Fix: put a prior on θ (Chapter 2) and report a range, not one number (Chapter 5).
Chapter 1
Score each candidate bias by how well it explains the flips, multiply by the prior, and rescale
Bayes' rule weighed two hypotheses, sick or healthy. Here the hypotheses are every bias from 0 to 1. Each one needs two scores: how well it explains the flips, and how plausible it was before them.
Start with the first score. Say you flipped n times and saw k heads. A coin with bias θ lands heads with chance θ and tails with chance 1 − θ. The flips do not affect each other, so the chances multiply.
p of D given theta equals theta to the k, times one minus theta to the n minus k.
Pick a candidate θ. Multiply θ once for each head and 1 − θ once for each tail. Do it for every θ from 0 to 1. The product is high where θ explains the flips well.
7 heads and 3 tails. For θ = 0.7: 0.77 × 0.33 = 0.0022. For θ = 0.5: 0.510 = 0.00098. The flips favour 0.7 over 0.5 by a factor of 2.3.
Now the second score. Call your belief about θ before the flips the prior, p(θ). Bayes' rule multiplies the two scores and rescales the result so it adds up to 1.
p of theta given D equals p of D given theta, times p of theta, divided by p of D.
For every candidate θ, multiply its prior p(θ) by its likelihood p(D | θ). Add all the products to get p(D). Divide each product by p(D). The result is the posterior p(θ | D).
Three candidate coins, θ = 0.3, 0.5 and 0.7, each with prior 1/3. After 7 heads and 3 tails the likelihoods are 0.000075, 0.00098 and 0.0022. The equal priors cancel, the likelihoods sum to 0.0033, and the posteriors are 0.02, 0.30 and 0.68.
Each bar is one candidate bias, 0.00 to 1.00 in steps of 0.05. Step through prior, times likelihood, then rescale. Add heads or tails and watch the purple bars move.
Exact arithmetic on a grid of 21 values. The fair hunch is a prior shaped like θ4(1 − θ)4, the Beta(5, 5) of Chapter 2.
Symptom: with 2,000 flips, every posterior value comes out 0 or NaN.
Measure: print the raw likelihood. 0.52000 is about 10−602, far below the smallest number a double can hold (about 10−308). It rounds to 0.
Fix: work in logs. Compute k log θ + (n − k) log(1 − θ) + log p(θ), subtract the largest value, then exponentiate and rescale.
Chapter 2
Pick a prior with the likelihood's shape, and the update becomes adding heads and tails to two counters
The grid works for one parameter. For a coin there is a shortcut that needs no grid. It comes from the shape of the likelihood: θ to some power times 1 − θ to some power.
The Beta distribution Beta(α, β) is a curve on 0 to 1 with that same shape: its height is proportional to θα − 1(1 − θ)β − 1. Multiply it by the likelihood and the powers add.
Beta of alpha and beta becomes Beta of alpha plus k, and beta plus n minus k.
Add the heads k to α. Add the tails n − k to β. That is the whole update. The posterior mean is the head counter over both counters: (α + k) / (α + β + n).
Flat prior Beta(1, 1), then 7 heads and 3 tails: Beta(8, 4), mean 8/12 = 0.667. A fair hunch Beta(5, 5) with the same flips: Beta(12, 8), mean 12/20 = 0.600. That is halfway between the prior's 0.5 and the data's 0.7, because the prior's 10 counts weigh as much as the 10 real flips.
A prior that stays in its family after the update is a conjugate prior. The counters α and β are its pseudo-counts. The flat prior Beta(1, 1) adds one head and one tail, so its mean is (k + 1) / (n + 2). This is Laplace's rule of succession. After three heads it says 4/5 = 0.80, not 1.
Left: two counters. Warm pebbles are the prior's pseudo-counts, blue pebbles are real flips. Right: the posterior curve they make. Choose a prior, then add flips.
Exact Beta curves. "Flip the 0.6 coin" deals the next ten flips of the hero's fixed sequence.
| Data | Conjugate prior | Posterior | Example |
|---|---|---|---|
| Heads and tails | Beta(α, β) | Beta(α + k, β + n − k) | a coin, a click rate |
| Readings with known noise | Normal | Normal (Chapter 6) | a thermometer |
| Counts per interval | Gamma(a, b) | Gamma(a + total count, b + n intervals) | calls per hour |
| One of several categories | Dirichlet(α1, …) | Dirichlet(αi + counti) | the faces of a die |
Symptom: 100 flips barely move the estimate.
Measure: compare α + β with n. Beta(50, 50) is worth 100 flips, so 100 real flips only pull halfway.
Fix: set α + β to the number of flips your belief is worth.
Chapter 3
Take the top of the likelihood or the top of the posterior, and see the prior act as extra flips
Often you want one number, fast. The quickest choice is the top of a curve. You have two curves, so you have two tops.
The top of the likelihood is the maximum likelihood estimate, the MLE. To find it, take the log (the top does not move), set the slope to zero and solve.
The MLE is the count. The top of the posterior is the maximum a posteriori estimate, the MAP. With a Beta(α, β) prior the posterior is Beta(α + k, β + n − k), and the same steps give its top.
theta-hat MAP equals k plus alpha minus one, over n plus alpha minus one plus beta minus one.
Add α − 1 imagined heads to your k heads, and β − 1 imagined tails to your tails. Divide the heads by the total. With a flat prior, α = β = 1, the prior adds nothing, and the MAP equals the MLE k / n.
3 heads in 3 flips: the MLE is 3/3 = 1.00. With a Beta(2, 2) prior, the MAP is (3 + 1) / (3 + 2) = 0.80. With Beta(5, 5) and 7 heads in 10, the MAP is 11/18 = 0.611, against an MLE of 0.70.
Blue is the likelihood, with its top, the MLE. Purple is the posterior, with its top, the MAP. Raise the prior strength and watch the purple peak lean toward 0.5.
Exact formulas: MLE = k / n, MAP = (k + s − 1) / (n + 2s − 2). We rescale the likelihood to area 1 so both curves share an axis.
In machine learning this pull toward the prior is regularization. Put a Gaussian prior on a model's weights, and MAP becomes least squares plus a penalty on the squared weights. That is the L2 or ridge penalty (Bishop, Pattern Recognition and Machine Learning, Section 3.3). With Gaussian noise the MLE becomes weighted least squares, as in VNAV 9. Add the prior as one more reading and the same solver gives the MAP, as in Uncertainty and Least Squares.
Symptom: an event never seen gets probability 0, and the model calls it impossible.
Measure: look for zero counts. 0 heads in 4 flips gives an MLE of 0/4 = 0.
Fix: use a prior with α and β above 1. Beta(2, 2) gives a MAP of 1/6 = 0.17.
Chapter 4
Say what a miss costs, and the best single guess becomes the mean, the median or the mode
The posterior is a curve. A decision needs one number. Which number is best depends on what a miss costs you.
A loss function gives the cost of guessing a when the truth is θ. You do not know θ, so you average the cost over the posterior. The best guess makes that average smallest. Three losses give three answers:
Why the mean for squared loss? Call your guess a, the posterior mean θ̄ ("theta-bar"), and the spread of the curve its variance, Var(θ | D).
The expected value of theta minus a, squared, given D, equals the variance of theta given D, plus theta-bar minus a, squared.
The average squared miss has two parts: the spread of the curve, and how far a sits from θ̄. Only the second part depends on a. Set a = θ̄ and it is 0. So the mean gives the minimum mean squared error: it is the MMSE estimate.
Posterior Beta(3, 2): mean 0.600, variance 0.040. Guess the mean: 0.040. Guess the mode, 0.667: 0.040 + 0.0672 = 0.044. Guess 0.70: 0.040 + 0.102 = 0.050.
Top: the posterior with its mean, median and mode. Bottom: the average loss of every possible guess. Drag your guess (yellow) and find the floor of the curve.
Expected losses computed on a grid of 1,000 points. The hit-or-miss window is ±0.05; with a narrower window its best guess moves closer to the mode.
For Beta(3, 2) the three answers are 0.667 (mode), 0.614 (median) and 0.600 (mean). The long left tail pulls the mean down the most. For a symmetric curve, such as a Gaussian, all three are the same number.
Symptom: the reported estimate sits where the posterior is low, such as a mean between two humps.
Measure: plot the posterior before you report one number from it.
Fix: report the curve or a range, and pick the point estimate by the loss you face.
Chapter 5
Cut 2.5% of the posterior from each end, watch the range shrink with data, then check how often it catches the truth
One number hides how sure you are. "0.67 from 10 flips" and "0.67 from 1,000 flips" are different claims. Report a range as well.
A 95% credible interval is a range that holds 95% of the posterior's area. The simplest kind cuts 2.5% of the area off each end. You read its ends off the posterior's cumulative curve. For a quick check, use the curve's standard deviation (sd), its typical spread. Write the posterior as Beta(α′, β′), so α′ = α + k and β′ = β + n − k, with mean θ̄.
The s-d of theta given D equals the square root of theta-bar times one minus theta-bar, over alpha-prime plus beta-prime plus one.
Multiply θ̄ by 1 − θ̄. Divide by the total count α′ + β′ plus 1. Take the square root. When the curve looks like a bell, the 95% range is about θ̄ ± 1.96 sd. The total count grows with n, so four times the flips halve the range.
Flat prior, 7 heads in 10: Beta(8, 4), θ̄ = 0.667, sd = √(0.667 × 0.333 / 13) = 0.131. The bell rule gives 0.41 to 0.92; the exact ends are 0.39 to 0.89. At 63 heads in 100, Beta(64, 38): bell rule 0.534 to 0.721, exact 0.532 to 0.718.
The bell rule misses at 10 flips because Beta(8, 4) leans to one side. Use the exact ends; the sd tells you how fast the range shrinks.
Top: the posterior after n flips of the 0.6 coin, flat prior, with its 95% band. Bottom: 40 coins with biases drawn from the flat prior, each flipped n times. Each line is a coin's 95% range: green if it caught that coin's true bias (pink dot), red if not.
Exact Beta quantiles. The coins come from a fixed pseudo-random stream; the read-out counts 1,000 of them, the picture shows the first 40.
How often does a 95% range catch the truth? If the true biases are spread like the prior, it catches it 95% of the time. A seeded run of 10,000 coins with 10 flips each gave 95.3%. For one fixed coin of bias 0.6 with a flat prior, exact sums give 98.2% at 10 flips and 94.8% at 100.
Symptom: tight ranges that keep missing new data.
Measure: hold some data back and count how often it lands inside your 95% ranges. A wrong prior Beta(4, 16), centred at 0.2, catches the true 0.6 only 4.6% of the time at 10 flips and 69.7% at 100.
Fix: check the prior against past data, or weaken it so the data can win.
Chapter 6
Fuse a belief with thermometer readings, weighting each by how sharp it is
Now a sensor. A thermometer reads the room temperature θ with noise. Before you look, you think θ is about μ0, give or take σ0. You take n readings, each with noise sd σ, and their average is x̄.
The prior and the noise are both Gaussian bells, so the posterior is a Gaussian too: the Normal row of the conjugate table. The trick is to work with precision, which is 1 over the variance. A sharp bell has a high precision.
One over sigma-n squared equals one over sigma-zero squared, plus n over sigma squared. Mu-n equals sigma-n squared times, mu-zero over sigma-zero squared, plus n x-bar over sigma squared.
Add the precisions: the prior's, plus one for each reading. Then average the prior mean μ0 and the reading average x̄, each weighted by its precision. The sharper source gets the bigger say.
A vague prior: μ0 = 0, σ0 = 10, and 5 readings with σ = 1 averaging x̄ = 3. Precision 0.01 + 5 = 5.01, so σn = 0.447 and μn = 15 / 5.01 = 2.994. A firm prior, σ0 = 0.5: precision 4 + 5 = 9, σn = 0.333, μn = 15 / 9 = 1.667. The prior holds back almost half the way.
Warm is your prior, centred at 0. Blue is what the readings say, centred at their average 3.0. Purple is the posterior. The bar below splits the weight between prior and data.
Illustrative: the reading average is fixed at 3.0 and the true temperature at 3.0. The prior sd slider runs from 0.1 to 10 on a log scale. Exact Gaussian formulas.
The purple bell is narrower than both the warm and the blue ones. Precisions add, so two independent sources leave you surer than either alone.
Symptom: a posterior that is confident and far from fresh readings.
Measure: compare the spread of the readings with the σ you assumed. If they scatter by 1 but you set σ = 0.1, you claim each reading is worth 100 real ones.
Fix: estimate σ from repeated readings of a fixed quantity before you fuse.
Chapter 7
Update after every reading, get the batch answer exactly, and watch two different priors meet
Readings often arrive one at a time: a thermometer every second, a robot's range sensor every scan. You do not need to keep them all. After each reading, the posterior becomes the prior for the next one.
Call the current belief's mean μ and its variance s2. A new reading x arrives with noise sd σ. Chapter 6 with n = 1, rearranged, gives the update.
Mu-new equals mu plus K times x minus mu, where K equals s squared over s squared plus sigma squared.
Measure the surprise x − μ. Move the fraction K of the way toward the reading. K is a trust slider: near 1 when your belief is vague, near 0 when the sensor is noisy. Then shrink the variance s2 by the factor 1 − K.
Prior mean 0, sd 2 (s2 = 4), noise σ = 1, readings 2.5, 3.1, 2.8. First K = 4/5 = 0.80: μ = 2.000, sd 0.894. Then K = 0.444: μ = 2.489, sd 0.667. Then K = 0.308: μ = 2.585, sd 0.555. One batch update with all three gives 2.585 and 0.555: the same.
Sequential and batch agree exactly, because each step multiplies in one more likelihood and multiplication does not care about order. Add a motion step between readings and this update is the Kalman filter; in general form it is the Bayes filter.
Person A starts sure the temperature is 0 (sd 1). Person B starts sure it is 6 (sd 1). Both see the same readings (blue dots, noise sd 1). The purple lines are their posterior means; the yellow bar is the gap between them.
Illustrative stream: 60 readings of a true value 3.0 with noise sd 1, drawn once with numpy (seed 5) and rounded to 0.01. Both people use the update above.
With prior sd equal to the noise sd, each person's mean after n readings is (μ0 + n x̄) / (n + 1). The gap between them is 6 / (n + 1): 1.0 after 5 readings, 0.1 after 59. This is the prior washing out: enough data makes any two reasonable priors agree.
Symptom: the belief grows too confident and stops following the readings.
Measure: count updates against readings. A message sent twice gets applied twice, and each copy shrinks s2.
Fix: give each reading an ID and apply each ID once.
Chapter 8
Pick a true bias and a prior, then read off every estimator's average error and the interval's hit rate at every sample size
Everything so far in one race. You choose the coin's true bias and a prior. The device averages each estimator over every possible run of n flips, exactly: the MLE, the posterior mean and the MAP. It also gives how often the 95% range catches the truth.
Top: average squared error against the number of flips, both on log scales. Blue is the MLE, solid purple the posterior mean, dashed purple the MAP. Bottom: how often the 95% range catches the truth; yellow marks 95%. Drag the flips marker.
Exact sums over the binomial distribution of k, no sampling. The hit rate counts the runs whose posterior puts between 2.5% and 97.5% of its area below the true bias. It zigzags because the number of heads is a whole number.
Three results to find. With the true bias 0.6 and 10 flips, the good hunch has an average squared error of 0.0027, nine times smaller than the MLE's 0.0240. The wrong hunch has 0.0738, three times larger, and its range catches the truth only 4.6% of the time. At 200 flips the wrong hunch still costs 1.9 times the MLE's error, and its hit rate is 82.5%.
The flat prior is not free either. Move the true bias to 0.95: at 10 flips the posterior mean's error is 0.0089 and the MLE's is 0.0048. The prior's pull toward 0.5 now points the wrong way.
Symptom: a model that is confident, and wrong in the same direction on every batch.
Measure: compare the posterior mean with the plain count on a large batch. A steady gap points at the prior.
Fix: weaken the prior, so its pseudo-count is small next to n, or rebuild it from relevant past data.
Chapter 9
Keep the failure table, the numbers and the code in one place
Bayesian estimation turns a prior and data into a posterior curve over the unknown. For a coin the curve is a Beta, and the update adds heads and tails to two counters. For a Gaussian sensor, precisions add and means average by precision. One number comes from the curve by your loss: the mean for squared error, the median for absolute error, the mode for hit or miss. Report a range with it, and remember the range is only as honest as the prior.
| Failure | Symptom | Check that names it |
|---|---|---|
| Certainty from a few trials | an estimate of exactly 0 or 1 | how many trials? any zero count? |
| Likelihood underflow | posterior all 0 or NaN | compute in logs, subtract the max |
| Prior too strong | data barely move the estimate | compare α + β with n |
| Wrong prior | steady gap to the count; ranges miss | held-out data inside the 95% range? |
| Wrong point estimate | estimate where the posterior is low | plot the curve; match the estimate to the loss |
| Noise set too small | confident and far from new readings | measured spread of readings against σ |
| Double counting | belief shrinks faster than data arrive | one update per reading ID |
python import numpy as np from scipy import stats def beta_update(a, b, heads, tails): """Conjugate update: add the counts to the prior's pseudo-counts.""" return a + heads, b + tails def estimates(a, b): """Point estimates and the 95% equal-tailed range of Beta(a, b).""" d = stats.beta(a, b) mode = (a - 1) / (a + b - 2) if a > 1 and b > 1 else None return dict(mean=a / (a + b), median=d.median(), mode=mode, lo=d.ppf(0.025), hi=d.ppf(0.975)) def gauss_update(mu, var, x, noise_var): """One reading: move a fraction K toward it, shrink the variance.""" K = var / (var + noise_var) return mu + K * (x - mu), (1 - K) * var a, b = beta_update(1, 1, 7, 3) print(a, b, estimates(a, b)) # 8 4: mean 0.667, median 0.676, mode 0.700, range 0.390 to 0.891 print(estimates(3, 2)) # mean 0.600, median 0.614, mode 0.667 mu, var = 0.0, 4.0 for x in [2.5, 3.1, 2.8]: mu, var = gauss_update(mu, var, x, 1.0) print(mu, np.sqrt(var)) # 2.585 0.555, the same as one batch update
We ran every line above with numpy and scipy; the comments are its output, rounded.
| Number | Value | Where it comes from |
|---|---|---|
| Three heads from a 0.6 coin | 0.216 | 0.6 × 0.6 × 0.6 |
| Flat prior after 3 heads: mean, range | 0.80, 0.40 to 0.99 | Beta(4, 1) |
| Flat prior after 7 heads, 3 tails | 0.667 | Beta(8, 4): 8 / 12 |
| Fair hunch after 7 heads, 3 tails | 0.600 | Beta(12, 8): 12 / 20 |
| MAP, Beta(2, 2), 3 heads in 3 | 0.80 | (3 + 1) / (3 + 2) |
| Beta(3, 2): mode, median, mean | 0.667, 0.614, 0.600 | 2/3; numeric; 3/5 |
| Thermometer, vague prior | 2.994 ± 0.447 | 15 / 5.01 |
| Thermometer, firm prior | 1.667 ± 0.333 | 15 / 9 |
| Wrong hunch, 10 flips: error, hit rate | 0.0738, 4.6% | exact binomial sums |
Where it sits. Run the update in a loop with a motion step and you have the Bayes filter and, with Gaussians, the Kalman filter. Take the log of a Gaussian posterior and the MAP becomes least squares, as in VNAV 9 and, on rotations, VNAV 10. Most models have no conjugate prior; then you sample the posterior with Markov chain Monte Carlo or fit an approximation with variational inference. Sampling a Beta posterior per option and picking the best draw is Thompson sampling, in Bandits and Preference Learning.
Now teach it: press Present or Teach and explain why three heads do not make the coin certain. Then go back to the coin at the top and pick the stubborn prior. Predict how many flips the purple curve needs to reach the pink line.