Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 1: Math FoundationsProbability and Statistics

Bayes' theorem

P1.D645 min●●○ IntermediateReviewed Dec 1, 2026

Why this matters for machine learning

Bayes' theorem turns “how likely is this evidence if the hypothesis is true” into “how likely is the hypothesis, given the evidence”. Every classifier output, spam filter and parameter estimate answers the second question.

  • Naive Bayes classifies an email or document by multiplying the prior probability of each class by the likelihood of the words in it. (P3.B2: Naive Bayes, coming soon)
  • A classifier's output is meant to estimate the posterior probability of each class given the input, though raw scores are not always well calibrated. (P3.A7: Logistic regression, coming soon)
  • Precision is the posterior probability that a predicted positive is really positive, so it drops when the positive class is rare. Accuracy, precision and recall must be read together with the class balance. (P3.A9: Evaluation metrics, coming soon)
  • Class imbalance changes the base rate, and with it how a classifier's scores should be turned into decisions and probabilities. (P3.A10: Calibration and class imbalance, coming soon)
  • A prior times a likelihood gives a posterior over a model's parameters. Maximum likelihood ignores the prior, and MAP estimation keeps it, which acts like a regularizer. (P1.D11: MAP estimation and priors)

Before this: Probability basics, Joint, marginal and conditional probability

After this lesson you can

  • Derive Bayes' theorem from the product rule and name its parts: the prior P(H)\mathbb{P}(H), the likelihood P(E∣H)\mathbb{P}(E\mid H), the evidence P(E)\mathbb{P}(E) (by the law of total probability) and the posterior P(H∣E)\mathbb{P}(H\mid E)
  • Turn a prevalence, a sensitivity and a specificity into counts of 1000 people, compute P(condition∣positive)\mathbb{P}(\text{condition}\mid\text{positive}), and explain why it is low when the condition is rare (the base-rate fallacy)
  • Update with the odds form (posterior odds == prior odds ×\times likelihood ratio), with two independent results, and with several hypotheses (posterior ∝\propto prior ×\times likelihood, then normalize)
  • Explain why P(E∣H)\mathbb{P}(E\mid H) and P(H∣E)\mathbb{P}(H\mid E) differ, and how a classifier's posterior, its precision and its recall depend on the base rate

A medical test is built for a condition that 11 person in 100100 has. The test catches 90%90\% of the people who have the condition, and clears 90%90\% 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 8%8\%. 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 DD (for “has the condition”) and write DcD^c 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: P(D)=0.01\mathbb{P}(D)=0.01.
  • The sensitivity is the chance that a person who has the condition tests positive: P(+∣D)=0.9\mathbb{P}(+\mid D)=0.9. 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: P(−∣Dc)=0.9\mathbb{P}(-\mid D^c)=0.9. Its complement, 1−1- specificity, is the false positive rate, here 0.10.1.

None of the three is the number you want. You want P(D∣+)\mathbb{P}(D\mid +): 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 10001000 people chosen at random.

  • Prevalence 1%1\%: 1010 people have the condition and 990990 do not.
  • Of the 1010 who have it, 90%90\% test positive: 99 true positives, and 11 false negative.
  • Of the 990990 who do not, 10%10\% test positive: 9999 false positives, and 891891 true negatives.

Now look only at the people who tested positive. There are 9+99=1089+99=108 of them, and only 99 have the condition:

P(D∣+)=99+99=9108=112≈8.3%.\begin{aligned} \mathbb{P}(D\mid +)&=\frac{9}{9+99}\\ &=\frac{9}{108}=\frac1{12}\approx8.3\%. \end{aligned}

Only about one positive result in twelve is a true one. Yet the test is right for 9+891=9009+891=900 of the 10001000 people. A test can be right 90%90\% of the time overall and still give mostly wrong positives.

The widget draws the 10001000 people. Move the sliders and watch the groups change.

1000 people and one medical test

Squares have the condition, circles do not. Filled marks tested positive, hollow marks tested negative. The groups run in reading order: sick people first, then the rest.

  • Has it, tests positive (true positive) 9 9
  • Has it, tests negative (false negative) 1 1
  • Does not have it, tests positive (false positive) 99 99
  • Does not have it, tests negative (true negative) 891 891

