Sub topic 5
The naive Bayes decision rule
This chapter assumes you know Bayes' theorem (prior, likelihood, posterior), the idea of conditional independence, and the basics of supervised classification. It also assumes you can read short Python snippets and know what a logarithm does. Here we put those pieces together into the rule a naive Bayes classifier uses to pick a label.
From the posterior to a score
A classifier receives a feature vector x = (x1, x2, ..., xn) and must choose a class y. Bayes' theorem gives the posterior probability of each class:
P(y | x) = P(y) * P(x | y) / P(x)
The prediction is the class with the highest posterior. This is the maximum a posteriori (MAP) rule:
y_hat = argmax over y of P(y | x)
P(x) is the probability of the features regardless of class. It is the same number for every candidate class, so it cannot change which class wins. We can drop it:
y_hat = argmax over y of P(y) * P(x | y)
The remaining product is called the unnormalized posterior, or the score of class y. It no longer sums to 1 across classes, but its ordering is the same as the ordering of the true posteriors.
The expensive term: P(x | y)
The prior P(y) is easy to estimate. It is the share of training rows with each label. The likelihood P(x | y) is the problem. It is the joint distribution of all n features within one class.
With n binary features, a full joint table per class has 2^n - 1 free numbers. For 30 features that is over a billion parameters per class, and almost every combination of feature values never appears in the training data. You cannot estimate a table like that from a realistic dataset.
Applying the naive assumption
Naive Bayes assumes the features are conditionally independent given the class. The chain rule gives an exact factorization:
P(x | y) = P(x1 | y) * P(x2 | x1, y) * ... * P(xn | x1, ..., x(n-1), y)
Under the assumption, each factor ignores the other features:
P(x | y) = P(x1 | y) * P(x2 | y) * ... * P(xn | y)
Substituting this into the score gives the naive Bayes decision rule:
y_hat = argmax over y of P(y) * product over j of P(xj | y)
The parameter count drops from 2^n - 1 to n per class for binary features. Each factor P(xj | y) is a one-dimensional distribution you can estimate from the rows of one class and one feature column.
The assumption is conditional. Features may be strongly correlated overall, for example "free" and "prize" in spam. The rule only treats them as independent once the class is known.
The steps of a prediction
The classifier needs only two kinds of stored numbers: one prior per class and one likelihood per class and feature value. Prediction is a loop over classes, with a loop over features inside it. That costs O(C * n) for C classes and n features.
A worked example
Suppose training gave these priors and word likelihoods, where each likelihood is the probability that a given word appears in a message of that class:
| Class | Prior | P(free \ | y) | P(meeting \ | y) | P(now \ | y) |
|---|---|---|---|---|---|---|---|
| spam | 0.5 | 0.30 | 0.05 | 0.25 | |||
| ham | 0.5 | 0.05 | 0.30 | 0.10 |
For a message containing "free" and "now", the scores are:
- spam:
0.5 * 0.30 * 0.25 = 0.0375 - ham:
0.5 * 0.05 * 0.10 = 0.0025
Spam wins. The scores sum to 0.04, not 1. Dividing each by that sum recovers the posteriors: 0.9375 for spam and 0.0625 for ham. You only need that division if you want probabilities. For the label alone, comparing raw scores is enough.
Writing the rule in code
Multiplying many small probabilities underflows a floating-point number, so implementations add logs instead. Because log is increasing, the argmax is unchanged. The rule becomes:
y_hat = argmax over y of [ log P(y) + sum over j of log P(xj | y) ]
The next chapters cover underflow in detail. This example already uses the log form:
import math
priors = {"spam": 0.5, "ham": 0.5}
likelihood = {
"spam": {"free": 0.30, "meeting": 0.05, "now": 0.25},
"ham": {"free": 0.05, "meeting": 0.30, "now": 0.10},
}
doc = ["free", "now"]
scores = {}
for c in priors:
scores[c] = math.log(priors[c]) + sum(
math.log(likelihood[c][w]) for w in doc
)
best = max(scores, key=scores.get)
print({c: round(s, 4) for c, s in scores.items()})
print("prediction:", best)
# Convert log scores back to posteriors with a stable normalization.
top = max(scores.values())
exp_scores = {c: math.exp(s - top) for c, s in scores.items()}
total = sum(exp_scores.values())
print({c: round(v / total, 4) for c, v in exp_scores.items()})The output is {'spam': -3.2834, 'ham': -5.9914}, then prediction: spam, then {'spam': 0.9375, 'ham': 0.0625}. These match the hand calculation. The last block subtracts the maximum log score before exponentiating. This keeps the largest term at exp(0) = 1, so the sum cannot underflow to zero.
Properties worth knowing
- Linear in log space. For binary or count features, the log score of each class is a linear function of the feature values. Multinomial and Bernoulli naive Bayes therefore have a linear decision boundary, like logistic regression.
- Ties. If two classes have equal scores,
maxreturns the first one it meets. Real data rarely ties exactly, but with tiny datasets and smoothing it can happen. - Priors matter most for short or uninformative inputs. If an input has few features, or its features have similar likelihoods across classes, the priors decide the result. On imbalanced data this pushes predictions toward the majority class.
- Unseen features. A feature value never seen with a class gives a likelihood of 0. That sends the whole product to 0 and
log(0)to negative infinity, whatever the other features say. Smoothing fixes this and is covered in a later chapter.
Common errors
- Forgetting the prior. Using only the likelihood product is maximum likelihood classification. It gives wrong answers on imbalanced data.
- Mixing probabilities and logs. Adding a probability to a log, or multiplying log values, produces numbers that look plausible but mean nothing. Pick one space for the whole computation.
- Treating scores as probabilities. The unnormalized scores do not sum to 1. Even after normalizing, the probabilities are usually too extreme, because the independence assumption counts correlated features as separate evidence.
- Looping over features not in the model. A word outside the training vocabulary has no likelihood entry. Either skip it, as the from-scratch classifier in this tutorial does, or look it up with a default. Do not let it raise a
KeyErrorin production.
Exercise
A fruit classifier has priors P(apple) = 0.6 and P(orange) = 0.4. For a certain input, the two features have likelihoods P(x1 | apple) = 0.5, P(x2 | apple) = 0.2, P(x1 | orange) = 0.8, P(x2 | orange) = 0.4. Which class does the naive Bayes rule predict, and what are the normalized posteriors?
Show answer
Apple score = 0.6 0.5 0.2 = 0.06. Orange score = 0.4 0.8 0.4 = 0.128. The rule predicts orange. The scores sum to 0.188, so the posteriors are about 0.319 for apple (0.06 / 0.188) and 0.681 for orange (0.128 / 0.188).
Exercise
A dataset has 20 binary features and 3 classes. How many free likelihood parameters does a full joint model of P(x | y) need, compared with naive Bayes? Ignore the priors.
Show answer
The full joint model needs 2^20 - 1 = 1,048,575 free parameters per class, so 3,145,725 in total. Naive Bayes needs one Bernoulli parameter per feature per class, so 20 * 3 = 60.