Sub topic 10
Multinomial Naive Bayes for Count Features
This chapter assumes you know the naive Bayes decision rule, the conditional independence assumption, and why we sum log probabilities. It covers the variant built for features that are counts, most often word counts in a document.
The model
Multinomial naive Bayes treats a document as a bag of words. You draw $n$ tokens independently from a vocabulary. For class $c$, each vocabulary word $w$ has a probability $\theta{c,w}$, and the probabilities sum to 1 over the vocabulary. The feature vector $x$ holds the count $xw$ of each word in the document.
Under this model the class-conditional likelihood is proportional to a product of powers:
$$P(x \mid c) \propto \prod{w} \theta{c,w}^{x_w}$$
The multinomial coefficient is the same for every class, so it cancels when you compare classes. The decision rule in log space is:
$$\hat{c} = \arg\maxc \left[ \log P(c) + \sum{w} xw \log \theta{c,w} \right]$$
A word that appears three times contributes its log likelihood three times. This is the main difference from Bernoulli naive Bayes, which only records whether a word is present.
Estimating the parameters
The prior is the fraction of training documents in each class: $P(c) = N_c / N$.
The word probability is the smoothed share of class-$c$ tokens that are word $w$:
$$\theta{c,w} = \frac{N{c,w} + \alpha}{N_c^{\text{tok}} + \alpha \lvert V \rvert}$$
- $N_{c,w}$ is the total count of $w$ across all documents of class $c$.
- $N_c^{\text{tok}}$ is the total number of tokens in class $c$.
- $\lvert V \rvert$ is the vocabulary size.
- $\alpha$ is the smoothing constant. $\alpha = 1$ is Laplace smoothing.
The denominator has $\alpha \lvert V \rvert$ added so that $\sumw \theta{c,w} = 1$. If you add $\alpha$ to the numerator but forget this term, the "probabilities" no longer sum to 1.
Training is one pass of counting. That is why the model scales to very large vocabularies.
A worked example
Use the four training messages from the spam example.
- Spam: "free prize now" and "free offer now". That is 6 tokens.
- Ham: "meeting at noon" and "project meeting notes". That is 6 tokens.
- The vocabulary has 9 words, and $\alpha = 1$.
For both classes the denominator is $6 + 1 \cdot 9 = 15$. Both priors are 0.5.
Now classify "free meeting now".
| Word | Spam count | Spam $\theta$ | Ham count | Ham $\theta$ |
|---|---|---|---|---|
| free | 2 | 3/15 | 0 | 1/15 |
| meeting | 0 | 1/15 | 2 | 3/15 |
| now | 2 | 3/15 | 0 | 1/15 |
Spam score: $0.5 \times \frac{3}{15}\cdot\frac{1}{15}\cdot\frac{3}{15} = 0.001333$, so the log score is about $-6.62$.
Ham score: $0.5 \times \frac{1}{15}\cdot\frac{3}{15}\cdot\frac{1}{15} = 0.000444$, so the log score is about $-7.72$.
Spam wins. Normalizing gives $P(\text{spam} \mid x) = 0.001333 / (0.001333 + 0.000444) = 0.75$.
Without smoothing, "meeting" would have probability 0 under spam and "free" would have probability 0 under ham. Both scores would collapse to 0, and the classifier couldn't separate the classes.
Checking the math against scikit-learn
The following code computes the scores by hand from the fitted model's attributes. It confirms that MultinomialNB is just a matrix product plus a prior.
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
texts = [
"free prize now",
"meeting at noon",
"free offer now",
"project meeting notes",
]
labels = ["spam", "ham", "spam", "ham"]
vec = CountVectorizer()
X = vec.fit_transform(texts)
nb = MultinomialNB(alpha=1.0).fit(X, labels)
print(nb.classes_) # ['ham' 'spam']
print(np.exp(nb.feature_log_prob_).sum(axis=1)) # each row sums to 1
x = vec.transform(["free meeting now"])
scores = x @ nb.feature_log_prob_.T + nb.class_log_prior_
print(np.round(scores, 2)) # about [[-7.72 -6.62]]
print(nb.predict_proba(x)) # about [[0.25 0.75]]Two attributes matter here:
feature_log_prob_has shape(n_classes, n_features)and holds $\log \theta_{c,w}$.class_log_prior_holds $\log P(c)$.
The classes appear in sorted order, so ham comes before spam.
Choosing alpha
$\alpha$ controls how much probability mass is moved to unseen words.
- Small $\alpha$ (for example 0.01) trusts the training counts. It works well on large corpora, but a word seen in only one class can dominate the prediction.
- Large $\alpha$ (for example 10) pulls every $\theta_{c,w}$ toward $1/\lvert V \rvert$. The classes become harder to tell apart.
- $\alpha = 0$ reintroduces zero probabilities. scikit-learn warns and clips it to a tiny positive value, so you don't get the exact maximum likelihood estimate.
Treat $\alpha$ as a hyperparameter and tune it with cross-validation. A search over values such as 0.01, 0.1, 0.5, and 1.0 is usually enough.
Fractional features and TF-IDF
The derivation assumes integer counts, but the formulas only multiply and add. Fractional features such as TF-IDF weights work in practice, and MultinomialNB accepts any non-negative value. TF-IDF often helps on text because it down-weights words that appear in nearly every document. The result is no longer a strict multinomial model, so read the probabilities as heuristic scores.
Common errors
- Using it on continuous measurements. Features such as height or temperature are not counts. Use Gaussian naive Bayes, or bin the values first.
- Forgetting document length. Longer documents add more terms to the sum, so scores are not comparable across documents. This does not affect the argmax for a single document, because every class gets the same number of terms. It does affect how extreme the posterior probabilities look.
- Fitting the vectorizer on test data. Fit
CountVectorizeron training text only, then calltransformon new text. A pipeline handles this for you. Words outside the training vocabulary are ignored at prediction time. - Reading
predict_probaas calibrated. Repeated words are treated as independent evidence, so probabilities tend toward 0 or 1. Use them for ranking, not as literal confidence. - Mixing up the two smoothing terms. The numerator gets $\alpha$, and the denominator gets $\alpha \lvert V \rvert$. A wrong denominator shifts every class differently when class sizes differ.
When to prefer it
Multinomial naive Bayes is a strong first baseline for text. It trains in a single pass, it handles tens of thousands of features, and it needs little tuning beyond $\alpha$. Choose Bernoulli naive Bayes when presence or absence matters more than frequency, as in short texts. Choose Gaussian naive Bayes for real-valued features.
Exercise
A class "tech" has 1000 total tokens in training, the vocabulary has 5000 words, and the word "kernel" appears 4 times in tech documents. With alpha = 0.5, what is the smoothed probability of "kernel" given tech, and what would it be for a word never seen in tech?
Show answer
The denominator is 1000 + 0.5 * 5000 = 3500. For "kernel": (4 + 0.5) / 3500 = 4.5 / 3500, about 0.001286. For an unseen word: 0.5 / 3500, about 0.000143. Neither is zero, so no unseen word can zero out a class score.
Exercise
A test document contains the word "free" three times and the word "meeting" once. Write its log score for class c in terms of theta values, and say how it differs from the Bernoulli model's treatment of "free".
Show answer
The score is log P(c) + 3 log theta(c, free) + 1 log theta(c, meeting). The multinomial model counts each occurrence, so "free" contributes three times. A Bernoulli model records only that "free" is present and contributes one term. It also adds a term for every vocabulary word that is absent.