“Expected” is the exact expected count out of 1000 people and “Drawn” is the number of marks in the grid; here all four are whole numbers, so the grid matches them exactly. The probabilities below use the exact counts.

P(condition | positive) = true positives / all positives = 9 / 108 = 8.3% P(condition | negative) = false negatives / all negatives = 1 / 892 = 0.11% Odds form: prior odds 0.0101 × likelihood ratio (sensitivity / (1 − specificity)) 9 = posterior odds 0.091.
Of the 108 people expected to test positive, 9 have the condition: P(condition | positive) = 8.3%, against 1% before the test. False positives (99) outnumber true positives (9), because more people are without the condition than with it, so most positives are false alarms. After a negative result the chance is 0.11%.
One thousand people, a condition and a test. Squares have the condition and circles do not; filled marks tested positive and hollow marks tested negative. Sliders set the prevalence, the sensitivity and the specificity. The counts list gives the exact expected number in each group and the number of marks drawn; the readouts give P(condition | positive) and P(condition | negative) and the odds form. “Show only the positives” fades the negatives, “Group by test result” puts all the positives together, and “Test the positives a second time” adds a second, independent test given to the people who tested positive.

What to try:

  • The default (1%1\%, 90%90\%, 90%90\%). The pink squares with a filled mark are the 99 true positives. The blue filled circles, 9999 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: 108108 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 10%10\%: the posterior becomes 50%50\%. At 50%50\% it is 90%90\%. With a common condition, a positive is convincing.
  • Improve one thing at a time at 1%1\%. Raising the sensitivity from 90%90\% to 99%99\% lifts the posterior only from 8.3%8.3\% to 9.1%9.1\%. Raising the specificity from 90%90\% to 99%99\% lifts it to 47.6%47.6\%. The false positives, which come from the big healthy group, are what limit it.
  • Set the specificity to 91%91\%. The exact expected count of false positives is 89.189.1, which is not a whole number of people. The grid shows 8989 marks, rounded so the four groups still add up to 10001000, and the readouts keep the exact numbers.
  • Set sensitivity 0%0\% and specificity 100%100\%. Nobody tests positive, so there is nothing to condition on and P(D∣+)\mathbb{P}(D\mid +) is undefined. The widget says so.

Why the posterior is low: the base-rate fallacy

The sick group is small (1010 people) and the healthy group is large (990990). A false positive rate of 10%10\% sounds small, but applied to 990990 people it gives 9999 false alarms, while the high sensitivity applied to only 1010 people gives 99 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: P(A∣B)=P(A∩B)P(B)\mathbb{P}(A\mid B)=\dfrac{\mathbb{P}(A\cap B)}{\mathbb{P}(B)}, the share of the outcomes in BB that are also in AA (defined when P(B)>0\mathbb{P}(B)>0).
  • The product rule: P(A∩B)=P(A∣B) P(B)\mathbb{P}(A\cap B)=\mathbb{P}(A\mid B)\,\mathbb{P}(B). The same event can be split the other way around, so also P(A∩B)=P(B∣A) P(A)\mathbb{P}(A\cap B)=\mathbb{P}(B\mid A)\,\mathbb{P}(A).
  • The law of total probability: if the events H1,…,HkH_1,\dots,H_k do not overlap and together cover every outcome, then P(E)=∑iP(E∣Hi) P(Hi)\mathbb{P}(E)=\sum_i\mathbb{P}(E\mid H_i)\,\mathbb{P}(H_i).

Now write the event “HH and EE” both ways with the product rule:

P(E∣H) P(H)=P(H∩E)=P(H∣E) P(E).\begin{aligned} \mathbb{P}(E\mid H)\,\mathbb{P}(H)&=\mathbb{P}(H\cap E)\\ &=\mathbb{P}(H\mid E)\,\mathbb{P}(E). \end{aligned}

Divide both sides by P(E)\mathbb{P}(E) and you have Bayes’ theorem:

