Sub topic 2
Zero Counts and Laplace Smoothing
Assume you know conditional probability, logarithms, and supervised classification. Naive Bayes estimates a class prior and feature likelihoods from labeled training data.
Zero counts and Laplace smoothing
Suppose a word never appears in the training documents for class spam. Its estimated likelihood is:
\[ P(\text{word} \mid \text{spam}) = 0 \]
Because naive Bayes multiplies feature likelihoods, one zero makes the entire class score zero. This is too strong for a small training set.
Laplace smoothing, also called additive smoothing, adds a positive value α to every feature count:
\[ P(w \mid c) = \frac{\text{count}(w,c)+\alpha} {\text{total feature count in }c+\alpha |V|} \]
Here, V is the vocabulary. With α = 1, every possible word receives one artificial count.
from collections import Counter
counts = Counter({"free": 3, "offer": 1})
vocabulary_size = 4
alpha = 1
probability = (counts["meeting"] + alpha) / (
sum(counts.values()) + alpha * vocabulary_size
)
print(probability)Working in log space
Products of many probabilities can underflow: a computer rounds extremely small values to zero. Since logarithms turn products into sums, implementations use:
\[ \log P(c \mid x) \propto \log P(c) + \sumi \log P(xi \mid c) \]
The class with the largest log score is the prediction. Adding log probabilities preserves the comparison while avoiding numerical underflow.
Choosing a Naive Bayes variant
| Variant | Feature type | Typical example |
|---|---|---|
| GaussianNB | Continuous measurements | Height, temperature |
| MultinomialNB | Nonnegative counts | Word frequencies |
| BernoulliNB | Binary presence or absence | Whether a word appears |
Gaussian naive Bayes
Gaussian naive Bayes models each continuous feature with a normal distribution within each class. It estimates a mean and variance per class-feature pair. It works well when measurements are roughly bell-shaped, but unusual values can affect the estimates.
Multinomial naive Bayes
Multinomial naive Bayes models counts. In text classification, a document becomes a vector of word counts. Laplace smoothing is especially useful because many words are absent from many classes.
Bernoulli naive Bayes
Bernoulli naive Bayes uses binary features. A feature records whether a word appears, not how many times it appears. It also models absent features, so repeated occurrences do not increase a word's influence.
Exercise
A word is unseen in one class. Which problem does Laplace smoothing prevent, and why are log probabilities used?
Show answer
It prevents a zero likelihood from forcing the whole class score to zero. Log probabilities replace products with sums and avoid numerical underflow.