Bayes' Rule

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.

Test a thousand people

80%

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

The Base-Rate Trap

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%.

Guess, then count

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.

80%

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.

The road

  1. Condition: a "given" shrinks the room you count in.
  2. The rule: derive Bayes' rule from the joint probability, and name its four parts.
  3. The test: the evidence term, and the disease test worked in full.
  4. Base rate: hold the test fixed and watch a positive lose its meaning.
  5. Odds: evidence multiplies the odds by a fixed amount.
  6. Chain: yesterday's posterior is today's prior, if the tests are independent.
  7. Many: ten hypotheses at once, a robot finding its alcove.
  8. Naive Bayes: a spam filter is the chain over words.
  9. Showcase: design a screening programme.
  10. Field guide: the failure table and the code.
1 in 5 people have a disease. An 80/80 test says positive. Why is the chance you are sick far below 80%?

Chapter 1

A "Given" Shrinks the Room

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.

Change the room

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).

Say it aloud

P of A given B equals P of A and B, divided by P of B.

P(A | B)
P of A given B the share of the B room that is also A.
P(A and B)
P of A and B the share of everyone who is both. It is the same group as "B and A".
P(B)
P of B the share of everyone who is B: the size of the room. It must be above 0.
In plain words

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.

With numbers

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.

In a class of 100, 30 students play an instrument and 12 of those also sing. What is P(sings | plays)?

Chapter 2

Bayes' Rule Flips the Conditional

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(X and Y) = P(X | Y) × P(Y)
P(Y and X) = P(Y | X) × P(X)
so P(Y | X) × P(X) = P(X | Y) × P(Y)
Say it aloud

P of Y given X equals P of X given Y, times P of Y, divided by P of X.

P(Y | X)
P of Y given X the posterior: your belief in the cause after you see the evidence.
P(X | Y)
P of X given Y the likelihood: how often the cause produces this evidence. For the test, 0.8.
P(Y)
P of Y the prior: your belief before the evidence. Here the base rate, 0.2.
P(X)
P of X the evidence: how likely the evidence was over all causes. It makes the posteriors sum to 1.
In plain words

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).

With numbers

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".

Reweight, then normalise

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.

0.20
0.80
0.20

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.

In P(Y | X) = P(X | Y) × P(Y) / P(X), which term is your belief before you see the evidence?

Chapter 3

The Disease Test, Worked in Full

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.

Say it aloud

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.

P(+)
P of plus the evidence: the share of everyone who tests positive.
P(+ | D)
P of plus given D the sensitivity, 0.8.
P(D)
P of D the prior, the base rate: 0.2.
P(+ | not D)
P of plus given not D the false-positive rate, 1 minus the specificity: 0.2.
P(not D)
P of not D the share who are healthy, 1 minus the prior: 0.8.
In plain words

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.

With numbers

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.

Shade the positives

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.

0.20
0.80
0.80

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.

With a prior of 0.2 and an 80/80 test, P(+) = 0.16 + 0.16. What is the second 0.16?

Chapter 4

Rare Things Are Hard to Screen For

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.

Sweep the base rate

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.

20%
80.0%

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.

The test stays the same and the disease gets rarer. What happens to the chance that a positive person is sick?

Chapter 5

Evidence Multiplies the Odds

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.

Say it aloud

O-post equals LR times O-prior, where LR is P of plus given D over P of plus given not D.

Opost
O-post the posterior odds: P(D | +) over P(not D | +).
LR
L-R the likelihood ratio: how many times likelier the evidence is if D is true. Above 1 pushes belief up, below 1 pushes it down.
Oprior
O-prior the prior odds: P(D) over P(not D).
P(+ | D)
P of plus given D the sensitivity.
P(+ | not D)
P of plus given not D the false-positive rate.
In plain words

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.

With numbers

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.

Push the odds

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.

20%
80%

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.

Prior odds are 1 to 99. A test with likelihood ratio 19 is positive. What are the posterior odds?

Chapter 6

Today's Posterior Is Tomorrow's Prior

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.

Say it aloud

O-n equals O-zero times L-R-one times L-R-two, and so on up to L-R-n.

On
O-n the odds after n results.
O0
O-zero the prior odds, before any result. Here 0.25.
LRk
L-R-k the likelihood ratio of result number k: 4 for a positive, 0.25 for a negative.
In plain words

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.

With numbers

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.

Chain the results

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.