P(H∣E)=P(E∣H) P(H)P(E).\mathbb{P}(H\mid E)=\frac{\mathbb{P}(E\mid H)\,\mathbb{P}(H)}{\mathbb{P}(E)}.

Here HH is a hypothesis (a guess about the world, such as “this person has the condition”) and EE is the evidence (what you observed, such as “the test is positive”). It needs P(E)>0\mathbb{P}(E)>0. Each part has a name:

  • The prior P(H)\mathbb{P}(H): how probable HH was before you saw EE.
  • The likelihood P(E∣H)\mathbb{P}(E\mid H): how probable the evidence is if HH were true. It is a probability of the evidence, not of the hypothesis. Seen as a function of HH with EE fixed, the likelihoods do not have to add up to 11.
  • The evidence P(E)\mathbb{P}(E): how probable EE is overall. If the hypotheses H1,…,HkH_1,\dots,H_k are all the possibilities, it is the total probability ∑iP(E∣Hi) P(Hi)\sum_i\mathbb{P}(E\mid H_i)\,\mathbb{P}(H_i). It is also called the marginal likelihood or the normalizing constant, because it makes the posteriors add up to 11.
  • The posterior P(H∣E)\mathbb{P}(H\mid E): how probable HH is after seeing EE.

In words: posterior == likelihood ×\times prior ÷\div evidence. Beliefs are updated when evidence arrives, as P1.D1 promised, and this is the rule for doing it.

For the test, HH is DD and EE is ++. The evidence needs the two ways to test positive:

P(+)=P(+∣D) P(D)+P(+∣Dc) P(Dc)=0.9⋅0.01+0.1⋅0.99=0.009+0.099=0.108.\begin{aligned} \mathbb{P}(+)&=\mathbb{P}(+\mid D)\,\mathbb{P}(D)\\ &\quad+\mathbb{P}(+\mid D^c)\,\mathbb{P}(D^c)\\ &=0.9\cdot0.01+0.1\cdot0.99\\ &=0.009+0.099=0.108. \end{aligned} P(D∣+)=0.9⋅0.010.108=0.0090.108=112≈0.083.\begin{aligned} \mathbb{P}(D\mid +)&=\frac{0.9\cdot0.01}{0.108}\\ &=\frac{0.009}{0.108}=\frac1{12}\approx0.083. \end{aligned}

These are the counting numbers divided by 10001000: 99 true positives, and 108108 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 11 person, and the negatives are 1+891=8921+891=892 people, so P(D∣−)=1892≈0.11%\mathbb{P}(D\mid -)=\frac1{892}\approx0.11\%. A negative result here is very reassuring.

Do not swap the two conditionals

P(E∣H)\mathbb{P}(E\mid H) and P(H∣E)\mathbb{P}(H\mid E) 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:

  • P(+∣D)=0.9\mathbb{P}(+\mid D)=0.9 (sensitivity): given the condition, a positive result is likely.
  • P(D∣+)≈0.083\mathbb{P}(D\mid +)\approx0.083 (the positive predictive value, PPV): given a positive result, the condition is unlikely.

Two more numbers complete the picture: the specificity P(−∣Dc)=0.9\mathbb{P}(-\mid D^c)=0.9, and the negative predictive value P(Dc∣−)=891/892≈99.9%\mathbb{P}(D^c\mid -)=891/892\approx99.9\%. 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 11 in 10,00010{,}000. That says P(match∣innocent)=0.0001\mathbb{P}(\text{match}\mid\text{innocent})=0.0001. It does not say P(innocent∣match)=0.0001\mathbb{P}(\text{innocent}\mid\text{match})=0.0001. To see the difference, count. Take a city of 1,000,0001{,}000{,}000 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 100100 innocent people will match as well, so

P(guilty∣match)≈11+100≈1%.\mathbb{P}(\text{guilty}\mid\text{match})\approx\frac{1}{1+100}\approx1\%.

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 pp are p1−p\dfrac{p}{1-p}, often written as a ratio: p=1100p=\frac1{100} has odds 1:991:99, read “one to ninety-nine”. A probability of 12\frac12 has odds 1:11:1.

Write Bayes’ theorem for HH and for its complement HcH^c and divide the first by the second. The evidence P(E)\mathbb{P}(E) is the same in both, so it cancels:

P(H∣E)P(Hc∣E)⏟posterior odds=P(H)P(Hc)⏟prior odds×P(E∣H)P(E∣Hc)⏟likelihood ratio.\underbrace{\frac{\mathbb{P}(H\mid E)}{\mathbb{P}(H^c\mid E)}}_{\text{posterior odds}}=\underbrace{\frac{\mathbb{P}(H)}{\mathbb{P}(H^c)}}_{\text{prior odds}}\times\underbrace{\frac{\mathbb{P}(E\mid H)}{\mathbb{P}(E\mid H^c)}}_{\text{likelihood ratio}}.

The likelihood ratio (also called the Bayes factor) says how many times more likely the evidence is if HH is true than if it is false. For a positive result it is sensitivity divided by the false positive rate: LR+=0.90.1=9\mathrm{LR}_+=\dfrac{0.9}{0.1}=9. For a negative result it is LR−=0.10.9=19\mathrm{LR}_-=\dfrac{0.1}{0.9}=\dfrac19. In the example:

  • Positive result: prior odds 1:991:99, times 99, give posterior odds 9:99=1:119:99=1:11. As a probability, 11+11=112\frac{1}{1+11}=\frac1{12}. This matches.
  • Negative result: 1:991:99 times 19\frac19 gives 1:8911:891, a probability of 1892\frac1{892}. This matches too.

To turn odds a:ba:b back into a probability, use aa+b\dfrac{a}{a+b}.

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 99 is strong evidence, yet it only turns odds of 1:991:99 into 1:111:11, 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 108108 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 99 times more likely under HH multiplies the odds by 99. 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 HH and evidence EE with P(E)>0\mathbb{P}(E)>0:

P(H∣E)=P(E∣H) P(H)P(E).\mathbb{P}(H\mid E)=\frac{\mathbb{P}(E\mid H)\,\mathbb{P}(H)}{\mathbb{P}(E)}.

For hypotheses H1,…,HkH_1,\dots,H_k that do not overlap and together cover everything,

P(Hi∣E)=P(E∣Hi) P(Hi)P(E)\begin{aligned} &\mathbb{P}(H_i\mid E)\\ &=\frac{\mathbb{P}(E\mid H_i)\,\mathbb{P}(H_i)}{\mathbb{P}(E)} \end{aligned}

where P(E)=∑jP(E∣Hj) P(Hj)\mathbb{P}(E)=\sum_{j}\mathbb{P}(E\mid H_j)\,\mathbb{P}(H_j) adds over all kk hypotheses.

The denominator does not depend on ii, so

P(Hi∣E) ∝ P(E∣Hi) P(Hi).\mathbb{P}(H_i\mid E)\ \propto\ \mathbb{P}(E\mid H_i)\,\mathbb{P}(H_i).

The symbol ∝\propto means “is proportional to”: multiply every term by the same number and the posteriors add up to 11. The odds form for two hypotheses is

P(H∣E)P(Hc∣E)=P(H)P(Hc)⋅P(E∣H)P(E∣Hc).\begin{aligned} \frac{\mathbb{P}(H\mid E)}{\mathbb{P}(H^c\mid E)}&=\frac{\mathbb{P}(H)}{\mathbb{P}(H^c)}\\ &\quad\cdot\frac{\mathbb{P}(E\mid H)}{\mathbb{P}(E\mid H^c)}. \end{aligned}

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 112\frac1{12}, odds 1:111:11. Multiply by the likelihood ratio 99 again: odds 9:119:11, and the probability is 99+11=45%\frac{9}{9+11}=45\%.

The counts agree. Give a second, identical test to the 108108 people who tested positive: of the 99 who have the condition, 9⋅0.9=8.19\cdot0.9=8.1 test positive again, and of the 9999 who do not, 99⋅0.1=9.999\cdot0.1=9.9 do. So 8.18.1+9.9=8.118=45%\frac{8.1}{8.1+9.9}=\frac{8.1}{18}=45\%. 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 45%45\%.

With the assumption, results simply multiply the odds, in any order:

posterior odds=prior odds×LR1×LR2×⋯\begin{aligned} \text{posterior odds}&=\text{prior odds}\\ &\quad\times\mathrm{LR}_1\times\mathrm{LR}_2\times\cdots \end{aligned}

Multiplication does not care about order, so it does not matter which test you look at first. A positive followed by a negative gives 1:99×9×19=1:991:99\times9\times\frac19=1:99: back to the prior, because for this test the sensitivity equals the specificity, so LR+×LR−=9×19=1\mathrm{LR}_+\times\mathrm{LR}_-=9\times\frac19=1 and the two results cancel exactly. For a test whose two likelihood ratios do not multiply to 11, 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 (P(heads)=0.5\mathbb{P}(\text{heads})=0.5), a heads-biased coin (0.80.8) and a tails-biased coin (0.20.2). You pull one out at random, so each coin has prior 13\frac13, 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 0.5⋅0.5=0.250.5\cdot0.5=0.25; prior ×\times likelihood =13⋅0.25≈0.0833=\frac13\cdot0.25\approx0.0833.
  • Heads-biased: likelihood 0.8⋅0.8=0.640.8\cdot0.8=0.64; prior ×\times likelihood =13⋅0.64≈0.2133=\frac13\cdot0.64\approx0.2133.
  • Tails-biased: likelihood 0.2⋅0.2=0.040.2\cdot0.2=0.04; prior ×\times likelihood =13⋅0.04≈0.0133=\frac13\cdot0.04\approx0.0133.

The three products add up to 0.310.31. That sum is the evidence P(two heads)\mathbb{P}(\text{two heads}). Divide each product by it:

  • Fair: 0.0833/0.31≈26.9%0.0833/0.31\approx26.9\%.
  • Heads-biased: 0.2133/0.31≈68.8%0.2133/0.31\approx68.8\%.
  • Tails-biased: 0.0133/0.31≈4.3%0.0133/0.31\approx4.3\%.

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 0.25+0.64+0.04=0.930.25+0.64+0.04=0.93 do not add up to 11, 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 0.80.8, 0.10.1 and 0.10.1, the same two heads would give 74.6%74.6\%, 23.9%23.9\% and 1.5%1.5\%: 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 (26.9%26.9\%, 68.8%68.8\%, 4.3%4.3\%) and flip a tail. The likelihoods of a tail are 0.50.5, 0.20.2, 0.80.8, and after normalizing, the posteriors become 43.9%43.9\%, 44.9%44.9\% and 11.2%11.2\%. 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 yy and the evidence is the input x\mathbf{x} (the features). The quantity a classifier estimates is the posterior p(y∣x)p(y\mid\mathbf{x}), and Bayes’ theorem relates it to two other things:

p(y∣x)=p(x∣y) p(y)p(x)∝p(x∣y) p(y).\begin{aligned} p(y\mid\mathbf{x})&=\frac{p(\mathbf{x}\mid y)\,p(y)}{p(\mathbf{x})}\\ &\propto p(\mathbf{x}\mid y)\,p(y). \end{aligned}

Here p(y)p(y) is the class prior (how common each class is) and p(x∣y)p(\mathbf{x}\mid y) 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 p(y∣x)p(y\mid\mathbf{x}) 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 20%20\% of email is spam, and the word “free” appears in 30%30\% of spam and in 2%2\% of other email. Then

P(spam∣“free”)=0.30⋅0.200.30⋅0.20+0.02⋅0.80=0.060.076≈78.9%.\begin{aligned} &\mathbb{P}(\text{spam}\mid\text{“free”})\\ &=\frac{0.30\cdot0.20}{0.30\cdot0.20+0.02\cdot0.80}\\ &=\frac{0.06}{0.076}\approx78.9\%. \end{aligned}

If only 1%1\% of email were spam, the numerator would be 0.30⋅0.01=0.0030.30\cdot0.01=0.003 and the evidence 0.003+0.0198=0.02280.003+0.0198=0.0228, so the same word would give about 13.2%13.2\%. 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, P(predicted positive∣positive)\mathbb{P}(\text{predicted positive}\mid\text{positive}). Precision is the positive predictive value, P(positive∣predicted positive)=TP/(TP+FP)\mathbb{P}(\text{positive}\mid\text{predicted positive})=\mathrm{TP}/(\mathrm{TP}+\mathrm{FP}): a posterior (P3.A9 defines the confusion matrix and the rest).

