A disease affects 1 person in 100. A test for it catches 95% of people who have it, and wrongly flags 5% of people who don't. You test positive. What's the chance you have the disease? Most people, including many doctors in published studies, say about 95%. The real answer is about 16%.
The gap comes from mixing up two different questions. The test's makers tell you P(positive | disease): how the test behaves for sick people. You want the reverse, P(disease | positive). Bayes' theorem is the rule for turning one into the other. You've already used it without the name, by reading a tree diagram backwards. Here you'll turn that into a short formula, give names to its three ingredients, and see why the most important ingredient is the one people forget: how common the cause was to begin with.
What you need first: conditional probability explained and tree diagrams for probability.
Key terms
- Prior, P(H): how likely a hypothesis H is before you see the evidence. Here, 1% have the disease.
- Likelihood, P(E | H): how likely the evidence E is if the hypothesis is true. Here, 95% of sick people test positive.
- Posterior, P(H | E): how likely the hypothesis is after seeing the evidence. The answer you want.
- Base rate: how common something is in the population; the prior, in many problems.
- Sensitivity and false positive rate: a test's P(positive | disease) and P(positive | no disease).
Start from the tree
Imagine 10,000 people taking the test:
- 1% have the disease: 100 people. The test catches 95% of them: 95 true positives.
- 99% don't: 9,900 people. The test wrongly flags 5% of them: 495 false positives.
- 590 positive tests in total. Only 95 of them belong to sick people.
P(disease | positive) = 95 ÷ 590 ≈ 0.16
The test is good, but the disease is rare. The healthy group is 99 times bigger than the sick group, so even its small false alarm rate produces five times as many positives as the real cases.
From the tree to the formula
Write the tree's calculation with probabilities instead of people:
- True positives: P(disease) × P(positive | disease) = 0.01 × 0.95
- All positives (law of total probability): 0.01 × 0.95 + 0.99 × 0.05
Divide the first by the second, and that's Bayes' theorem:
P(H | E) = P(H) × P(E | H) ÷ P(E)
In words: posterior = prior × likelihood ÷ how common the evidence is overall.
There's nothing new in it. The top is the "true" path through the tree; the bottom adds up every path that produces the evidence. You can also derive it in one line from conditional probability: P(H and E) can be written as P(H) × P(E | H) or as P(E) × P(H | E). Set the two equal and divide by P(E).
Here it is as a small function:
def bayes(prior, p_evidence_if_true, p_evidence_if_false):
true_path = prior * p_evidence_if_true
false_path = (1 - prior) * p_evidence_if_false
return true_path / (true_path + false_path)
print(round(bayes(prior=0.01, p_evidence_if_true=0.95, p_evidence_if_false=0.05), 3))
0.161
The function computes the two paths that end in "positive", then the share of them that came through the "true" branch.
The base rate decides everything
The same test gives very different answers depending on how common the disease is. Before running this, guess the posterior if 20% of the people tested have the disease, for example in a clinic where everyone has symptoms:
import numpy as np
import matplotlib.pyplot as plt
for prior in [0.001, 0.01, 0.2, 0.5]:
print(f"prior {prior:>5}: P(disease | positive) = {bayes(prior, 0.95, 0.05):.3f}")
priors = np.linspace(0.001, 0.6, 300)
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(priors, bayes(priors, 0.95, 0.05), color="#c2410c", linewidth=2.5)
ax.plot([0.01, 0.2], [bayes(0.01, 0.95, 0.05), bayes(0.2, 0.95, 0.05)], "o", color="#1c1917")
ax.annotate("screening everyone\nprior 1% → 16%", (0.01, bayes(0.01, 0.95, 0.05)), xytext=(0.06, 0.08))
ax.annotate("clinic with symptoms\nprior 20% → 83%", (0.2, bayes(0.2, 0.95, 0.05)), xytext=(0.25, 0.62))
ax.set_xlabel("Prior: share of tested people who have the disease")
ax.set_ylabel("P(disease | positive test)")
ax.set_title("The same test (95% sensitive, 5% false positives)")
ax.set_ylim(0, 1)
plt.show()
prior 0.001: P(disease | positive) = 0.019
prior 0.01: P(disease | positive) = 0.161
prior 0.2: P(disease | positive) = 0.826
prior 0.5: P(disease | positive) = 0.950
bayes(priors, 0.95, 0.05) works on a whole NumPy array of priors at once, because the function only uses arithmetic.
At a prior of 1 in 1,000, a positive test means only about a 2% chance of disease. At 1 in 5, it means 83%. The test didn't change; the base rate did. Ignoring the prior is called the base-rate fallacy, and it's why mass screening for rare diseases is followed by a second, more accurate test before anyone is told they're ill.
Updating twice
You test positive, so the doctor orders a second, independent test, and it's positive too. Bayes' theorem chains: today's posterior becomes tomorrow's prior.
after_one = bayes(0.01, 0.95, 0.05)
after_two = bayes(after_one, 0.95, 0.05)
print(f"after one positive: {after_one:.3f} after two positives: {after_two:.3f}")
after one positive: 0.161 after two positives: 0.785
From 1% to 16% to about 79%. Each piece of evidence moves the belief; strong evidence moves it a lot. This is how Bayesian reasoning works in general: start with a prior, update it with each new piece of evidence, and the posterior after each step is the prior for the next. (It assumes the two test results are independent given the disease status. Two tests that make the same kind of mistake don't count as two separate pieces of evidence.)
The odds form: a quick mental shortcut
For quick estimates, Bayes' theorem has a simpler form using odds (the chance for, against the chance against):
posterior odds = prior odds × (P(E | H) ÷ P(E | not H))
The fraction at the end is called the likelihood ratio: how much more likely the evidence is if H is true. For the test, it's 0.95 ÷ 0.05 = 19.
- Prior odds of 1% are 1 to 99.
- Multiply by 19: 19 to 99, which is about 1 to 5.
- Odds of 1 to 5 mean 1 chance in 6, about 16%.
The likelihood ratio says how strong the evidence is. A ratio of 1 means the evidence is useless; 19 is strong; 1,000 is overwhelming.
Where machine learning uses Bayes' theorem
- Naive Bayes classifiers compute P(class | features) from P(features | class) and the class's prior, exactly this formula, once per class. The Naive Bayes classifier lesson builds one.
- Precision and the base rate. A fraud model's precision is P(fraud | flagged): a posterior. It falls when fraud gets rarer, even if the model doesn't change, just like the curve above. That's why precision on a balanced test set can't be trusted for a rare real-world event, a theme of imbalanced datasets.
- Adjusting for a new base rate. If a model was trained on data with 50% fraud (after resampling) but the real rate is 1%, Bayes' theorem tells you how to correct its probabilities.
- Bayesian machine learning treats a model's parameters as hypotheses with priors, updated by data. Regularisation turns out to be a prior in disguise, a link this course returns to later.
Common mistakes
- Ignoring the base rate. P(positive | disease) = 95% doesn't make P(disease | positive) high.
- Swapping the conditionals. Say both directions in words before calculating.
- Forgetting the false-path in the denominator. P(E) includes evidence from cases where H is false.
- Treating correlated evidence as independent. Two tests with the same blind spot add less than two independent ones.
Practice
- A spam word appears in 40% of spam messages and 2% of normal messages. 20% of messages are spam. A message contains the word. What's the chance it's spam?
Show the answer
print(round(bayes(0.2, 0.4, 0.02), 3))
0.833
About 83%. As counts: of 1,000 messages, 200 spam (80 contain the word) and 800 normal (16 contain it). 80 of 96 is 83%.
- Predict, then check: with the same test, what prior gives a posterior of exactly 50% after one positive test?
Show the answer
5%. At a prior of 5%, the true positives (0.05 × 0.95) exactly equal the false positives (0.95 × 0.05).
print(round(bayes(0.05, 0.95, 0.05), 3))
0.5
- An improved test has the same 95% sensitivity but only 0.5% false positives. What's P(disease | positive) at a 1% prior? What changed?
Show the answer
print(round(bayes(0.01, 0.95, 0.005), 3))
0.657
About 66%. Cutting false positives tenfold shrinks the 495 false alarms per 10,000 people to about 50, so true positives are now the majority. For rare conditions, the false positive rate matters more than the sensitivity.
- A smoke alarm sounds for 99% of real fires and also goes off on 1 day in 200 from cooking. A real fire happens on 1 day in 10,000. When the alarm sounds, is there probably a fire?
Show the answer
print(round(bayes(1 / 10_000, 0.99, 1 / 200), 4))
0.0194
No: only about 2% of alarms are real fires. You should still check every time, because missing a real fire is so costly. A probability and a decision are different things.
- Explain, using the words prior and likelihood, why a positive test means more in a clinic of people with symptoms than in random screening.
Show the answer
The likelihoods (95% and 5%) are the same in both places, but the prior is much higher in the clinic, because people with symptoms are more likely to have the disease. A higher prior gives a higher posterior from the same evidence.
Interview questions
State Bayes' theorem and name each term.
P(H | E) = P(E | H) P(H) / P(E). P(H) is the prior, P(E | H) the likelihood, P(H | E) the posterior, and P(E) the evidence or marginal likelihood, computed by total probability as P(E | H)P(H) + P(E | ¬H)P(¬H).
A classifier has 99% recall and 1% false positive rate on a problem with 0.1% positives. What's its precision?
Precision = P(positive | flagged) = 0.001 × 0.99 / (0.001 × 0.99 + 0.999 × 0.01) ≈ 0.09. Fewer than 1 in 10 flags is a true positive, because false positives from the huge negative class outnumber the true positives. Rare classes need very low false positive rates.
Key takeaways
- Bayes' theorem turns P(evidence | cause) into P(cause | evidence): posterior = prior × likelihood ÷ P(evidence).
- It's the tree diagram read backwards: the "true" path divided by all paths that produce the evidence.
- The base rate (prior) matters enormously; ignoring it is the base-rate fallacy.
- Evidence updates beliefs one piece at a time: each posterior becomes the next prior.
- In ML, Naive Bayes uses it directly, and precision is a posterior that falls with the base rate.
Frequently asked questions
Who was Bayes?
Thomas Bayes, an 18th-century English minister and mathematician. His idea was published after his death, and Pierre-Simon Laplace developed it into the general form used today.
What's the difference between Bayesian and frequentist statistics?
Both use Bayes' theorem for events like disease. They differ on whether you can put probabilities on fixed unknowns, such as a model's true parameter. Bayesians do, using priors; frequentists don't. The statistics course covers this later.
Where does the prior come from?
From data about the population when you have it (how common the disease is), from earlier evidence (the previous posterior), or from judgement. With enough evidence, different reasonable priors end up at similar posteriors.
What to learn next
- Apply it to real data in Bayes in practice: medical tests and spam filters.
- Revisit backward reading in tree diagrams for probability.
- Build a Bayes classifier in Naive Bayes classifier.