After one positive your belief is 0.50. A second independent 80/80 test is also positive. What is your belief now?

Chapter 7

Many Hypotheses at Once

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.

Say it aloud

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.

P(hi | z)
P of h-i given z the posterior: the belief that the robot is in alcove i after the reading.
P(z | hi)
P of z given h-i the likelihood: how well a robot in alcove i explains the reading z.
P(hi)
P of h-i the prior for alcove i, before the reading.
Σj
the sum over j add one term for every alcove, j = 1 to 10. This is the evidence P(z), the law of total probability with ten terms.
In plain words

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.

With numbers

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.

Find the alcove

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.

2.30 m

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.

With equal priors, three alcoves fit the reading almost equally well. What does Bayes' rule do?

Chapter 8

A Spam Filter Is the Chain Over Words

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.

Say it aloud

P of w given spam equals n-w plus one, over N plus two.

P(w | spam)
P of w given spam the estimated chance that a spam email contains word w.
nw
n-w how many training spam emails contain w.
+ 1
plus one one imagined spam email that contains w.
N
N the number of training spam emails, here 500.
+ 2
plus two two imagined emails in all: one with the word and one without.
In plain words

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.

With numbers

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.

Score an email

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.

What does "naive" mean in a naive Bayes spam filter?

Chapter 9

Design a Screening Programme

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.

Run the programme

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.

90%

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.

The confirmation reruns the same blood sample, and the share of confirmed positives who are sick stays low. Why?

Chapter 10

Field Guide

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.

FailureSymptomCheck that names it
Base-rate trap"80% accurate" reported as 80% surecount true and false positives in 100 people
Flipped conditionalP(+ | D) quoted as P(D | +)which room is the denominator?
Joint for conditionala "given" that comes out tinydivided by everyone instead of the room
Missing normaliserposteriors do not sum to 1sum over every hypothesis
Specificity for false-positive rateposterior far too lowsecond term uses 1 − specificity
Probabilities multipliedbelief above 1 after two testsmultiply odds, not probabilities
Correlated evidencerepeat tests give false certaintydo the tests share a sample or a mechanism?
Snapping to one hypothesisconfident and wrong after one readinglook at the whole posterior first
Zero countone word decides the emailany 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.

NumberValueWhere 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 positive40.8 / 0.2
Two independent positives from 20%80%0.25 × 4 × 4 = 4 to 1
Same two, repeat chance 0.560%0.2 × 0.72 / (0.144 + 0.8 × 0.12)
Trick coin after one head0.6670.5 / 0.75
Smoothed LR of an unseen ham word61.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.

Keep going

Read next

The habit. Before you trust a percentage, ask which room it was counted in. Then ask how common the cause was before you looked.
A model says "this transaction looks like fraud with 95% sensitivity". What do you need before you can say how likely it is fraud?

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.

Workbook

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.

Workbook progress
0 / 35 exercises (0%)
0
Day streak
Best: 0

Part A: Conditional probability, the smaller room

Read every "given" as an instruction to change the room.

A.1: What the bar means Trace
P(A | B) is read "the probability of A given B." What does conditioning on B do?
A.2: Count in the room Derive
Of 100 people, 40 own a bike and of those 10 own a helmet. Compute P(helmet | bike). Enter a decimal.
P
Show derivation
Condition on "bike" → denominator is 40, not 100.
P(helmet | bike) = 10 / 40 = 0.25
Once you condition on bike, the 60 people without a bike drop out.
A.3: Card conditioning Derive
From a 52-card deck, what is P(Queen | face card)? Face cards are J, Q, K. Enter the decimal (3 dp).
P
Show derivation
12 face cards; 4 are Queens. P(Q | face) = 4/12 = 1/3 ≈ 0.333
Unconditional P(Queen) = 4/52 ≈ 0.077; the "face card" room raised it to 0.333.
A.4: The directional trap Trace
Which statement is true about P(A | B) versus P(B | A)?
A.5: Multiplication rule Derive
P(rain) = 0.30 and P(umbrella | rain) = 0.90. Using P(A and B) = P(A | B)·P(B), find P(rain and umbrella). Enter a decimal.
P
Show derivation
P(rain and umbrella) = P(umbrella | rain) · P(rain) = 0.90 × 0.30 = 0.27
A.6: Spot the "and"/"given" swap Debug
A student computes P(sick | positive) from 100 people. Exactly one line confuses "and" with "given." Click it.
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
Part A rule. "Given" shrinks the denominator to the room you condition on. "And" divides by everyone. Mixing the two is where the base-rate trap starts.

