A test that is right 80% of the time says positive. If 1 in 5 people have the disease, you have it with probability 50%. If 1 in 1,000 do, 0.4%.
Pick how common the disease is, then set how accurate the test is. Watch which squares light up and read the bar: the pink share of the positives is the chance a positive person is sick. Then we build, piece by piece, conditional probability, the rule, the odds form and evidence that stacks.
You need fractions and the idea that a probability is a number from 0 to 1. We build the rest from zero.
Illustrative test: "accuracy" means the same rate both ways, sick people test positive and healthy people test negative at that rate. The squares show the expected counts for 1,000 people, rounded; the read-out counts 10,000 and the bar uses the exact posterior.
Chapter 0
Guess what a positive test is worth, then count the crowd and see where the guess went wrong
You take a screening test. When a person has the disease, it says positive 80% of the time. When a person is healthy, it says negative 80% of the time. Your result is positive. What is the chance you have the disease?
Most people answer 80%. A 1978 study at Harvard Medical School gave 60 doctors and students a harder version. The disease hit 1 in 1,000 people, and the test had 5% false positives. Only 11 gave the right answer, about 2%. The most common answer was 95%.
100 people, 20 of them sick (pink). Set your guess for the chance that a positive person is sick. Then run the test on everyone and count who lights up.
Illustrative crowd with the exact expected counts: 20 sick, 80 healthy, an 80/80 test.
Count it. The test catches 80% of the 20 sick people: 16 true positives. It also flags 20% of the 80 healthy people: 16 false positives. So 32 people test positive, and 16 of them are sick. A positive means 16 out of 32, which is 50%.
The gut answer ignores how common the disease is. That number is the base rate, also called the prevalence. The 80 healthy people outnumber the 20 sick ones, so their small false-positive rate makes as many positives as the sick do. Ignoring the base rate is the base-rate trap. Thomas Bayes's rule, published in 1763, is the fix.
Symptom: a report calls a positive "80% likely" because the test is "80% accurate".
Measure: ask what share of all positives is sick. Count true and false positives in a crowd of 100.
Fix: fold in the base rate. Chapter 3 shows how, step by step.
Chapter 1
Change the room you count in, and watch the same crowd give 20%, 80% and 50%
The trap has a cause. "The chance a sick person tests positive" and "the chance a positive person is sick" sound alike. They count different rooms.
A conditional probability answers "if I already know B, how likely is A?" We write it P(A | B) and say "the probability of A given B". The bar means "given". To compute it, throw out everyone who is not B, and count A inside the room that is left.
The crowd from Chapter 0, after the test. Pick a room. Everyone outside it fades. The fraction is the count inside the room over the size of the room.
Illustrative crowd: 20 sick, 16 of them positive; 80 healthy, 16 of them positive.
In the room of the sick, 16 of 20 test positive: P(+ | sick) = 0.8. In the room of the positives, 16 of 32 are sick: P(sick | +) = 0.5. Same 16 people on top, different room below.
Write the count with probabilities. Call the share of everyone who is both A and B P(A and B), the joint probability. Call the share who are B P(B).
P of A given B equals P of A and B, divided by P of B.
Take the share who are both A and B. Divide by the share who are B. Dividing both counts by the crowd size does not change their ratio, so this is the head count inside the B room.
A is "sick" and B is "positive". P(sick and +) = 16/100 = 0.16 and P(+) = 32/100 = 0.32, so P(sick | +) = 0.16 / 0.32 = 0.5. Swap the roles: P(+ | sick) = 0.16 / 0.20 = 0.8.
Multiply both sides by P(B) and you get the multiplication rule: P(A and B) = P(A | B) × P(B). To be in both groups, first be in B, then be A inside that room. Chapter 2 uses it twice.
Symptom: a "given" probability comes out tiny, like 0.16 for P(sick | +).
Measure: check the denominator. Dividing by the whole crowd gives the joint, not the conditional.
Fix: divide by the size of the room you condition on: 32 positives, not 100 people.
Chapter 2
Derive the rule from the joint in three lines, then reweight two hypotheses and normalise
You can measure P(positive | sick): test people you know are sick and count. You want P(sick | positive). The arrow points the wrong way. Bayes' rule turns it around, and it falls out of Chapter 1.
Call the hidden cause Y (sick) and the evidence you see X (positive). Write the joint P(X and Y) with the multiplication rule, once each way round. Both lines describe the same group of people, so the right sides are equal. Divide by P(X).
P of Y given X equals P of X given Y, times P of Y, divided by P of X.
Start from the prior P(Y). Multiply by the likelihood P(X | Y), how well Y predicted what you saw. Divide by the evidence P(X) so the beliefs over all causes add up to 1. The result is the posterior P(Y | X).
A bag holds a fair coin and a two-headed coin. You pick one at random and flip heads. Prior P(two-headed) = 0.5, likelihood P(heads | two-headed) = 1.0, evidence P(heads) = 1.0 × 0.5 + 0.5 × 0.5 = 0.75. Posterior = 0.5 / 0.75 = 0.667. One head moves you from 50% to 67%, not to certainty, because the fair coin lands heads too.
The rule does two things. It reweights each hypothesis by its likelihood. Then it rescales all of them so they sum to 1. People write the first part as "posterior is proportional to likelihood times prior".
Two hypotheses, three steps. We multiply the prior (warm) by each likelihood (blue). The products (faint purple) no longer sum to 1, so we rescale them into the posterior (purple). Pick a preset or drag the knobs.
Exact arithmetic on two hypotheses. If both likelihoods are 0, the evidence cannot happen under either hypothesis. Then no posterior exists, and the device says so.
Symptom: posteriors that add up to 0.4, or to 1.3.
Measure: sum the posterior over every hypothesis. It must be exactly 1.
Fix: you skipped the divide. Compute P(X) as the sum of likelihood × prior over all hypotheses, and divide by it.
Chapter 3
Add up every way a positive can happen, then divide out the true positives
Two test words first. Sensitivity is the chance a sick person tests positive, P(+ | D), where D means "has the disease". Specificity is the chance a healthy person tests negative, P(− | not D). "80% accurate" means both are 0.8. The false-positive rate is 1 minus the specificity: 0.2.
Bayes' rule needs P(+), the evidence. Nobody hands it to you. A positive happens two ways: a sick person tests positive, or a healthy person does. Add the two.
P of plus equals P of plus given D times P of D, plus P of plus given not D times P of not D.
For each hypothesis, multiply its prior by its chance of a positive. Add the products. This is the law of total probability, and its first term is the numerator of Bayes' rule.
P(+) = 0.8 × 0.2 + 0.2 × 0.8 = 0.16 + 0.16 = 0.32. Then P(D | +) = 0.16 / 0.32 = 0.50. The first 0.16 is the 16 true positives in a crowd of 100; the second is the 16 false positives.
Draw it as a square of area 1. Cut it at the prior: sick on the left, healthy on the right. In each column, shade the share that tests positive. The posterior is the sick shaded area over all the shaded area.
Left column: the sick (pink). Right column: the healthy. The blue band in each is who tests positive. The bar on the right is the positive room, split into true and false positives. Drag the three knobs.
Exact areas. Areas are shares of everyone, so 0.16 is 16 people in 100.
The answer is 0.5 because the two shaded areas tie. That happens whenever sensitivity × prior equals false-positive rate × (1 − prior). A prior of 0.1 with a 90/90 test ties too: 0.09 against 0.09. Raise the specificity to 0.99 at a prior of 0.2 and the false-positive area shrinks to 0.008: the posterior jumps to 0.95.
Symptom: the posterior comes out above 1, or the false positives look huge.
Measure: check the second term of P(+). It must use 1 − specificity, not the specificity.
Fix: with specificity 0.8 the false-positive rate is 0.2. Writing 0.8 × 0.8 = 0.64 instead of 0.2 × 0.8 = 0.16 drops the posterior from 0.50 to 0.20.
Chapter 4
Hold the test fixed, make the disease rarer, and watch what a positive is worth fall away
Keep the 80/80 test and make the disease rarer. At a prior of 0.20 the posterior is 0.50. At 0.05 the true positives are 0.8 × 0.05 = 0.040 and the false positives 0.2 × 0.95 = 0.190, so the posterior is 0.040 / 0.230 = 0.174. At 0.01 it is 0.008 / 0.206 = 0.039.
The true positives shrink with the prior. The false positives hardly move, because they come from the healthy, who are now 99% of everyone. At 1%, a positive is 25 times more likely to be a false alarm than a real case.
The purple curve is the posterior after one positive. The yellow diagonal is "posterior = prior": a test that tells you nothing. The prior axis is logarithmic. Drag the prior, then the accuracy.
Exact posterior; accuracy means sensitivity and specificity are equal. Prior from 0.1% to 50% on a log scale.
A better test helps, slowly. At a prior of 0.1%, a 95/95 test gives 1.9% and a 99/99 test gives 9.0%. No accuracy short of perfect makes one positive trustworthy for a truly rare condition. Doctors respond in two ways: they test a higher-risk group, which raises the prior, or they confirm with a second, different test (Chapter 6).
Symptom: a screen of the whole population floods the clinic with positives, and most turn out healthy.
Measure: the share of positives confirmed sick. At a 1% prior with an 80/80 test it is 3.9%.
Fix: screen a group with a higher prior, or confirm every positive with a second, independent test.
Chapter 5
Rewrite the rule in odds, and see one positive as the same fixed push from any start
Why does the curve in Chapter 4 fall so fast? Rewrite belief as odds: the chance it is true over the chance it is false. A prior of 0.2 is odds of 0.2 / 0.8 = 0.25, said "1 to 4".
Write Bayes' rule once for D and once for not D, then divide one by the other. The evidence P(+) appears in both and cancels. What is left is three numbers. Call the ratio of the two likelihoods the likelihood ratio, LR.
O-post equals LR times O-prior, where LR is P of plus given D over P of plus given not D.
Turn the prior into odds O-prior. Multiply by the likelihood ratio LR. To get a probability back, compute O-post over 1 plus O-post.
An 80/80 test has LR = 0.8 / 0.2 = 4. Prior 0.2: odds 0.25, times 4 is 1, which is 1 / (1 + 1) = 0.50. Prior 0.01: odds 1/99 = 0.0101, times 4 is 0.0404, which is 0.039. Both match Chapter 4.
A positive from this test always multiplies the odds by 4. From 1 to 4 that lands at 1 to 1. From 1 to 99 it lands at 4 to 99. On a log scale, multiplying is adding, so the same evidence is the same length of arrow wherever it starts.
The ruler is in odds on a log scale, with probabilities written underneath. The warm mark is the prior. The blue arrow is one positive: its length is the log of LR. The purple mark is where you land. Drag the prior and watch the arrow keep its length.
Exact odds. A negative has LR = (1 − sensitivity) / specificity, 0.25 for the 80/80 test: the same length of arrow, pointing the other way.
Symptom: after two positives the belief goes above 1, or barely moves.
Measure: check whether the update adds the likelihood ratio or multiplies by it.
Fix: multiply odds, never probabilities. 0.2 × 4 = 0.8 is wrong; 0.25 × 4 = 1 in odds is 0.5.
Chapter 6
Chain test results one after another, and see what happens when the tests share their mistakes
One positive left you at a coin flip. So take a second test. After the first, your belief is 0.50: that is the prior for the second. Run Bayes again: 0.8 × 0.5 = 0.40 over 0.40 + 0.2 × 0.5 = 0.50, which gives 0.80.
In odds it is one line. Start at 0.25. Each positive multiplies by 4, so two make 16: 0.25 × 16 = 4, which is 4 / 5 = 0.80. A negative multiplies by 0.25. One positive and one negative cancel and leave you at the prior, 0.20.
O-n equals O-zero times L-R-one times L-R-two, and so on up to L-R-n.
Start from the prior odds O-zero. Multiply by each result's likelihood ratio, in any order. The product is O-n. This holds only if the results are conditionally independent: once you know whether the person is sick, one result tells you nothing about the next.
Results +, +: O-two = 0.25 × 4 × 4 = 4, a probability of 0.80. Results −, −: 0.25 × 0.25 × 0.25 = 0.0156, a probability of 1.5%.
Independence is the catch. Suppose the second test runs on the same blood sample in the same lab, so half the time it repeats the first result. Then two positives are worth less than two separate tests. With that repeat chance of 0.5, the true posterior after +, + is 0.60, not 0.80.
Add results with the buttons. The purple steps are the correct belief. Switch to the shared-sample lab: the red dashed line is the naive update that multiplies as if the tests were independent.
Illustrative 80/80 test and a 20% prior. In the same-sample mode, each test after the first copies the previous result with probability 0.5. Otherwise it is a fresh test. The correct belief uses that model exactly.
Symptom: a repeated test makes the team near certain, and the follow-up proves them wrong.
Measure: ask whether the second result could share the first one's error: same sample, same lab, same sensor, same blind spot.
Fix: confirm with a test that fails for a different reason. If you cannot, count the repeat as less than a full likelihood ratio.
Chapter 7
Weigh ten places a robot could be by one noisy range, and keep every candidate the reading allows
A robot parks in one of ten alcoves of different depths. Its range sensor reads 2.3 m. Where is it?
Three alcoves are 2.2, 2.3 and 2.4 m deep, and the sensor noise is 0.15 m, so the reading cannot tell them apart. Snapping to the nearest depth claims a certainty the reading lacks.
Number the alcoves i = 1 to 10. Call the reading z. Call the belief in alcove i P(hi). Call how likely the reading is from alcove i P(z | hi): for bell-shaped noise it peaks at the alcove's depth.
P of h-i given z equals P of z given h-i times P of h-i, divided by the sum over j of P of z given h-j times P of h-j.
For each alcove, multiply its prior by its likelihood. Add all ten products. Divide each product by that total. The ten posteriors now sum to 1.
Equal priors, reading 2.3 m. The likelihoods are 1.00 for the 2.3 m alcove, 0.80 for 2.2 and 2.4 m, and 0.14 for 2.6 m. The rest are near 0, and the sum is 2.74. Posteriors: 1.00 / 2.74 = 0.36, then 0.29, 0.29 and 0.05.
Ten alcoves sorted by number, each labelled with its depth. Warm outlines: the prior. Blue dots: the likelihood of the reading. Purple bars: the posterior. The pink mark is where the robot is. Drag the reading, then try the prior that favours the charger.
Illustrative depths in metres: 1.5, 2.3, 3.0, 2.4, 1.8, 2.9, 2.2, 3.4, 1.6, 2.6. Gaussian sensor noise, standard deviation 0.15 m. The robot is in alcove 2.
With the charger prior, alcove 10 starts at 0.55. The reading fits it poorly, a likelihood of 0.14. It still ends on top at 0.36, ahead of the true alcove at 0.24. One reading does not overturn a strong prior; more readings as the robot moves do. That loop is the Bayes filter.
Hypotheses can also form a continuum, like a coin's unknown bias. A Beta prior keeps two counts: each head adds 1 to the first, each tail 1 to the second. Start at 1 and 1, see 7 heads and 3 tails: 8 and 4, mean 8 / 12 = 0.67. A prior that keeps its form after the update is a conjugate prior; Bayes Estimation builds it out.
Symptom: the robot jumps to the wrong alcove and stays there, sure of itself.
Measure: look at the posterior before the snap. Three bars near 0.3 mean an ambiguous reading.
Fix: keep the whole posterior and update it with the next reading.
Chapter 8
Score an email by multiplying one likelihood ratio per word, and stop one unseen word from deciding everything
An email arrives. The hypothesis is "spam". The evidence is the words. Each word gets a likelihood ratio from training mail: how much more often it appears in spam than in normal mail, called ham. Multiply the ratios onto the prior odds, as in Chapter 6.
This is a naive Bayes classifier. "Naive" means it treats the words as conditionally independent given the class. They are not: "wire" and "transfer" travel together.
The likelihoods come from counts. Suppose training holds 500 spam and 1,000 ham emails. "free" appears in 300 spam and 50 ham: 0.60 against 0.05, LR = 12. With a 10% spam prior, one "free" gives odds 0.111 × 12 = 1.33, a probability of 0.57.
Now a word appears in 30 spam emails and no ham. Its ham rate is 0, so its likelihood ratio is infinite, and one such word makes any email certain spam. The fix adds one imagined email to each count. Call the number of spam emails that contain word w nw, and the number of spam emails N.
P of w given spam equals n-w plus one, over N plus two.
Count the spam emails with the word, n-w, and add 1. Divide by the number of spam emails N plus 2. Do the same for ham. No rate is ever 0 or 1, so no single word can decide the email. This is Laplace smoothing.
The word is in 30 of 500 spam and 0 of 1,000 ham. Spam: (30 + 1) / 502 = 0.0618. Ham: (0 + 1) / 1,002 = 0.0010. So LR = 62, large but finite. An email with "meeting", "lunch" and this word scores 100% spam without smoothing, 18% with it.
Toggle the words in the email. Each word is a blue push on the log-odds ruler, right toward spam, left toward ham. The warm mark is the prior; purple is the verdict. Turn smoothing off and add "crypto".
Illustrative training set of 500 spam and 1,000 ham emails. Spam and ham counts: free 300 and 50; unsubscribe 200 and 80; invoice 50 and 50; meeting 10 and 100; lunch 5 and 80; crypto 30 and 0. This toy multiplies only the words present; a full model also counts the words that are absent.
Symptom: one rare word flips an email to 100% spam, or to 0%, whatever the rest says.
Measure: look for a word whose count is 0 in one class: its likelihood ratio is 0 or infinite.
Fix: add-one smoothing on every count, and sum log ratios instead of multiplying, so small numbers do not underflow.
Chapter 9
Choose who to test, how good the first test is, and how to confirm, then count every outcome in 100,000 people
Everything so far, in one plan. You run a programme for 100,000 people. A cheap first test screens everyone. A second, better test confirms the positives. You choose the population, the first test's accuracy and the confirmation.
Each row is a stage. Pink is people who are sick, blue is healthy people still flagged. The purple number is the share of flagged people who are sick. Change one thing at a time.
Illustrative programme with expected counts, not a real screening policy. The first test has equal sensitivity and specificity. The confirmation has sensitivity 0.95 and specificity 0.99; in the same-sample mode it repeats the first result with probability 0.5.
The defaults: 100,000 people, 500 sick, a 90/90 first test. It flags 450 sick and 9,950 healthy people, so a first positive means 4.3%. The independent confirmation keeps 427.5 sick and 99.5 healthy: 81%. It misses 72.5 of the 500 along the way, the price of two tests that must both say yes.
Switch the confirmation to the same sample and the false positives climb to 5,025: 8.0%. Move to the at-risk group and a first positive means 32%, a confirmed one 98%.
Symptom: the confirmed positives are still mostly healthy.
Measure: compute the share at each stage. If the second stage barely moves it, the two tests share their errors.
Fix: confirm with a test that works by a different mechanism, or screen a group with a higher prior.
Chapter 10
Keep the failure table, the numbers and the code in one place
A probability is always counted in some room. Bayes' rule changes the room: multiply the prior by the likelihood, divide by the evidence. A rare cause stays unlikely after one piece of evidence, because the evidence multiplies the odds, it does not replace them. Chain evidence only when the pieces fail independently, and never let one unseen count decide.
| Failure | Symptom | Check that names it |
|---|---|---|
| Base-rate trap | "80% accurate" reported as 80% sure | count true and false positives in 100 people |
| Flipped conditional | P(+ | D) quoted as P(D | +) | which room is the denominator? |
| Joint for conditional | a "given" that comes out tiny | divided by everyone instead of the room |
| Missing normaliser | posteriors do not sum to 1 | sum over every hypothesis |
| Specificity for false-positive rate | posterior far too low | second term uses 1 − specificity |
| Probabilities multiplied | belief above 1 after two tests | multiply odds, not probabilities |
| Correlated evidence | repeat tests give false certainty | do the tests share a sample or a mechanism? |
| Snapping to one hypothesis | confident and wrong after one reading | look at the whole posterior first |
| Zero count | one word decides the email | any count of 0 in a class? |
python import numpy as np def posterior(prior, sens, spec): """P(D | +): Bayes' rule with the law of total probability.""" p_pos = sens * prior + (1 - spec) * (1 - prior) return sens * prior / p_pos def update_odds(odds, lr): """One piece of independent evidence: multiply the odds by its likelihood ratio.""" return odds * lr def bayes_vector(prior, likelihood): """Many hypotheses: reweight, then normalise. Both are arrays of the same length.""" joint = np.asarray(prior, float) * np.asarray(likelihood, float) total = joint.sum() if total == 0: raise ValueError("the evidence is impossible under every hypothesis") return joint / total def word_lr(n_spam_w, n_spam, n_ham_w, n_ham): """Laplace-smoothed likelihood ratio of a word.""" return ((n_spam_w + 1) / (n_spam + 2)) / ((n_ham_w + 1) / (n_ham + 2)) print(posterior(0.20, 0.8, 0.8)) # 0.5 print(posterior(0.01, 0.8, 0.8)) # 0.0388 print(update_odds(update_odds(0.25, 4), 4)) # 4.0, a probability of 0.8 print(bayes_vector([0.5, 0.5], [1.0, 0.5])) # [0.667 0.333]: the trick coin print(word_lr(30, 500, 0, 1000)) # 61.9
We ran every function above in numpy; the comments are its output, rounded.
| Number | Value | Where it comes from |
|---|---|---|
| 80/80 test, prior 20% | 50% | 0.16 / (0.16 + 0.16) |
| 80/80 test, prior 1% | 3.9% | 0.008 / (0.008 + 0.198) |
| 80/80 test, prior 0.1% | 0.4% | 0.0008 / (0.0008 + 0.1998) |
| Likelihood ratio, 80/80 positive | 4 | 0.8 / 0.2 |
| Two independent positives from 20% | 80% | 0.25 × 4 × 4 = 4 to 1 |
| Same two, repeat chance 0.5 | 60% | 0.2 × 0.72 / (0.144 + 0.8 × 0.12) |
| Trick coin after one head | 0.667 | 0.5 / 0.75 |
| Smoothed LR of an unseen ham word | 61.9 | (31 / 502) / (1 / 1,002) |
Where it sits. Run Bayes' rule in a loop over time, with a motion step between readings, and you have the Bayes filter. Make every belief a Gaussian and it becomes the Kalman filter. Take the log of the posterior over a robot's whole trajectory and you get the least-squares costs of Uncertainty and Least Squares and VNAV 9.
Now teach it: press Present or Teach and explain why an 80% accurate positive means 50%, then 0.4%. Then go back to the thousand squares, pick 1 in 1,000, push the accuracy to 99%, and predict the posterior before you look.
Thirty-five exercises in five kinds: derive a number, trace a reason, find the buggy line, order a recipe. Work them on paper first; each reveal shows the full path.
Read every "given" as an instruction to change the room.
100 people: 20 sick, 80 healthy true positives (sick & +) = 0.8 * 20 = 16 false positives (healthy & +) = 0.2 * 80 = 16 P(sick | +) = 16 / 100 = 0.16
Name every term, then compute posteriors from scratch.
prior = 0.2; sens = 0.8; spec = 0.8 true_pos = sens * prior # 0.8 * 0.2 = 0.16 false_pos = spec * (1 - prior) P_pos = true_pos + false_pos posterior = true_pos / P_pos
Hold the test fixed, shrink the prior, and watch a positive lose its meaning.
prior_prob = 0.2 prior_odds = prior_prob / (1 - prior_prob) # 0.2/0.8 = 0.25 LR = sens / (1 - spec) # 0.8/0.2 = 4 post_odds = prior_odds + LR post_prob = post_odds / (1 + post_odds)
Spam, fraud and stacked tests run on the same rule.
belief = 0.20 # prevalence prior belief = posterior(belief, 0.8, 0.8) # after test 1 -> 0.5 belief = 0.20 belief = posterior(belief, 0.8, 0.8) # after test 2 print(belief) # prints 0.5, expected 0.8
These test whether you can explain the rule, not only compute it.
The test is 80% accurate. It came back positive. At 20% prevalence, half of the positives are false alarms. P(sick | positive) = P(positive | sick) = 0.8 We must fold in the 20% prior, giving 0.5.