Sub topic 10
Multinomial naive Bayes for count features
This chapter assumes you know Bayes' theorem, the conditional independence assumption, the naive Bayes decision rule, Laplace smoothing, and log probabilities from the earlier chapters. Here we put them together for count data such as word counts.
The model
Multinomial naive Bayes treats a document as a bag of words. Each feature xj is the count of word j, and the document is a draw of n words from a class-specific distribution over the vocabulary. For class c, the model stores a probability θcj for each word j, with the θ_cj for a class summing to 1.
The score for a document is:
log P(c) + Σj xj · log θ_cj
Each word contributes its log likelihood once per occurrence. The multinomial coefficient is the same for every class, so it drops out of the comparison.
Estimating the parameters
With additive smoothing α, the estimate is:
θcj = (Ncj + α) / (N_c + α·V)
- N_cj is the total count of word j in all training documents of class c.
- N_c is the total count of all words in class c.
- V is the vocabulary size.
The α·V term in the denominator keeps each class's probabilities summing to 1. Setting α = 1 gives Laplace smoothing.
A from-scratch implementation
The code below follows the formulas directly. It treats each document as a list of words, so a repeated word is counted each time it appears.
import math
from collections import Counter, defaultdict
def train(docs, labels, alpha=1.0):
vocab = {w for d in docs for w in d}
class_counts = Counter(labels)
word_counts = defaultdict(Counter)
for d, c in zip(docs, labels):
word_counts[c].update(d)
log_prior = {c: math.log(n / len(docs)) for c, n in class_counts.items()}
log_like = {}
for c in class_counts:
total = sum(word_counts[c].values()) + alpha * len(vocab)
log_like[c] = {
w: math.log((word_counts[c][w] + alpha) / total) for w in vocab
}
return log_prior, log_like, vocab
def predict(doc, log_prior, log_like, vocab):
scores = {}
for c in log_prior:
scores[c] = log_prior[c] + sum(log_like[c][w] for w in doc if w in vocab)
return max(scores, key=scores.get)
docs = [
["free", "prize", "now"],
["meeting", "at", "noon"],
["free", "offer", "now"],
["project", "meeting", "notes"],
]
labels = ["spam", "ham", "spam", "ham"]
log_prior, log_like, vocab = train(docs, labels, alpha=1.0)
print(predict(["free", "meeting", "now"], log_prior, log_like, vocab))Here the vocabulary has 8 words. The spam class has 6 word tokens, so its denominator is 6 + 8 = 14. The word "free" appears twice in spam, so θ = (2 + 1) / 14. The test message contains "free" and "now", which are common in spam, and "meeting", which is common in ham. The spam words outweigh the single ham word, so the output is spam.
Common errors
- Feeding negative values. Counts cannot be negative.
MultinomialNBin scikit-learn raises an error if a feature is negative, so do not standardize the features first. - Using alpha = 0. Any word seen only in other classes gives a zero probability and an infinite negative log score. Keep α above 0.
- Using it on continuous measurements. Features like height or petal length are not counts. Use Gaussian naive Bayes for those.
- Counting only presence. If you only record whether a word appears, Bernoulli naive Bayes models that case, and it also penalizes absent words.
Fractional counts
TF-IDF values are not integer counts, but they often work well with MultinomialNB in practice. The formulas still run on non-negative real numbers, though the multinomial interpretation is only approximate.
Exercise
A spam class has 20 total word tokens in training, the vocabulary has 50 words, and the word "free" appears 4 times in spam. With α = 1, what is the smoothed probability of "free" given spam?
Show answer
θ = (4 + 1) / (20 + 1 × 50) = 5 / 70 ≈ 0.0714.
Exercise
Why does the term α·V appear in the denominator of the smoothed estimate?
Show answer
Adding α to each of the V word counts adds α·V to the numerator total. The denominator must grow by the same amount so that the word probabilities for the class still sum to 1.