Part B: Bayes' rule and its parts

Name every term, then compute posteriors from scratch.

B.1: Name the prior Trace
In P(Y|X) = P(X|Y)P(Y)/P(X), the term P(Y) is the...
B.2: Name the likelihood Trace
Which term is the likelihood: how well the cause explains the evidence?
B.3: Compute the evidence Derive
Prior P(D)=0.10, sensitivity P(+|D)=0.90, false-positive P(+|¬D)=0.20. By total probability, P(+) = 0.90·0.10 + 0.20·0.90. Enter P(+).
P(+)
Show derivation
P(+) = (0.90 × 0.10) + (0.20 × 0.90) = 0.09 + 0.18 = 0.27
B.4: The famous posterior Derive
Prior 0.20, sensitivity 0.80, specificity 0.80. Compute P(D | +). Enter a decimal.
P
Show derivation
numerator = 0.80 × 0.20 = 0.16
P(+) = 0.16 + (0.20 × 0.80) = 0.16 + 0.16 = 0.32
P(D | +) = 0.16 / 0.32 = 0.50
0.5, not 0.8: the true and false positives are equal.
B.5: A better test Derive
Same prior 0.20, but sensitivity 0.90 and specificity 0.95 (false-positive 0.05). Compute P(D | +), 2 dp.
P
Show derivation
numerator = 0.90 × 0.20 = 0.18
P(+) = 0.18 + (0.05 × 0.80) = 0.18 + 0.04 = 0.22
P(D | +) = 0.18 / 0.22 ≈ 0.818
Raising specificity from 0.80 to 0.95 jumped the posterior from 0.50 to 0.82.
B.6: Trick-coin posterior Derive
A fair coin (heads 0.5) and a two-headed coin (heads 1.0), picked 50/50. You flip heads. P(two-headed | heads)? 3 dp.
P
Show derivation
P(heads) = 1.0·0.5 + 0.5·0.5 = 0.5 + 0.25 = 0.75
P(2H | heads) = (1.0 × 0.5) / 0.75 = 0.5/0.75 = 2/3 ≈ 0.667
B.7: The sign-error bug Debug
A student computes the evidence P(+) for prior 0.2, sens 0.8, spec 0.8. One line has the wrong false-positive rate. Click it.
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
B.8: Order the Bayes recipe Design
Put the steps of computing a posterior in order.
?
→
?
→
?
→
?
divide numerator by evidence numerator = likelihood × prior write down prior & likelihoods evidence = sum over all causes
Part B rule. Posterior = likelihood × prior / evidence, and the evidence is the sum of likelihood × prior over every hypothesis. Name the parts, compute the numerator, compute the evidence, divide.

Part C: The base-rate effect

Hold the test fixed, shrink the prior, and watch a positive lose its meaning.

C.1: Rare-disease posterior Derive
Prevalence 0.01, sens 0.80, spec 0.80. Compute P(D | +), 3 dp.
P
Show derivation
numerator = 0.80 × 0.01 = 0.0080
false pos = 0.20 × 0.99 = 0.198
P(+) = 0.0080 + 0.198 = 0.206
P(D | +) = 0.0080 / 0.206 ≈ 0.039
C.2: The likelihood ratio Derive
For sensitivity 0.80 and false-positive rate 0.20, the likelihood ratio of a positive is sens / FP-rate. Enter it.
LR
Show derivation
LR = 0.80 / 0.20 = 4: a positive multiplies your odds by 4.
C.3: Odds form Derive
Prevalence 0.20 → prior odds 0.25. Positive test, LR = 4. Posterior odds = 4×0.25 = 1. Convert to probability: odds/(1+odds). Enter it.
P
Show derivation
posterior odds = 4 × 0.25 = 1 = 1:1
P = 1 / (1 + 1) = 0.50: agrees with the long calculation.
C.4: Why screening rare things fails Trace
For a rare disease, why does a positive test mean so little even with a good test?
C.5: The wrong fix Trace
To make a positive trustworthy for a rare disease, the highest-leverage single change is to...
C.6: Design a precise screen Design
A disease affects 1% of people and the test is 80/80, so a positive means 3.9%. Order these changes from the largest to the smallest posterior after one positive.
?
→
?
→
?
raise sensitivity to 0.90 test only a group where 1 in 4 is sick raise specificity to 0.99
C.7: Odds-form bug Debug
A student updates odds for a positive test. Exactly one line is wrong. Click it.
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)
Part C rule. Evidence multiplies the odds by its likelihood ratio. A rare condition starts at tiny odds, so even a 4× or 19× push leaves them small. Raise the prior (test a higher-risk group) or the specificity; more sensitivity barely helps.