For a classifier with recall 90%90\% and a false positive rate of 10%10\%, precision depends on how common the positive class is:

  • Positives are 1%1\% of the data: precision 8.3%8.3\%.
  • Positives are 50%50\% of the data: precision 90%90\%.

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 1%1\% case, cutting the false positive rate to 1%1\% lifts precision to 9/(9+9.9)≈47.6%9/(9+9.9)\approx47.6\%. Another trap is accuracy: a model that says “negative” for everyone is 99%99\% accurate when 1%1\% 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 θ\boldsymbol{\theta}, and the evidence can be the training data:

p(θ∣data) ∝ p(data∣θ) p(θ).p(\boldsymbol{\theta}\mid\text{data})\ \propto\ p(\text{data}\mid\boldsymbol{\theta})\,p(\boldsymbol{\theta}).

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 8.3%8.3\%. 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 θ\theta, any number between 00 and 11. A convenient prior is the Beta distribution Beta(a,b)\mathrm{Beta}(a,b), whose density is proportional to θa−1(1−θ)b−1\theta^{a-1}(1-\theta)^{b-1}. With a=b=1a=b=1 this is flat: every θ\theta is equally plausible.

After hh heads and tt tails, the likelihood of the flips is proportional to θh(1−θ)t\theta^{h}(1-\theta)^{t}. Multiply prior by likelihood and the exponents add:

p(θ∣flips)∝θa−1+h×(1−θ)b−1+t,\begin{aligned} p(\theta\mid\text{flips})&\propto\theta^{a-1+h}\\ &\quad\times(1-\theta)^{b-1+t}, \end{aligned}

which is Beta(a+h, b+t)\mathrm{Beta}(a+h,\,b+t). The posterior is in the same family as the prior, so updating only adds the counts. The posterior mean is a+ha+b+h+t\dfrac{a+h}{a+b+h+t}. From a flat prior, 33 heads and 11 tail give Beta(4,2)\mathrm{Beta}(4,2) with mean 46=23\frac46=\frac23, a little below the raw fraction 34\frac34: the prior acts like one imaginary head and one imaginary tail. This is Laplace’s rule of succession: h+1n+2\frac{h+1}{n+2} after nn flips.

For a continuous unknown, the evidence P(E)\mathbb{P}(E) becomes an integral over θ\theta 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 (50%50\% positive), is well calibrated there, and says a case is positive with probability 0.90.9, which is odds 9:19:1. Deploy it where only 1%1\% of cases are positive. If the likelihoods p(x∣y)p(\mathbf{x}\mid y) 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:

new odds=old odds×new prior oddsold prior odds=9×199=111.\begin{aligned} \text{new odds}&=\text{old odds}\\ &\quad\times\frac{\text{new prior odds}}{\text{old prior odds}}\\ &=9\times\frac{1}{99}=\frac1{11}. \end{aligned}

So the same score now means a probability of 112≈8.3%\frac1{12}\approx8.3\%. This follows from Bayes’ theorem for the two classes: the likelihood terms cancel and only the priors differ. Two assumptions matter: the 0.90.9 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 1,000,0001{,}000{,}000 random people (seed 00), 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 50%50\% positives?

Try it: the medical test, by counts, formula and odds

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Try it: coins, spam and base rates

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

With these settings the first cell prints 99, 11, 9999 and 891891 and the posterior 0.08330.0833; the simulated fractions are near 0.0830.083 and 0.00110.0011 and change a little with the seed. Challenge: in the widget at prevalence 1%1\%, find a sensitivity and a specificity (whole percents) that make a positive result at least 50%50\% likely.

Common mistakes

