A medical test is built for a condition that person in has. The test catches of the people who have the condition, and clears of the people who do not. You take the test and it comes back positive. How likely is it that you have the condition?
Take a moment and guess. The answer is about . This lesson shows why, using counts of people you can check by hand. It then turns the counting into a formula, Bayes’ theorem, which says how a probability should change when evidence arrives. That is the rule behind spam filters, classifiers and the “prior” in P1.D11. All numbers about tests in this lesson are made up for teaching. They are not the numbers of any real test.
Three numbers that describe a test
Call the condition (for “has the condition”) and write for “does not have it”. A test result is positive () or negative (). Three numbers describe the situation:
- The prevalence (also called the base rate) is the share of people who have the condition: .
- The sensitivity is the chance that a person who has the condition tests positive: . It is also called the true positive rate. In machine learning the same number is called recall (P3.A9).
- The specificity is the chance that a person who does not have the condition tests negative: . Its complement, specificity, is the false positive rate, here .
None of the three is the number you want. You want : given a positive result, how likely is the condition? Sensitivity points the other way: given the condition, how likely is a positive result?
Count 1000 people
Instead of multiplying probabilities, count people. Picture people chosen at random.
- Prevalence : people have the condition and do not.
- Of the who have it, test positive: true positives, and false negative.
- Of the who do not, test positive: false positives, and true negatives.
Now look only at the people who tested positive. There are of them, and only have the condition:
Only about one positive result in twelve is a true one. Yet the test is right for of the people. A test can be right of the time overall and still give mostly wrong positives.
The widget draws the people. Move the sliders and watch the groups change.
What to try:
- The default (, , ). The pink squares with a filled mark are the true positives. The blue filled circles, of them, are the false alarms.
- Show only the positives. The grid fades the negatives and what is left is the whole world of a person who tested positive: people. Learning the result shrinks the group you are in, and the probability you want is the share of that smaller group that has the condition. That is conditioning (P1.D5).
- Raise the prevalence to : the posterior becomes . At it is . With a common condition, a positive is convincing.
- Improve one thing at a time at . Raising the sensitivity from to lifts the posterior only from to . Raising the specificity from to lifts it to . The false positives, which come from the big healthy group, are what limit it.
- Set the specificity to . The exact expected count of false positives is , which is not a whole number of people. The grid shows marks, rounded so the four groups still add up to , and the readouts keep the exact numbers.
- Set sensitivity and specificity . Nobody tests positive, so there is nothing to condition on and is undefined. The widget says so.
Why the posterior is low: the base-rate fallacy
The sick group is small ( people) and the healthy group is large (). A false positive rate of sounds small, but applied to people it gives false alarms, while the high sensitivity applied to only people gives real detections. The false alarms win because there are so many more chances for them.
Ignoring the starting proportion, the base rate, and answering with the test’s accuracy alone is called the base-rate fallacy. The base rate is the probability you had before the test, and it must be combined with the test result, not replaced by it. The next sections do that with a formula.
From counts to a formula
Three results from P1.D5 are all that is needed. Here is a one-line reminder of each.
- Conditional probability: , the share of the outcomes in that are also in (defined when ).
- The product rule: . The same event can be split the other way around, so also .
- The law of total probability: if the events do not overlap and together cover every outcome, then .
Now write the event “ and ” both ways with the product rule:
Divide both sides by and you have Bayes’ theorem:
Here is a hypothesis (a guess about the world, such as “this person has the condition”) and is the evidence (what you observed, such as “the test is positive”). It needs . Each part has a name:
- The prior : how probable was before you saw .
- The likelihood : how probable the evidence is if were true. It is a probability of the evidence, not of the hypothesis. Seen as a function of with fixed, the likelihoods do not have to add up to .
- The evidence : how probable is overall. If the hypotheses are all the possibilities, it is the total probability . It is also called the marginal likelihood or the normalizing constant, because it makes the posteriors add up to .
- The posterior : how probable is after seeing .
In words: posterior likelihood prior evidence. Beliefs are updated when evidence arrives, as P1.D1 promised, and this is the rule for doing it.
For the test, is and is . The evidence needs the two ways to test positive:
These are the counting numbers divided by : true positives, and positives in all. The counts and the formula are the same calculation. Counting people just shows each step as something you can see.
The same formula gives the chance of the condition after a negative result. The false negatives are person, and the negatives are people, so . A negative result here is very reassuring.
Do not swap the two conditionals
and are different numbers, and sometimes very different. Two everyday examples: in most places most rainy days are cloudy, but most cloudy days are not rainy; most professional basketball players are tall, but very few tall people are professional basketball players. In our test:
- (sensitivity): given the condition, a positive result is likely.
- (the positive predictive value, PPV): given a positive result, the condition is unlikely.
Two more numbers complete the picture: the specificity , and the negative predictive value . The first of each pair describes the test; the second describes what a result means for a person, and it also depends on the prevalence.
The prosecutor’s fallacy is this swap in a courtroom. Suppose a trace left at a crime matches the suspect, and a random innocent person would match with probability in . That says . It does not say . To see the difference, count. Take a city of people where exactly one is guilty, the guilty person certainly matches, everyone was equally likely to be the culprit before the evidence, and the match is the only evidence. About innocent people will match as well, so
Real cases have other evidence and different numbers; the point is that the probability of the evidence given innocence and the probability of innocence given the evidence are different quantities, linked by the prior.
The odds form
There is a version of Bayes’ theorem that is easy to compute by hand. The odds of an event with probability are , often written as a ratio: has odds , read “one to ninety-nine”. A probability of has odds .
Write Bayes’ theorem for and for its complement and divide the first by the second. The evidence is the same in both, so it cancels:
The likelihood ratio (also called the Bayes factor) says how many times more likely the evidence is if is true than if it is false. For a positive result it is sensitivity divided by the false positive rate: . For a negative result it is . In the example:
- Positive result: prior odds , times , give posterior odds . As a probability, . This matches.
- Negative result: times gives , a probability of . This matches too.
To turn odds back into a probability, use .
The odds form shows two things at once. The likelihood ratio belongs to the test: it does not depend on the prevalence. A ratio of is strong evidence, yet it only turns odds of into , because it multiplies what you already believed. The posterior needs both.
Intuition
Think of the evidence as a filter on the group of people. Before the test, everyone is possible. After a positive result, only the people who tested positive remain, and the posterior is the share of them who have the condition. The prior decides how many sick and how many healthy people there are to begin with; the likelihoods decide how many of each survive the filter.
Another picture is a tug of war. The prior odds pull one way and the likelihood ratio multiplies them: evidence that is times more likely under multiplies the odds by . Strong evidence can overcome a weak prior, and a strong prior can survive weak evidence. The picture breaks when two pieces of evidence share a cause (see updating twice, below): multiplying by both ratios then counts the same information twice.
Math
For a hypothesis and evidence with :
For hypotheses that do not overlap and together cover everything,
where adds over all hypotheses.
The denominator does not depend on , so
The symbol means “is proportional to”: multiply every term by the same number and the posteriors add up to . The odds form for two hypotheses is
Code
The posterior over several hypotheses is the prior times the likelihood, divided by its sum. In NumPy:
import numpy as np
def update(prior, likelihood):
unnormalized = np.asarray(prior) * np.asarray(likelihood)
return unnormalized / unnormalized.sum() # the sum is the evidence
# D = has the condition, then D^c = does not. Evidence: a positive test.
print(update([0.01, 0.99], [0.9, 0.1])) # about [0.0833, 0.9167]Updating twice
What if you take a second test and it is also positive? Yesterday’s posterior becomes today’s prior. After the first positive result the probability of the condition is , odds . Multiply by the likelihood ratio again: odds , and the probability is .
The counts agree. Give a second, identical test to the people who tested positive: of the who have the condition, test positive again, and of the who do not, do. So . The widget’s “Test the positives a second time” shows these numbers; the counts are expected values, so they need not be whole.
This calculation assumes that given the condition status, the two results are independent: among people who have the condition, one test result tells nothing more about the other, and the same holds among people who do not. This is called conditional independence, and it is not the same as the two results being independent overall (they are not: a positive first result makes a second positive more likely, because it makes the condition more likely). It can fail. If the same feature of a person causes a false positive in both tests, the second positive is less convincing than the calculation says, and the true probability is lower than .
With the assumption, results simply multiply the odds, in any order:
Multiplication does not care about order, so it does not matter which test you look at first. A positive followed by a negative gives : back to the prior, because for this test the sensitivity equals the specificity, so and the two results cancel exactly. For a test whose two likelihood ratios do not multiply to , they would not cancel. The same multiplying of likelihoods returns in naive Bayes, below.
Several hypotheses
Bayes’ theorem is not limited to yes or no. A bag holds three coins: a fair coin (), a heads-biased coin () and a tails-biased coin (). You pull one out at random, so each coin has prior , and you flip it twice. You get two heads. Which coin is it?
For each coin, multiply the prior by the likelihood of the evidence “two heads”:
- Fair: likelihood ; prior likelihood .
- Heads-biased: likelihood ; prior likelihood .
- Tails-biased: likelihood ; prior likelihood .
The three products add up to . That sum is the evidence . Divide each product by it:
- Fair: .
- Heads-biased: .
- Tails-biased: .
The order of work is worth seeing. You can multiply prior by likelihood first and divide at the end, once; that is what “posterior is proportional to prior times likelihood” means in practice. The likelihoods do not add up to , and they should not: they answer the question “how likely is this evidence under each hypothesis?” three separate times.
The prior matters. If the bag held mostly fair coins, with priors , and , the same two heads would give , and : the fair coin stays the most likely, since it was so common to begin with.
Updating one flip at a time gives the same answer. Start from the posteriors after two heads (, , ) and flip a tail. The likelihoods of a tail are , , , and after normalizing, the posteriors become , and . Updating on all three flips in one go (heads, heads, tails) gives these same numbers.
Bayes’ theorem in machine learning
A classifier’s output is meant to be a posterior
In classification, the hypothesis is the class and the evidence is the input (the features). The quantity a classifier estimates is the posterior , and Bayes’ theorem relates it to two other things:
Here is the class prior (how common each class is) and is the likelihood of the features within the class. Some models estimate those two parts and apply Bayes’ theorem, which is how naive Bayes works (P3.B2). Others, such as logistic regression and neural networks, estimate directly (P3.A7). Either way, the probability a classifier reports is meant to be this posterior. Whether it matches how often the model is right is a separate question, called calibration (P3.A10).
A spam filter. Suppose, for illustration, that of email is spam, and the word “free” appears in of spam and in of other email. Then
If only of email were spam, the numerator would be and the evidence , so the same word would give about . The evidence is the same; the prior is not. A real filter looks at many words at once. Naive Bayes multiplies the likelihoods of the words, as if the words were independent given the class. That assumption is rarely exactly true, which is why it is called naive; P3.B2 builds the filter.
Base rates, precision and recall
The medical test is a classifier with two classes, and its numbers have ML names. Recall is the sensitivity, . Precision is the positive predictive value, : a posterior (P3.A9 defines the confusion matrix and the rest).
For a classifier with recall and a false positive rate of , precision depends on how common the positive class is:
- Positives are of the data: precision .
- Positives are of the data: precision .
The recall and the false positive rate did not change; only the share of positives did. So a precision measured on a balanced test set does not carry over to data where the positive class is rare. In the case, cutting the false positive rate to lifts precision to . Another trap is accuracy: a model that says “negative” for everyone is accurate when of the data is positive, and useless. The base rate also changes what a good decision threshold is (P3.A10 covers class imbalance).
Parameters have posteriors too
The hypothesis does not have to be a class. It can be the value of a model’s parameters , and the evidence can be the training data:
The likelihood says how well the parameters explain the data, and the prior says which parameters you considered plausible beforehand. Maximum likelihood (P1.D10) picks the parameters that maximize the likelihood alone. MAP estimation (P1.D11) maximizes likelihood times prior, and a prior that prefers small weights turns out to act like a regularization penalty. The width of the posterior also says how sure you are about the parameters. P1.D10 and P1.D11 develop this; here it is only the same formula in a new place.
Go deeper Bayesian and frequentist views
Two schools differ on what probability means and where priors come from. A frequentist takes probability to be a long-run frequency (P1.D1). Parameters, such as the true fairness of a coin, are fixed unknown numbers, so a probability statement about a parameter has no frequency reading. Frequentist methods give estimates, confidence intervals and p-values (P1.D13). A Bayesian takes probability to be a degree of belief, so a parameter can have a probability distribution, and the posterior is the result of the analysis.
Both accept Bayes’ theorem, because it follows from the rules of probability. The medical example uses only frequencies, so a frequentist would compute exactly the same . The disagreement starts when the prior is a belief and not a measured frequency: critics say it adds subjectivity, supporters say the assumption is then stated openly. With a lot of data, and a prior that does not rule anything out, the posterior is often dominated by the data, so reasonable priors lead to similar answers.
Go deeper A coin's bias with a Beta prior
Suppose the unknown is a coin’s heads probability , any number between and . A convenient prior is the Beta distribution , whose density is proportional to . With this is flat: every is equally plausible.
After heads and tails, the likelihood of the flips is proportional to . Multiply prior by likelihood and the exponents add:
which is . The posterior is in the same family as the prior, so updating only adds the counts. The posterior mean is . From a flat prior, heads and tail give with mean , a little below the raw fraction : the prior acts like one imaginary head and one imaginary tail. This is Laplace’s rule of succession: after flips.
For a continuous unknown, the evidence becomes an integral over and the probabilities become densities, but the shape of Bayes’ theorem is the same.
Go deeper The same classifier on a different base rate
Suppose a classifier was trained on balanced data ( positive), is well calibrated there, and says a case is positive with probability , which is odds . Deploy it where only of cases are positive. If the likelihoods stay the same and only the class prior changes (a situation called prior shift or label shift), the odds change by the ratio of the prior odds:
So the same score now means a probability of . This follows from Bayes’ theorem for the two classes: the likelihood terms cancel and only the priors differ. Two assumptions matter: the must be a well-calibrated probability on the balanced data (P3.A10), and the likelihoods must really stay the same. If the data themselves change (different people, different sensors), the likelihoods change too, and this correction is not enough.
Try it: counting people, updating beliefs
The first cell redoes the medical example three ways: counts, the formula, and the odds form, then a second test, and finally a simulation of random people (seed ), whose fractions come out close to the exact values but not equal to them. The second cell updates the three coins (all at once and one flip at a time), computes the spam posterior at two priors, and shows precision for a fixed classifier as the share of positives changes. Predict first: what happens to precision at positives?
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
With these settings the first cell prints , , and and the posterior ; the simulated fractions are near and and change a little with the seed. Challenge: in the widget at prevalence , find a sensitivity and a specificity (whole percents) that make a positive result at least likely.
Common mistakes
Check your understanding
A condition has prevalence . A test has sensitivity and specificity . Of the people who test positive, about what share have the condition?
Of people, have the condition and of them test positive. Of the without it, , which is , also test positive. So of positives are real, about . The value is the sensitivity, the chance of a positive result given the condition. The value is the specificity. The value is the prior, the probability before the test.
The prior odds of a hypothesis are , and the evidence is times as likely if the hypothesis is true as if it is false. What is the posterior probability?
Posterior odds are , which is a probability of . The value is the prior probability, before using the evidence. The value is , which comes from treating the likelihood ratio as odds and forgetting the prior. The value is the probability of the complement.
In Bayes' theorem for , which quantity is the likelihood?
The likelihood is the probability of the evidence if the hypothesis is true: how often the word appears in spam. The probability of spam given the word is the posterior, the quantity being computed. The overall chance of spam is the prior. The overall chance of the word is the evidence, which normalizes the result.
The prior odds are . Two independent positive tests (independent given the condition status) each have likelihood ratio . What is the probability of the condition after both?
The odds become times , which is , and . The value would be , the chance that a person with the condition tests positive twice, and not the chance that a person with two positives has it. The value counts only the first test. The value is the sensitivity.
A classifier with a fixed recall and a fixed false positive rate is moved from a test set with positives to data where only are positive, and the features of each class look the same as before. What happens?
Recall is a probability given the positive class, and the false positive rate is a probability given the negative class, so neither depends on how many of each there are. Precision is the share of predicted positives that are real, so with the same false positive rate applied to far more negatives, false positives pile up and precision drops. For recall and false positive rate it falls from to .
Exercises
- A condition has prevalence . A test has sensitivity and specificity . For people, find the expected number of true positives, false negatives, false positives and true negatives, and .
Show answer
Of the , have the condition: true positives and false negatives. Of the without it, are false positives and true negatives. . - For the lesson’s main example (, , ), find .
Show answer
. By formula: . - A test has sensitivity and specificity . Find and , then the probability of the condition after a positive result when the prior is .
Show answer
and . Prior odds ; times gives , a probability of . - In the three-coin problem the flips so far are heads, heads, and then you flip a tail. Starting from the posteriors after two heads (, , ), find the new posteriors.
Show answer
Multiply by the tail likelihoods , , : the products are proportional to , , , which add up to . The posteriors are , and . - In a town of people, a trace matches an innocent person with probability . One person is guilty and certainly matches, and the match is the only evidence. What is ?
Show answer
About innocent people are expected to match, plus the guilty one: . The match is the only evidence and every person is equally likely a priori, which are the assumptions behind this. - Half of email is spam. The word “winner” appears in of spam and in of other email. What is ?
Show answer
. - A spam filter is tested on emails, of which are spam. It flags of the spam and also of the legitimate emails. Find its recall and precision.
Show answer
Recall . Precision . The false positive rate is . - A test has sensitivity and specificity both equal to , and the prevalence is . What is ?
Show answer
Of people, have the condition and test positive; of the without it, also test positive. So , even for a test. - A test has sensitivity and specificity . What is , and what does a positive result do to the probability of the condition?
Show answer
. The odds are multiplied by , so the posterior equals the prior: a positive result tells you nothing. The test is positive equally often with and without the condition. - The prior probability of a condition is , and two independent positive tests (independent given the status) each have . Find the posterior.
Show answer
Prior odds , times , give , a probability of . - A coin’s heads probability has a prior. You see heads and tail. What is the posterior, and its mean?
Show answer
, with mean .
Next: P1.D10 maximizes the likelihood to fit a model’s parameters, and P1.D11 keeps the prior and gets MAP estimation. P1.D13 asks how often a test result is fooled by chance. In Part 3, naive Bayes (P3.B2) builds a spam filter from the formulas here, and evaluation metrics and calibration (P3.A9, P3.A10) show how base rates change what precision and a predicted probability mean.