Part D: Applications & chaining

Spam, fraud and stacked tests run on the same rule.

D.1: Spam filter Derive
10% of mail is spam. The word "free" appears in 60% of spam and 5% of ham. An email contains "free." P(spam | "free")? 2 dp.
P
Show derivation
numerator = P("free"|spam)·P(spam) = 0.60 × 0.10 = 0.060
P("free") = 0.060 + 0.05×0.90 = 0.060 + 0.045 = 0.105
P(spam | "free") = 0.060 / 0.105 ≈ 0.571
D.2: Two positive tests Derive
After one positive your belief is 0.50. A second independent 80%-accurate test is positive too. P(sick | both +)? 2 dp.
P
Show derivation
new prior = 0.50; numerator = 0.80×0.50 = 0.40
P(+) = 0.40 + 0.20×0.50 = 0.50; posterior = 0.40/0.50 = 0.80
Odds shortcut: 0.25 × 4 × 4 = 4 → 4/5 = 0.8.
D.3: A negative result Derive
Prior 0.20, sens 0.80, spec 0.80. The test is negative. P(sick | −)? 3 dp. (Use P(−|D)=0.20, P(−|¬D)=0.80.)
P
Show derivation
numerator = P(−|D)·P(D) = 0.20 × 0.20 = 0.04
P(−) = 0.04 + 0.80×0.80 = 0.04 + 0.64 = 0.68
P(sick | −) = 0.04 / 0.68 ≈ 0.059
A negative lowered you from 0.20 to about 0.06: reassuring, but not zero.
D.4: Fraud detection Derive
0.5% of transactions are fraud. The detector flags 95% of fraud and 2% of legit transactions. A transaction is flagged. P(fraud | flag)? 3 dp.
P
Show derivation
numerator = 0.95 × 0.005 = 0.00475
P(flag) = 0.00475 + 0.02×0.995 = 0.00475 + 0.0199 = 0.02465
P(fraud | flag) = 0.00475 / 0.02465 ≈ 0.193
Even a 95%/98% detector raises about 4 false alarms for each real fraud: 0.0199 against 0.00475.
D.5: Naive Bayes chip Trace
What does "naive" mean in a naive Bayes spam filter?
D.6: Posterior becomes prior Trace
What is the core loop of Bayesian updating across multiple pieces of evidence?
D.7: Chaining bug Debug
A student chains two tests. One line resets belief instead of carrying it forward. Click it.
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
D.8: Design the chained pipeline Design
Order the steps to combine two independent tests.
?
→
?
→
?
update again using that posterior as the new prior start from the prevalence prior apply Bayes with test 1's result

Part E: Conceptual mastery

These test whether you can explain the rule, not only compute it.

E.1: Likelihood ≠ posterior Trace
"The test is 80% accurate" gives you which quantity directly?
E.2: Role of the evidence term Trace
What is the job of P(X), the evidence, in Bayes' rule?
E.3: When is the posterior exactly 0.5? Derive
The posterior is 0.5 when true positives equal false positives. With sens 0.6 and FP-rate 0.2, at what prevalence (2 dp) does sens·p = FP·(1−p) hold? Enter p.
p
Show derivation
0.6p = 0.2(1−p) ⇒ 0.6p = 0.2 − 0.2p ⇒ 0.8p = 0.2 ⇒ p = 0.25
E.4: The base-rate fallacy named Trace
A juror hears "the DNA match is 99.9% accurate" and concludes the defendant is 99.9% guilty. What's the error?
E.5: Two clues, odds form Derive
Prior odds 0.25. Clue 1 has LR 4 (raises belief); clue 2 has LR 0.5 (lowers it). Posterior odds = 0.25×4×0.5. Convert to probability, 3 dp.
P
Show derivation
posterior odds = 0.25 × 4 × 0.5 = 0.5
P = 0.5 / (1 + 0.5) = 0.333
E.6: Reasoning bug Debug
A reasoner walks through the disease case. Exactly one line is a logical error. Click 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.
Bayes' Rule · Updating Belief with Evidence
Next: Bayes Estimation · Back to Gleams