Sub topic 2
Bayes' theorem: priors, likelihoods, and posteriors
This chapter assumes you know what a conditional probability is, P(A | B), and what a labeled classification dataset looks like. It also assumes you can read short Python functions. Here you will turn the definition of conditional probability into Bayes' theorem. You will learn what each term means for a classifier and how to compute a posterior by hand and in code. The next chapters build the naive Bayes model on top of this.
From conditional probability to Bayes' theorem
The joint probability of two events can be factored in two ways:
P(A, B) = P(A | B) * P(B)P(A, B) = P(B | A) * P(A)
Both expressions equal the same quantity. Set them equal and divide by P(B), which must be greater than zero:
P(A | B) = P(B | A) * P(A) / P(B)That is Bayes' theorem. It reverses the direction of conditioning. If you know how likely the evidence B is when A is true, and you know how common A is, you can compute how likely A is once you have seen B.
The four terms
For classification, replace A with a class label y and B with an observed feature vector x. The theorem becomes:
P(y | x) = P(x | y) * P(y) / P(x)| Term | Symbol | Meaning in a classifier | Column |
|---|---|---|---|
| Prior | `P(y)` | How common each class is before you look at the features | |
| Likelihood | `P(x | y)` | How probable these features are, assuming the class is `y` |
| Evidence | `P(x)` | How probable these features are across all classes | |
| Posterior | `P(y | x)` | How probable each class is after seeing the features |
The likelihood is a function of x for a fixed class. It is not the probability that the class is y. Mixing up P(x | y) and P(y | x) is the most common error with this theorem.
The evidence is not an extra quantity you must estimate. It follows from the law of total probability:
P(x) = sum over all classes c of P(x | c) * P(c)So the evidence is the sum of the numerators over every class. Dividing by it rescales the numerators so the posteriors add up to 1.
A worked example: one word in an email
Suppose 40% of your email is spam, so P(spam) = 0.4 and P(ham) = 0.6. You count how often the word "free" appears. It shows up in 50% of spam emails and 5% of ham emails. You see an email containing "free". What is P(spam | free)?
Compute the numerator for each class:
- Spam:
0.5 * 0.4 = 0.20 - Ham:
0.05 * 0.6 = 0.03
The evidence is the sum: 0.20 + 0.03 = 0.23. Divide each numerator by it:
P(spam | free) = 0.20 / 0.23 ≈ 0.870P(ham | free) = 0.03 / 0.23 ≈ 0.130
One word moved the spam probability from 0.4 to about 0.87. The word is informative because its likelihood differs a lot between the classes.
The same calculation in code
The function below takes a prior and a likelihood for each class and returns the posteriors.
def posterior(priors, likelihoods):
"""Return P(class | evidence) for each class.
priors: dict mapping class -> P(class)
likelihoods: dict mapping class -> P(evidence | class)
"""
scores = {c: likelihoods[c] * priors[c] for c in priors}
evidence = sum(scores.values())
return {c: s / evidence for c, s in scores.items()}
priors = {"spam": 0.4, "ham": 0.6}
p_free = {"spam": 0.5, "ham": 0.05}
result = posterior(priors, p_free)
print({c: round(p, 4) for c, p in result.items()})The output is {'spam': 0.8696, 'ham': 0.1304}. The function never needs the evidence as an input. It builds the evidence from the scores.
Updating with more evidence
Posteriors can serve as the prior for the next piece of evidence. Suppose the same email also contains "meeting". Assume P(meeting | spam) = 0.02 and P(meeting | ham) = 0.2. Reuse the function with the posterior from the last step as the new prior:
priors = {"spam": 0.4, "ham": 0.6}
p_free = {"spam": 0.5, "ham": 0.05}
p_meeting = {"spam": 0.02, "ham": 0.2}
after_free = posterior(priors, p_free)
after_meeting = posterior(after_free, p_meeting)
print({c: round(p, 4) for c, p in after_meeting.items()})The output is {'spam': 0.4, 'ham': 0.6}. The two words cancel each other exactly, and the email is back at the original prior. "Free" multiplies the odds toward spam by 10, and "meeting" multiplies them toward ham by 10.
This sequential update is only valid if the words are conditionally independent given the class. Without that, P(meeting | spam) would have to be conditioned on having already seen "free". That assumption is the "naive" part of naive Bayes, and a later chapter covers it.
Priors matter: the base rate effect
A strong likelihood does not guarantee a high posterior if the prior is small. Consider a screening test for a condition that affects 1% of people. The test detects it 95% of the time, and it gives a false positive for 5% of healthy people.
- Condition present:
0.95 * 0.01 = 0.0095 - Condition absent:
0.05 * 0.99 = 0.0495 - Evidence:
0.0095 + 0.0495 = 0.059 - Posterior:
0.0095 / 0.059 ≈ 0.161
A positive result gives only about a 16% chance of having the condition. Most positives come from the large healthy group. Ignoring this is called base rate neglect. In classification, the prior pulls predictions toward the common class, which helps on balanced data and can hurt when you care about a rare class.
Common errors
- Swapping the conditional.
P(spam | free)is notP(free | spam). In the example they are 0.87 and 0.5. - Treating likelihoods as probabilities of the class. Likelihoods across classes do not need to sum to 1. In the example,
0.5 + 0.05 = 0.55. - Forgetting the prior. Comparing only
P(x | y)across classes gives the maximum likelihood class. It matches the Bayes answer only when the priors are equal. - Dividing by the wrong evidence. The evidence sums over all classes, not just the ones you are comparing in your head.
- Zero likelihoods. If
P(x | y) = 0for some class, that class gets a posterior of exactly 0, whatever the prior is. Later chapters handle this with smoothing.
Why this matters for naive Bayes
A classifier built on Bayes' theorem picks the class with the highest posterior. In practice that means comparing P(x | y) * P(y) across classes. The prior is easy to estimate by counting class frequencies. The likelihood P(x | y) is the hard part when x has many features, because the number of feature combinations explodes. The conditional independence assumption in the coming chapters addresses exactly this problem.
Exercise
A factory has two machines. Machine A makes 70% of the items and 2% of its items are defective. Machine B makes 30% of the items and 5% of its items are defective. An item is picked at random and is defective. What is the probability it came from machine B?
Show answer
Numerators: A is 0.02 0.7 = 0.014, and B is 0.05 0.3 = 0.015. The evidence is 0.014 + 0.015 = 0.029. So P(B | defective) = 0.015 / 0.029 ≈ 0.517. Machine B makes fewer items, but its higher defect rate makes it slightly more likely than not to be the source.
Exercise
In the spam example, suppose the prior were 50% spam and 50% ham, with the same likelihoods for "free" (0.5 and 0.05). Without running code, what is P(spam | free)?
Show answer
With equal priors, the numerators are 0.5 0.5 = 0.25 for spam and 0.05 0.5 = 0.025 for ham. The evidence is 0.275, so P(spam | free) = 0.25 / 0.275 ≈ 0.909. This is the likelihood ratio of 10 applied to even odds, which gives odds of 10 to 1.