Check your understanding

  1. A condition has prevalence 2%2\%. A test has sensitivity 80%80\% and specificity 95%95\%. Of the people who test positive, about what share have the condition?

  2. The prior odds of a hypothesis are 1:41:4, and the evidence is 66 times as likely if the hypothesis is true as if it is false. What is the posterior probability?

  3. In Bayes' theorem for P(spam∣“free”)\mathbb{P}(\text{spam}\mid\text{“free”}), which quantity is the likelihood?

  4. The prior odds are 1:991:99. Two independent positive tests (independent given the condition status) each have likelihood ratio 99. What is the probability of the condition after both?

  5. A classifier with a fixed recall and a fixed false positive rate is moved from a test set with 50%50\% positives to data where only 1%1\% are positive, and the features of each class look the same as before. What happens?

Exercises

  1. A condition has prevalence 5%5\%. A test has sensitivity 99%99\% and specificity 95%95\%. For 10001000 people, find the expected number of true positives, false negatives, false positives and true negatives, and P(D∣+)\mathbb{P}(D\mid +).
    Show answerOf the 10001000, 5050 have the condition: 49.549.5 true positives and 0.50.5 false negatives. Of the 950950 without it, 47.547.5 are false positives and 902.5902.5 true negatives. P(D∣+)=49.549.5+47.5=49.597≈51.0%\mathbb{P}(D\mid +)=\frac{49.5}{49.5+47.5}=\frac{49.5}{97}\approx51.0\%.
  2. For the lesson’s main example (1%1\%, 90%90\%, 90%90\%), find P(D∣−)\mathbb{P}(D\mid -).
    Show answer11+891=1892≈0.11%\frac{1}{1+891}=\frac1{892}\approx0.11\%. By formula: 0.1⋅0.010.892\frac{0.1\cdot0.01}{0.892}.
  3. A test has sensitivity 0.80.8 and specificity 0.950.95. Find LR+\mathrm{LR}_+ and LR−\mathrm{LR}_-, then the probability of the condition after a positive result when the prior is 2%2\%.
    Show answerLR+=0.80.05=16\mathrm{LR}_+=\frac{0.8}{0.05}=16 and LR−=0.20.95=419≈0.21\mathrm{LR}_-=\frac{0.2}{0.95}=\frac4{19}\approx0.21. Prior odds 0.020.98=149\frac{0.02}{0.98}=\frac1{49}; times 1616 gives 16:4916:49, a probability of 1665≈24.6%\frac{16}{65}\approx24.6\%.
  4. 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 (2593\frac{25}{93}, 6493\frac{64}{93}, 493\frac{4}{93}), find the new posteriors.
    Show answerMultiply by the tail likelihoods 0.50.5, 0.20.2, 0.80.8: the products are proportional to 12.512.5, 12.812.8, 3.23.2, which add up to 28.528.5. The posteriors are 2557≈43.9%\frac{25}{57}\approx43.9\%, 128285≈44.9%\frac{128}{285}\approx44.9\% and 32285≈11.2%\frac{32}{285}\approx11.2\%.
  5. In a town of 100,000100{,}000 people, a trace matches an innocent person with probability 11000\frac1{1000}. One person is guilty and certainly matches, and the match is the only evidence. What is P(guilty∣match)\mathbb{P}(\text{guilty}\mid\text{match})?
    Show answerAbout 99.99999.999 innocent people are expected to match, plus the guilty one: 11+99.999≈0.99%\frac{1}{1+99.999}\approx0.99\%. The match is the only evidence and every person is equally likely a priori, which are the assumptions behind this.
  6. Half of email is spam. The word “winner” appears in 40%40\% of spam and in 1%1\% of other email. What is P(spam∣“winner”)\mathbb{P}(\text{spam}\mid\text{“winner”})?
    Show answer0.4⋅0.50.4⋅0.5+0.01⋅0.5=0.20.205=4041≈97.6%\frac{0.4\cdot0.5}{0.4\cdot0.5+0.01\cdot0.5}=\frac{0.2}{0.205}=\frac{40}{41}\approx97.6\%.
  7. A spam filter is tested on 10001000 emails, of which 5050 are spam. It flags 4545 of the spam and also 1919 of the 950950 legitimate emails. Find its recall and precision.
    Show answerRecall =4550=90%=\frac{45}{50}=90\%. Precision =4545+19=4564≈70.3%=\frac{45}{45+19}=\frac{45}{64}\approx70.3\%. The false positive rate is 19950=2%\frac{19}{950}=2\%.
  8. A test has sensitivity and specificity both equal to 99%99\%, and the prevalence is 1%1\%. What is P(D∣+)\mathbb{P}(D\mid +)?
    Show answerOf 10001000 people, 1010 have the condition and 9.99.9 test positive; of the 990990 without it, 9.99.9 also test positive. So 9.99.9+9.9=50%\frac{9.9}{9.9+9.9}=50\%, even for a 99%99\% test.
  9. A test has sensitivity 30%30\% and specificity 70%70\%. What is LR+\mathrm{LR}_+, and what does a positive result do to the probability of the condition?
    Show answerLR+=0.31−0.7=1\mathrm{LR}_+=\frac{0.3}{1-0.7}=1. The odds are multiplied by 11, so the posterior equals the prior: a positive result tells you nothing. The test is positive equally often with and without the condition.
  10. The prior probability of a condition is 10%10\%, and two independent positive tests (independent given the status) each have LR+=9\mathrm{LR}_+=9. Find the posterior.
    Show answerPrior odds 1:91:9, times 8181, give 81:9=9:181:9=9:1, a probability of 910=90%\frac{9}{10}=90\%.
  11. A coin’s heads probability has a Beta(2,2)\mathrm{Beta}(2,2) prior. You see 55 heads and 11 tail. What is the posterior, and its mean?
    Show answerBeta(2+5, 2+1)=Beta(7,3)\mathrm{Beta}(2+5,\,2+1)=\mathrm{Beta}(7,3), with mean 77+3=0.7\frac{7}{7+3}=0.7.

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.

