Sub topic 7
Zero counts and Laplace smoothing
This chapter covers what happens when a word never appears with a class in the training data, and how additive smoothing fixes it. It assumes you know the naive Bayes decision rule, how counts become likelihood estimates, and basic Python. The examples use plain Python and no libraries.
The zero-count problem
Maximum likelihood estimation sets each word likelihood to a relative frequency:
P(w | c) = count(w, c) / total words in class c
Here count(w, c) is how often word w appears in training documents of class c. This estimate is honest about the training data, but it overstates what the data shows. If "meeting" never appears in a spam message, the estimate says spam messages can never contain "meeting". Your sample is small. It does not prove the word is impossible.
The naive Bayes score multiplies one likelihood per word. A single zero makes the whole product zero, however strongly the other words point to that class.
This is worse than it first looks. The tutorial's toy data has two spam and two ham messages. Take the message "free meeting now". "free" and "now" appear only in spam. "meeting" appears only in ham. Under maximum likelihood, spam gets a zero from "meeting" and ham gets a zero from "free". Both scores are 0 and the classifier has no basis to choose. In log space the problem is a log of zero, which is negative infinity or an error.
Additive smoothing
The fix is to add a pseudo-count alpha to every word in every class, as if you had seen each vocabulary word alpha extra times. The denominator grows to match, so the likelihoods for a class still sum to 1:
P(w | c) = (count(w, c) + alpha) / (N_c + alpha * V)
- N_c is the total number of word occurrences in class c.
- V is the vocabulary size, the number of distinct words across all classes.
- alpha is the smoothing strength.
The denominator gains alpha for each of the V words, which is alpha * V in total. Without that term, the probabilities would sum to more than 1.
Alpha has standard names:
| alpha | Name | Effect |
|---|---|---|
| 0 | No smoothing (maximum likelihood) | Zero probabilities for unseen words |
| 1 | Laplace smoothing | Each word gets one imaginary occurrence per class |
| between 0 and 1 | Lidstone smoothing | Gentler correction, often better on large corpora |
Smoothing has a Bayesian reading. It is the posterior mean of the word probabilities under a symmetric Dirichlet prior (the standard prior for categorical probabilities) that acts as alpha imaginary observations per word. You do not need that theory to use it. What matters is that alpha is a prior belief that every word is possible, and the training data gradually outweighs it.
Seeing it work
The script below computes smoothed likelihoods for the toy spam and ham data at several alpha values. It then scores "free meeting now" with and without smoothing.
from collections import Counter
spam_docs = [["free", "prize", "now"], ["free", "offer", "now"]]
ham_docs = [["meeting", "at", "noon"], ["project", "meeting", "notes"]]
vocab = {w for d in spam_docs + ham_docs for w in d}
def likelihoods(docs, alpha):
counts = Counter(w for d in docs for w in d)
total = sum(counts.values()) + alpha * len(vocab)
return {w: (counts[w] + alpha) / total for w in vocab}
for alpha in (0.0, 1.0, 0.1):
spam = likelihoods(spam_docs, alpha)
print(
f"alpha={alpha}: P(free|spam)={spam['free']:.4f} "
f"P(meeting|spam)={spam['meeting']:.4f} "
f"sum={sum(spam.values()):.1f}"
)
message = ["free", "meeting", "now"]
for alpha in (0.0, 1.0):
spam = likelihoods(spam_docs, alpha)
ham = likelihoods(ham_docs, alpha)
spam_score, ham_score = 0.5, 0.5 # equal priors: 2 of 4 documents each
for w in message:
spam_score *= spam[w]
ham_score *= ham[w]
print(f"alpha={alpha}: spam={spam_score:.6f} ham={ham_score:.6f}")Running it prints:
alpha=0.0: P(free|spam)=0.3333 P(meeting|spam)=0.0000 sum=1.0
alpha=1.0: P(free|spam)=0.2000 P(meeting|spam)=0.0667 sum=1.0
alpha=0.1: P(free|spam)=0.3043 P(meeting|spam)=0.0145 sum=1.0
alpha=0.0: spam=0.000000 ham=0.000000
alpha=1.0: spam=0.001333 ham=0.000444With alpha=0 the two classes tie at zero. With alpha=1 spam wins, because two of the three words ("free", "now") are strongly spam words and only "meeting" argues for ham. Smoothing keeps the dissenting word from erasing the evidence of the others.
Two details are worth checking in the output. The likelihoods still sum to 1 at every alpha. And a larger alpha pulls "free" down from 0.3333 to 0.2000 while lifting "meeting" from 0 to 0.0667. Smoothing takes probability from seen words and gives it to unseen ones.
Choosing alpha
Alpha moves the model between two failure modes.
- Too small: the model trusts rare counts. A word seen once in spam and never in ham becomes a very strong spam signal, which is probably noise.
- Too large: every class looks like the uniform distribution, and the real differences in the counts are washed out. With a small training set and a big alpha, the prior swamps the data.
The best value depends on corpus size and vocabulary size. Large corpora tolerate small alpha, and short documents with big vocabularies usually need more. Treat alpha as a hyperparameter. Tune it with cross-validation over a grid such as 0.01, 0.1, 0.5, 1.0, and keep the value with the best validation score on the metric you care about. Do not tune on the test set.
Where smoothing applies
The formula changes with the model variant.
- Multinomial naive Bayes uses the formula above. The denominator adds alpha * V because the model has V outcomes per class.
- Bernoulli naive Bayes models presence or absence of each word, so each feature has two outcomes. The estimate is (nc,w + alpha) / (nc + 2 * alpha). Here nc,w is the number of class-c documents containing the word and nc is the number of class-c documents.
- Gaussian naive Bayes has no counts, so zero counts do not arise in the same form. It has a related risk: a feature with zero variance in a class gives a degenerate density. scikit-learn handles this with
var_smoothing, which adds a small fraction of the largest feature variance to all variances.
Class priors can be smoothed too, but this is rarely needed. A class with no training documents cannot be learned anyway.
Edge cases and common errors
- Words not in the vocabulary. A word that appears at test time but never in training has no entry in the likelihood table. Smoothing does not cover it, because V counts only training words. The standard approach is to skip such words, as the from-scratch classifier in this tutorial does with
if w in vocab. Each class loses the same factor, so the comparison between classes is not distorted. - Forgetting alpha * V in the denominator. Adding alpha to the numerator only makes the likelihoods sum to more than 1. Rankings can still look reasonable, which hides the bug. Check that the likelihoods for each class sum to 1, as the script does.
- Computing V per class. V must be the shared vocabulary of all classes. If each class uses its own vocabulary size, the likelihoods are not comparable across classes.
- Setting alpha to 0 in scikit-learn. In
MultinomialNB,alphadefaults to 1.0. Values below about 1e-10 are clipped to 1e-10 unless you passforce_alpha=True, so you cannot silently get a log of zero.
Exercise
In the toy data, spam contains 6 word occurrences and the vocabulary has 9 words. Compute P("prize" | ham) with alpha = 0.5. The ham class also has 6 word occurrences, and "prize" never appears in ham.
Show answer
The numerator is 0 + 0.5 = 0.5. The denominator is 6 + 0.5 * 9 = 10.5. So P("prize" | ham) = 0.5 / 10.5, which is about 0.0476.
Exercise
A teammate smooths a multinomial model by adding alpha to each word count but leaves the denominator as N_c. What goes wrong, and how would you detect it?
Show answer
The likelihoods for each class sum to more than 1, because the numerator gained alpha for each of the V words but the denominator did not. Detect it by summing the likelihoods for a class over the whole vocabulary and checking that the total is 1. The fix is to use N_c + alpha * V in the denominator.