Bayes' Theorem
What You'll Learn
- 1State Bayes' theorem and identify prior, likelihood, evidence and posterior in any problem
- 2Apply the extended form when the sample space is split into several mutually exclusive causes
- 3Explain the base-rate paradox using a fully numeric medical-testing example
- 4Update probabilities in sequence with the odds form of the theorem
- 5Implement posterior calculations as short Python functions and test them on three classic problems
A manufacturing line rejects a batch because one machine produced defects at twice the usual rate â but which machine? A medical screening test comes back positive: how alarmed should the patient be? A spam filter sees the word "wire transfer": how much should that single clue shift the odds? All three questions share one shape. You observe evidence, you know how likely that evidence is under each of several possible causes, and you want the probability of each cause given the evidence. Bayes' theorem is the machine that performs that reversal, and the examples in this lesson show both how to run it and how it misleads people who skip the denominator.
The theorem and its four players
Every instance of the formula has four named parts. is the prior: what you believed about the cause before the evidence arrived. is the likelihood: how probable the evidence is if the cause is true. The product on top is the joint probability of cause and evidence together. The denominator is the evidence, also called the total probability or normalising constant, and it is almost always computed by summing the joint probability over every possible cause. The result is the posterior: the updated belief after seeing the evidence. Theorem names fade; these four roles do not, because every Bayes question on an exam is really a request to fill in this table.
| Quantity | Symbol | Where it comes from |
|---|---|---|
| Prior | given, or the natural base rate | |
| Likelihood | given in the problem statement | |
| Evidence | total probability over all causes | |
| Posterior | what the question asks for |
The extended theorem for a partition
If are mutually exclusive and exhaustive events, then:
The extended form is the practical one, because real evidence rarely has a single alternative cause. The denominator now collects one joint-probability term per cause, and those terms are exactly the numerator you would write for each cause in turn â a useful mnemonic is "compute every numerator first; their sum is the denominator." Mutually exclusive matters: overlapping causes would double-count evidence and push the posteriors above one. Exhaustive matters too: if some cause is missing from the partition, its share of the evidence leaks out of the denominator and every posterior is inflated.
Worked example: medical testing and the base-rate paradox
A disease affects 1% of a population. A test for the disease has 95% sensitivity (correctly identifies diseased) and 90% specificity (correctly identifies non-diseased). If a person tests positive, what is the probability they have the disease?
The number that drives the surprise is visible in the second step: among 1000 people, roughly 10 are truly diseased and about 9 of them test positive, while among the 990 healthy people about 99 test positive anyway. The false positives outnumber the true positives ten to one, and the posterior is nothing more than the true positives' share of that pile. Raising the prior to 50% would flip the conclusion â the same test in a high-risk population yields a posterior above 90% â which is exactly why screening protocols stage their tests: a cheap sensitive screen first, then an expensive specific confirmation for the positive subset.
Worked example: drawing from an urn
Urn I contains 3 red and 4 blue balls. Urn II contains 5 red and 6 blue balls. A ball is drawn at random from a randomly chosen urn. If the ball is red, find the probability it came from Urn I.
The answer sits just below one half, which makes sense: Urn I draws red less often than Urn II ( against ), so a red ball is mild evidence for Urn II, and the equal priors are only slightly disturbed. Notice how small the likelihood difference is compared with the medical example â when likelihoods barely differ, the posterior barely moves from the prior, a rule of thumb worth carrying into data-science work.
Worked example: attributing defects to a factory
Factory A produces 60% of items, Factory B produces 40%. Defect rates are 2% and 3% respectively. If an item is defective, find the probability it came from Factory A.
This tidy answer hides a coincidence worth unpacking: both factories contribute exactly defects, even though A makes more items and B makes them worse. The prior advantage of A (three to two) is cancelled by the quality disadvantage (two to three), and the posterior splits evenly. Change either number slightly and the balance tips â the sensitivity of the posterior to each input is precisely what quality-control engineers rely on when they decide which line to audit first.
The odds form and sequential updating
Rearranging Bayes' theorem into odds gives a compact tool for multi-stage evidence. Define prior odds as and the likelihood ratio as ; then
In the medical example the likelihood ratio is : a positive test multiplies the odds of disease by nine and a half. Starting from odds , the posterior odds become , which is the same as before. A second independent positive test multiplies by again, pushing the odds to about â near even â and that is the arithmetic reason confirmatory testing works. Independence is essential: if the two tests share failure modes the second multiplier is smaller, and naive multiplication overstates the posterior.
Computing posteriors in Python
The first function implements the two-class Bayes formula and sweeps the prior to show how strongly the base rate controls the answer, then applies a second independent test.
def posterior(prior, likelihood, false_rate):
top = likelihood * prior
return top / (top + false_rate * (1 - prior))
p1 = posterior(0.01, 0.95, 0.10)
print("P(D|+) prior 1% :", round(p1, 4))
print("P(D|+) prior 50% :", round(posterior(0.50, 0.95, 0.10), 4))
print("P(D|+) prior 90% :", round(posterior(0.90, 0.95, 0.10), 4))
p2 = posterior(p1, 0.95, 0.10)
print("second positive :", round(p2, 4))
lr = 0.95 / 0.10
odds = (0.01 / 0.99) * lr * lr
print("odds form twice :", round(odds / (1 + odds), 4))
The sweep prints approximately , and , and the odds-form shortcut matches the two-stage posterior exactly.
The second script reproduces the urn and factory examples using exact fractions, so no rounding error can creep into the comparison.
from fractions import Fraction as F
def bayes_exact(prior, likelihood, other_prior, other_likelihood):
evidence = likelihood * prior + other_likelihood * other_prior
return likelihood * prior / evidence
urn = bayes_exact(F(1, 2), F(3, 7), F(1, 2), F(5, 11))
print("P(U1|R) =", urn, "=", float(urn))
factory = bayes_exact(F(6, 10), F(2, 100), F(4, 10), F(3, 100))
print("P(A|D) =", factory, "=", float(factory))
print("contributions:", F(6, 10) * F(2, 100), F(4, 10) * F(3, 100))
The urn posterior reduces to and the two factory contributions print as identical fractions , confirming the even split found by hand.
Misreads that invert the answer
Three misunderstandings account for most wrong answers. Substituting the prior into the likelihood slot â reporting when the question asked for â is the classic inversion, and it turns the medical paradox into a false reassurance. Skipping the denominator and reporting only the numerator produces a number that is not a probability at all. Finally, using the overall positive rate as the prior, rather than the disease prevalence, double-counts the evidence. Each error is caught by the same test: ask whether the answer you wrote is a statement about the cause given the evidence, or about the evidence given the cause.
Common Mistakes
Reporting the likelihood when the question asks for the posterior
Fix: Read the conditioning out loud: given that the test is positive, the target is the probability of disease, which needs the full Bayes formula rather than the sensitivity number.
Forgetting to include every cause in the denominator
Fix: List all mutually exclusive causes first, write one joint probability term for each, and add them; the sum is the only legal denominator.
Multiplying likelihood ratios from tests that are not independent
Fix: Sequential updating assumes each new test's error rate is unchanged given the true state; if the tests share a failure mode, use the joint likelihood instead of two separate multipliers.
Key Takeaways
- Bayes' theorem converts a likelihood into a posterior by multiplying the prior and dividing by the total probability of the evidence
- The extended form sums one joint-probability term per cause, and every term that belongs in the partition must appear
- Rare events dominate the medical-testing paradox: 95% accuracy still yields under 9% posterior when the prior is 1%
- The odds form multiplies prior odds by the likelihood ratio, which makes multi-stage evidence a chain of multiplications
- Every posterior calculation is a short function in Python, and exact fractions keep the urn and factory answers free of rounding error