Sub topic 7
Zero counts and Laplace smoothing
This chapter assumes you know the naive Bayes decision rule and how to estimate priors and likelihoods by counting. It covers what goes wrong when a word never appears in a class during training, and how additive smoothing fixes it.
The zero-count problem
The multinomial likelihood of word w in class c is a relative frequency:
P(w | c) = count(w, c) / total words in c
Suppose "meeting" never appears in any spam training message. Then P(meeting | spam) = 0. The naive Bayes score multiplies one likelihood per word, so a single zero makes the whole spam score zero, however strongly the other words point to spam. In log space the same problem appears as log(0), which is negative infinity.
This is a sampling problem, not evidence. A word missing from a finite training set does not mean it is impossible in that class.
Laplace (additive) smoothing
Add a pseudo-count alpha to every word count in every class, and enlarge the denominator so the probabilities still sum to 1:
P(w | c) = (count(w, c) + alpha) / (total words in c + alpha × |V|)
Here |V| is the vocabulary size. Setting alpha = 1 is classic Laplace smoothing. Values between 0 and 1 are called Lidstone smoothing. The effect is shown in the diagram.
A worked example
Take the spam class from the earlier examples. Its messages contain six tokens: free, prize, now, free, offer, now. The full vocabulary has nine words. This code computes two likelihoods for several values of alpha:
from collections import Counter
spam_words = ["free", "prize", "now", "free", "offer", "now"]
vocab_size = 9
counts = Counter(spam_words)
total = sum(counts.values())
for alpha in (0.0, 1.0, 0.1):
denom = total + alpha * vocab_size
p_free = (counts["free"] + alpha) / denom
p_meeting = (counts["meeting"] + alpha) / denom
print(f"alpha={alpha}: P(free|spam)={p_free:.4f}, P(meeting|spam)={p_meeting:.4f}")The output is:
alpha=0.0: P(free|spam)=0.3333, P(meeting|spam)=0.0000
alpha=1.0: P(free|spam)=0.2000, P(meeting|spam)=0.0667
alpha=0.1: P(free|spam)=0.3043, P(meeting|spam)=0.0145With alpha=0, "meeting" has probability zero. With alpha=1, "meeting" gets 1/15, and "free" drops from 1/3 to 1/5 because probability mass moves to unseen words. A small alpha changes the seen words less.
Choosing alpha
- Large
alphapulls every likelihood toward uniform, which can wash out real signal in small datasets. - Small
alphatrusts the counts more, but unseen words still get a nonzero probability. - Treat
alphaas a hyperparameter and tune it with cross-validation. In scikit-learn it is thealphaargument ofMultinomialNB.
Exercise
The ham class has six tokens: meeting, at, noon, project, meeting, notes. The vocabulary has nine words and alpha = 1. What is P(meeting | ham), and what is P(free | ham)?
Show answer
"meeting" appears twice, so P(meeting | ham) = (2 + 1) / (6 + 1 × 9) = 3/15 = 0.2. "free" never appears in ham, so P(free | ham) = (0 + 1) / 15 ≈ 0.0667.