Level 3 In-Depth AI · Math Foundations
Bayes' Theorem
Bayes' theorem tells you how to update a belief when new evidence arrives — combine what you believed before (the prior) with how well the evidence fits (the likelihood) to get what you should believe now (the posterior). It explains why rare conditions fool good tests, and underlies spam filters and Bayesian machine learning.
- Level
- ●●●●● Easy
- Reading
- 11 min
- To learn it well
- 45 minutes to read, an hour to practise
- Builds on
- 1 concept →
- Quiz
- 5 questions ↓
Read first
Probability BasicsThis leads to
Naive BayesThe full path from zero — 1 concept before this one
- Probability Basics
- Bayes' Theorem
Read them roughly in this order. See it on the concept map →
Why it matters
A test for a rare disease is 90% accurate at catching the disease. You test positive. How worried should you be? Most people, and studies show many doctors too, guess about 90%. The right answer, with realistic numbers, can be under 10%.
The tool that gets this right is Bayes' theorem. It turns "how likely is this evidence if the hypothesis is true?" into "how likely is the hypothesis, now that I've seen the evidence?" Those two are very different, and confusing them is one of the most common mistakes in reasoning.
Bayes' theorem matters for AI in several ways:
- Naive Bayes spam filters, among the first machine-learning systems used by millions of people, apply it word by word.
- Any classifier's output can be read as a posterior probability: how likely each class is, given the input. Knowing how base rates affect that probability is essential for setting thresholds and judging precision.
- Bayesian machine learning treats a model's parameters as uncertain and updates beliefs about them as data arrives. Common techniques such as weight decay can be read as a Bayesian prior (see Regularization: L1 and L2 and Maximum Likelihood Estimation).
- It is a clear way of thinking about evidence in everyday life: about news, test results, and AI systems' own claims.
The intuition
Bayes' theorem says that what you should believe after seeing evidence depends on two things:
- How plausible the idea was before the evidence. This is the prior.
- How well the idea explains the evidence, compared with the alternatives. This is the likelihood.
Your updated belief is the posterior.
Here is an everyday example. You hear hooves outside your window in London. Horses explain hooves well. So do zebras, just as well. Yet you should think "horse", because horses in London are far more common than zebras. The evidence fits both, so the prior decides. Doctors have a saying for this: "When you hear hoofbeats, think horses, not zebras."
The trick that makes Bayes easy is to stop thinking in percentages and count people. Imagine 1,000 people taking a test. Work out how many are sick and how many test positive, then look only at the positives. This is the "shrink the world" idea of conditional probability again.
Key idea Posterior ∝ prior × likelihood. What you believe after the evidence is what you believed before, weighted by how well each possibility explains the evidence. A strong test for a rare condition still produces mostly false alarms, because the low prior wins.
How it works
The medical test, by counting
A disease affects 1% of people. A test for it:
- detects 90% of sick people (it says "positive" for 90% of those who have the disease);
- wrongly says "positive" for 9% of healthy people (a false positive rate of 9%).
You test positive. What is the probability you are sick?
Take 1,000 people:
- 1% are sick: 10 people. The test catches 90% of them: 9 true positives, and misses 1.
- 99% are healthy: 990 people. The test wrongly flags 9% of them: about 89 false positives.
Now look only at the people who tested positive: . Of those, only 9 are actually sick:
About 9%. A positive result raised the chance from 1% to 9%, a big increase, but most positives are still false alarms, because there are so many more healthy people available to produce them.
The proportion of a population that has a condition before any test is the base rate. Ignoring it, and answering "90%", is the base rate fallacy. Notice what 90% actually was: . What you wanted was . Bayes' theorem is the bridge between them.
The formula
From the multiplication rule in Probability Basics, the probability of "A and B" can be written two ways:
Divide both sides by and you have Bayes' theorem:
With a hypothesis (for example, "sick") and evidence (for example, "positive test"), each piece has a name:
- Prior : how probable the hypothesis was before seeing the evidence. Here 0.01.
- Likelihood : how probable the evidence is if the hypothesis is true. Here 0.90.
- Evidence : how probable the evidence is overall, counting every way it can happen. Here the true positives plus the false positives:
- Posterior : the updated belief.
Same answer as counting, as it must be. The denominator is just there to make the posterior probabilities of all the hypotheses add up to 1. That's why Bayes is often written with the symbol ("is proportional to"): posterior ∝ likelihood × prior. Compute likelihood × prior for every hypothesis, then divide by the total.
Updating again: today's posterior is tomorrow's prior
Suppose you take a second, independent test, and it is also positive. Now your starting belief isn't 1% any more. It's 9.2%. Apply Bayes again with prior 0.092:
Two positives bring you to about 50%. Each piece of evidence moves the belief, and the order doesn't matter. This step-by-step updating is the heart of Bayesian learning: start with a prior, and let each new observation turn it into a sharper posterior.
The odds form: how strong is the evidence?
Bayes has a compact version that is handy for mental arithmetic. Odds are the ratio of "for" to "against": a probability of 0.01 is odds of 1 to 99. The likelihood ratio measures how much more probable the evidence is if the hypothesis is true than if it is false. For a positive test, . Then:
Prior odds 1 : 99, times 10, gives 10 : 99, which is a probability of . A second positive multiplies by 10 again: 100 : 99, about 50%. So a likelihood ratio says how strong a piece of evidence is, regardless of the prior: a ratio of 10 multiplies the odds by 10, whatever they were before.
Spam filtering with Bayes
The spam table from Probability Basics had , and 60% of spam contains "free" versus 5% of normal email (). An email arrives containing "free":
This matches the 0.75 we counted directly. A Naive Bayes classifier does this with thousands of words at once, multiplying their likelihoods under the "naive" assumption that words are independent of each other given the class.
Learning a number: a coin's bias
Bayes works with infinitely many hypotheses too. Suppose you want to learn the probability that a bent coin lands heads. Every value of from 0 to 1 is a hypothesis. Start with a flat prior (no preference). After each batch of flips, multiply the prior by the likelihood of the observed flips for every possible , and renormalise.
Notice two things. The posterior's peak moves to where the data point (0.7). And with more data, the posterior gets narrower: you become more certain. A Bayesian answer is not just a single number but a whole distribution, which tells you how sure you should be. This is the idea behind Bayesian neural networks and many uncertainty-estimation methods.
In code
import numpy as np
def posterior(prior, p_pos_if_true, p_pos_if_false):
"""P(condition | positive test) by Bayes' theorem."""
evidence = p_pos_if_true * prior + p_pos_if_false * (1 - prior)
return p_pos_if_true * prior / evidence
p = posterior(prior=0.01, p_pos_if_true=0.90, p_pos_if_false=0.09)
print(round(p, 3)) # 0.092 after one positive test
print(round(posterior(p, 0.90, 0.09), 3)) # 0.503 after a second positive
# Check by simulating a million people
rng = np.random.default_rng(0)
sick = rng.random(1_000_000) < 0.01
positive = np.where(sick, rng.random(sick.size) < 0.90, rng.random(sick.size) < 0.09)
print(round(sick[positive].mean(), 3)) # 0.092 fraction of positives who are sick
# Learning a coin's bias: a grid of possible p values, flat prior
grid = np.linspace(0, 1, 101)
prior = np.ones_like(grid) / len(grid)
heads, flips = 7, 10
likelihood = grid**heads * (1 - grid)**(flips - heads)
post = prior * likelihood
post /= post.sum() # normalise so it sums to 1
print(round(grid[post.argmax()], 2)) # 0.7 most probable bias
print(round(post[grid > 0.5].sum(), 3)) # 0.88 P(coin favours heads | data)
The last line shows something a single estimate can't: given 7 heads in 10 flips and a flat prior, you can be about 88% sure the coin favours heads. Libraries such as PyMC and NumPyro automate this kind of reasoning for models with many parameters.
Common pitfalls
- Confusing with . "90% of sick people test positive" is not "90% of positives are sick". This error is so common in courtrooms it has a name, the prosecutor's fallacy.
- Ignoring the base rate. The rarer the condition, the more a positive result is dominated by false alarms. The same test applied to a high-risk group, where the base rate is higher, gives a far higher posterior.
- Double-counting evidence. Bayes' multiplication assumes each new piece of evidence is independent given the hypothesis. Two tests that share the same flaw, or two news stories copied from one source, are not two independent pieces of evidence.
- A prior of exactly 0 or 1. If the prior is 0, no evidence can ever raise it, because 0 times anything is 0. Keep some doubt.
- Base rates that shift. A classifier trained where 50% of examples were fraud will produce badly inflated fraud probabilities in production where 0.1% are. Adjust the prior or recalibrate.
Watch out A classifier's precision (the fraction of its "yes" answers that are right) depends on the base rate, just like the medical test. A fraud detector with excellent accuracy on a balanced test set can still raise mostly false alarms on real traffic where fraud is rare. Always evaluate on data with realistic class proportions (see Evaluation Metrics).
Where it leads
- Naive Bayes: Bayes' theorem plus an independence assumption makes a fast, strong text classifier.
- Statistics: Mean, Variance and Sampling: the frequentist toolkit of confidence intervals, a different way of expressing uncertainty from the Bayesian posterior.
- Maximum Likelihood Estimation: choosing parameters that maximise the likelihood alone. Adding a prior gives the maximum a posteriori (MAP) estimate, and a Gaussian prior on weights turns out to be L2 Regularization: L1 and L2.
- Evaluation Metrics: precision, recall and why base rates matter for them.
- Variational autoencoders and Diffusion Models use Bayesian ideas (priors, posteriors and approximations to them) at their core.
- Hallucinations: thinking in priors and evidence helps judge when to trust a model's confident claims.
A bit of history
Thomas Bayes, an English Presbyterian minister, worked out the core idea for the problem of inferring a coin's bias from flips. His essay was published in 1763, two years after his death, by his friend Richard Price. Pierre-Simon Laplace discovered the result independently in 1774, stated it in its general modern form, and used it on problems from astronomy to birth rates. Through much of the 20th century Bayesian methods were controversial among statisticians, who objected to subjective priors, but they were used to great effect in practice. During the Second World War, Alan Turing used Bayesian reasoning, with evidence measured in units he called "bans", to help break the Enigma code. With fast computers and sampling algorithms from the 1990s onwards, Bayesian methods became mainstream, and in 2002 Paul Graham's essay "A Plan for Spam" popularised Bayesian spam filtering.
Try it
- Redo the medical test with a base rate of 10% instead of 1%. What is now? Count 1,000 people first, then check with the formula.
- A test has a likelihood ratio of 50 for a positive result. Using the odds form, what is the posterior probability for someone whose prior is 2%?
- In the coin code, start from a prior that strongly believes the coin is fair:
prior = np.exp(-((grid - 0.5) / 0.05) ** 2), normalised. How many flips at a 70% heads rate does it take before the posterior peak passes 0.6?Hint for 1: 100 sick give 90 true positives, 900 healthy give 81 false positives, so .
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Bayes theorem, the geometry of changing beliefs
A 15-minute visual derivation of Bayes' theorem by counting people in a population. The picture sticks for life.
Seeing Theory
A visual introduction to probability and statistics with interactive animations.
Think Bayes (2nd edition)
Bayesian statistics taught through Python code rather than calculus. Free to read online, with runnable notebooks.
Conditional Probability, Explained Visually
Balls falling through shelves make conditional probability something you can watch.
Stat 110: Probability
A legendary probability course with free lectures, a free textbook and problem sets.
Probabilistic Machine Learning
A comprehensive two-volume reference viewing ML through probability. Free drafts online.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/math/bayes-theorem.md