Sub topic 5
The naive Bayes decision rule
This chapter assumes you know Bayes' theorem, conditional probability, and the idea that a generative classifier models P(x | y) and P(y). Here we combine those pieces into the rule that picks a class.
Starting from Bayes' theorem
For a feature vector x = (x1, ..., xn) and a class y, Bayes' theorem gives the posterior:
P(y | x) = P(x | y) * P(y) / P(x)To classify, we want the class with the highest posterior. P(x) is the same for every class, so it cannot change which class wins. We drop it:
y_hat = argmax_y P(x | y) * P(y)Applying the naive assumption
Modeling the joint likelihood P(x | y) directly needs a parameter for every combination of feature values, which is infeasible for many features. The naive assumption says the features are independent once the class is known, so the joint factors into a product:
P(x | y) = P(x1 | y) * P(x2 | y) * ... * P(xn | y)This gives the naive Bayes decision rule:
y_hat = argmax_y P(y) * product over j of P(xj | y)Each P(xj | y) is a one-feature distribution, which is easy to estimate. Multiplying many small numbers underflows, so in practice we take logarithms. Log is monotonic, so the winner does not change:
y_hat = argmax_y log P(y) + sum over j of log P(xj | y)A worked example
Take the spam and ham word counts from the spine's toy dataset. The vocabulary has 9 words, each class has 6 word tokens, and the smoothing constant is 1. That gives a denominator of 6 + 9 = 15 per class. Both priors are 0.5. Smoothed likelihoods for the document "free meeting now" are:
- Spam: free = 3/15, meeting = 1/15, now = 3/15.
- Ham: free = 1/15, meeting = 3/15, now = 1/15.
import math
prior = {"spam": 0.5, "ham": 0.5}
likelihood = {
"spam": {"free": 3 / 15, "meeting": 1 / 15, "now": 3 / 15},
"ham": {"free": 1 / 15, "meeting": 3 / 15, "now": 1 / 15},
}
doc = ["free", "meeting", "now"]
scores = {
c: math.log(prior[c]) + sum(math.log(likelihood[c][w]) for w in doc)
for c in prior
}
print(scores)
print(max(scores, key=scores.get))The scores are about -6.62 for spam and -7.72 for ham, so the rule predicts spam. Two spam-leaning words ("free" and "now") outweigh one ham-leaning word ("meeting").
Common errors
- Comparing raw scores as probabilities. The scores are unnormalized, and they only rank the classes.
- Forgetting the prior. With imbalanced classes, dropping
log P(y)biases predictions toward the rare class. - Leaving a zero likelihood in place. A single
P(xj | y) = 0makes the product zero, orlog 0undefined. Smoothing, covered in a later chapter, prevents this.
Exercise
A document scores log P(spam) + sum of log likelihoods = -10.2 for spam and -9.7 for ham. Which class does naive Bayes predict, and why is dropping P(x) safe?
Show answer
It predicts ham, because -9.7 is higher than -10.2. Dropping P(x) is safe because P(x) is identical for every class, so it scales all posteriors equally and cannot change which class has the maximum.