Sub topic 1
Refresher: conditional probability
Naive Bayes is built from conditional probabilities. This chapter reviews the one idea the rest of the tutorial depends on: how a probability changes once you know something else is true.
Prerequisites
This chapter assumes you know:
- Basic probability: events, and joint probability (both events happen).
- What supervised classification is: features, labels, and a train/test split.
- Basic Python.
The definition
The conditional probability of event A given event B is the probability that A happens among the cases where B happens. It is written P(A | B). When P(B) > 0:
P(A | B) = P(A, B) / P(B)
Here P(A, B) is the joint probability that both events happen. Conditioning on B shrinks the set of possible outcomes to those where B is true. You then ask what fraction of that smaller set also has A.
A worked example
Suppose a mail archive has 20 emails. Eight are spam and twelve are ham (not spam). The word "free" appears in 6 spam emails and 4 ham emails.
| Row | Contains "free" | No "free" | Total |
|---|---|---|---|
| Spam | 6 | 2 | 8 |
| Ham | 4 | 8 | 12 |
| Total | 10 | 10 | 20 |
From the table:
- P(spam, free) = 6/20 = 0.3
- P(free) = 10/20 = 0.5
- P(spam | free) = 0.3 / 0.5 = 0.6
- P(free | spam) = 6/8 = 0.75
counts = {
("spam", True): 6,
("spam", False): 2,
("ham", True): 4,
("ham", False): 8,
}
total = sum(counts.values())
n_free = sum(n for (label, has_free), n in counts.items() if has_free)
n_spam = sum(n for (label, has_free), n in counts.items() if label == "spam")
n_both = counts[("spam", True)]
p_spam_given_free = (n_both / total) / (n_free / total)
p_free_given_spam = (n_both / total) / (n_spam / total)
print("P(spam | free) =", round(p_spam_given_free, 3))
print("P(free | spam) =", round(p_free_given_spam, 3))The output is 0.6 and 0.75. The two numbers differ because they answer different questions. Naive Bayes classifies with P(class | features), but it is easier to estimate P(features | class) from labeled data. Connecting the two is the job of the next chapter.
Two useful rules
Rearranging the definition gives the product rule:
P(A, B) = P(A | B) · P(B)
Applied to several events, it becomes the chain rule. For three events:
P(A, B, C) = P(A | B, C) · P(B | C) · P(C)
The chain rule is exact. Naive Bayes later simplifies it by assuming each feature depends only on the class. That simplification is where the word "naive" comes from.
Two events are independent when knowing one does not change the other: P(A | B) = P(A). In the example, P(spam) = 0.4 but P(spam | free) = 0.6, so spam and the word "free" are not independent. That dependence is why the word is useful as a feature.
Exercise
In the table above, compute P(ham | no "free") and say whether it is larger or smaller than P(ham).
Show answer
Among the 10 emails without "free", 8 are ham, so P(ham | no free) = 8/10 = 0.8. P(ham) = 12/20 = 0.6, so the conditional probability is larger. Missing the word "free" makes ham more likely.