Key takeaways

  • Bayes' theorem reverses a conditional probability: P(H∣E)=P(E∣H) P(H)P(E)\mathbb{P}(H\mid E)=\dfrac{\mathbb{P}(E\mid H)\,\mathbb{P}(H)}{\mathbb{P}(E)}. It follows from the product rule in two lines. The prior P(H)\mathbb{P}(H) is your probability before the evidence, the likelihood P(E∣H)\mathbb{P}(E\mid H) says how probable the evidence is if HH is true, the evidence P(E)=∑iP(E∣Hi)P(Hi)\mathbb{P}(E)=\sum_i\mathbb{P}(E\mid H_i)\mathbb{P}(H_i) is the total probability of seeing it, and the posterior P(H∣E)\mathbb{P}(H\mid E) is your updated probability.
  • The base-rate fallacy is ignoring the prior. With a condition that 1 in 100 people have, and a test with sensitivity 90%90\% and specificity 90%90\%, a positive result means about 8%8\%, not 90%90\%: out of 1000 people there are 99 true positives and 9999 false positives, because the healthy group is so much bigger. Counting people (natural frequencies) makes this visible.
  • P(E∣H)≠P(H∣E)\mathbb{P}(E\mid H)\ne\mathbb{P}(H\mid E). The sensitivity of a test is not the chance that a positive result is right. Confusing the two is the transposed conditional, and in a courtroom it is called the prosecutor's fallacy.
  • Odds form: posterior odds == prior odds ×\times likelihood ratio. A positive result with sensitivity 0.90.9 and specificity 0.90.9 multiplies the odds by 0.9/0.1=90.9/0.1=9. Independent results (independent given the hypothesis) multiply the odds one after the other, and the order does not matter. With several hypotheses, the posterior is proportional to prior ×\times likelihood; divide by the sum at the end.
  • In machine learning a classifier's output is meant to estimate the posterior p(y∣x)p(y\mid\mathbf{x}) (how well it does is calibration, P3.A10); naive Bayes computes it from p(y)p(y) and p(x∣y)p(\mathbf{x}\mid y). Precision is a posterior, P(positive class∣predicted positive)\mathbb{P}(\text{positive class}\mid\text{predicted positive}), so it falls when the positive class is rare, while recall (the sensitivity) does not. The same rule applied to model parameters gives the posterior over parameters, the starting point of MAP estimation (P1.D11).
Found a mistake? Tell us