Multinomial Naive Bayes for Text
Spam filters of the early 2000s were naive Bayes classifiers, and for short texts with little training data the method is still hard to beat for its cost. A document becomes a bag of words, a vector of word counts over a vocabulary of thousands of words; most counts are zero. Multinomial naive Bayes models those counts directly, trains by counting, and classifies by adding up per-word log weights. Working with Text in the Machine Learning course shows the vectorisers; this lesson derives the model and its smoothing.
The model
Each class has a distribution over the words of the vocabulary: is the probability that a random word of a class- document is . A document with counts then has
That is a linear model in the counts, with weights , so prediction is one sparse matrix product. The parameters are word frequencies per class, with Laplace (additive) smoothing :
where is how often word occurs in class 's training documents and the total number of words in them. Without smoothing (), a word never seen in spam during training would get and a log of : one unseen word would veto the class whatever else the message says. ("add one") is the classic choice; it is also the posterior mean under a uniform Dirichlet prior (Conjugacy and the Exponential Family).
From scratch on eight messages
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
train = [("win a free prize now", "spam"), ("free money claim your prize", "spam"),
("cheap pills free shipping", "spam"), ("claim your free gift card now", "spam"),
("meeting moved to friday", "ham"), ("can you send the report", "ham"),
("lunch on friday with the team", "ham"), ("the report is ready for review", "ham")]
texts, labels = zip(*train)
vec = CountVectorizer()
X = vec.fit_transform(texts).toarray() # word counts, one row per message
y = np.array([1 if l == "spam" else 0 for l in labels])
vocab = vec.get_feature_names_out()
alpha = 1.0 # Laplace (add-one) smoothing
log_prior = np.log(np.bincount(y) / len(y))
counts = np.array([X[y == c].sum(axis=0) for c in [0, 1]]) # word counts per class
log_theta = np.log((counts + alpha) / (counts.sum(axis=1, keepdims=True) + alpha * len(vocab)))
def predict_proba(texts):
Xn = vec.transform(texts).toarray()
jll = Xn @ log_theta.T + log_prior # log p(c) + sum_w count(w) log theta_cw
jll -= jll.max(axis=1, keepdims=True)
p = np.exp(jll)
return p / p.sum(axis=1, keepdims=True)
new = ["free prize for the team", "send the report on friday", "claim now"]
sk = MultinomialNB(alpha=1.0).fit(X, y)
print("vocabulary size:", len(vocab))
for text, p_ours, p_sk in zip(new, predict_proba(new), sk.predict_proba(vec.transform(new))):
print(f"{text!r:30s} P(spam) ours {p_ours[1]:.3f} sklearn {p_sk[1]:.3f}")
weights = log_theta[1] - log_theta[0] # how much each word favours spam
top = sorted(zip(weights.round(3), vocab), key=lambda t: (-t[0], t[1]))[:5]
print("most spam-indicating words:", [(str(w), float(s)) for s, w in top])vocabulary size: 29
'free prize for the team' P(spam) ours 0.535 sklearn 0.535
'send the report on friday' P(spam) ours 0.008 sklearn 0.008
'claim now' P(spam) ours 0.907 sklearn 0.907
most spam-indicating words: [('free', 1.65), ('claim', 1.139), ('now', 1.139), ('prize', 1.139), ('your', 1.139)]
The word weights rank "free" first (four times in spam, never in ham: ), followed by a four-way tie of words seen twice in spam and never in ham. A message is scored by summing the weights of its words: "free prize" pulls towards spam, "for the team" towards ham, and the result is a near tie (0.535). Words not in the vocabulary are ignored by the vectoriser. The probabilities agree with MultinomialNB exactly.
A larger generated corpus
Three topics (sport, tech, finance), each document mixing topic words, some off-topic words and common filler words; 300 documents. The comparison uses 5-fold cross-validation, and then trains on very small slices:
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB, ComplementNB
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import cross_val_score, StratifiedKFold
rng = np.random.default_rng(0)
topics = {
"sport": "match goal team coach season player score league win fans stadium training".split(),
"tech": "software update phone app battery chip cloud data release users screen code".split(),
"finance": "market stock price bank rate inflation shares profit budget loan tax growth".split(),
}
common = "the a of to and in is it for on with this that was new today".split()
def make_doc(topic):
words = list(rng.choice(topics[topic], size=rng.integers(3, 8)))
other = [t for t in topics if t != topic]
words += list(rng.choice(topics[rng.choice(other)], size=rng.integers(0, 4))) # off-topic words
words += list(rng.choice(common, size=rng.integers(5, 12)))
rng.shuffle(words)
return " ".join(words)
labels = rng.choice(list(topics), size=300)
docs = [make_doc(t) for t in labels]
print("example:", labels[0], "->", docs[0])
cv = StratifiedKFold(5, shuffle=True, random_state=0)
for name, model in [("MultinomialNB, counts", make_pipeline(CountVectorizer(), MultinomialNB())),
("ComplementNB, counts", make_pipeline(CountVectorizer(), ComplementNB())),
("LogisticRegression, tf-idf", make_pipeline(TfidfVectorizer(), LogisticRegression(max_iter=1000)))]:
print(f"{name:27s} CV accuracy {cross_val_score(model, docs, labels, cv=cv).mean():.3f}")
for n in [15, 30, 60]:
idx = np.arange(n)
nb = make_pipeline(CountVectorizer(), MultinomialNB()).fit([docs[i] for i in idx], labels[idx])
lr = make_pipeline(TfidfVectorizer(), LogisticRegression(max_iter=1000)).fit([docs[i] for i in idx], labels[idx])
print(f"{n} training docs: NB {nb.score(docs[100:], labels[100:]):.3f} logistic {lr.score(docs[100:], labels[100:]):.3f} (200 test docs)")example: finance -> with this with market stock for rate and today
MultinomialNB, counts CV accuracy 0.963
ComplementNB, counts CV accuracy 0.963
LogisticRegression, tf-idf CV accuracy 0.947
15 training docs: NB 0.790 logistic 0.645 (200 test docs)
30 training docs: NB 0.840 logistic 0.825 (200 test docs)
60 training docs: NB 0.910 logistic 0.925 (200 test docs)
With all the data, naive Bayes and logistic regression are within a couple of documents of each other. With only 15 training documents, naive Bayes is far ahead (0.790 against 0.645): it needs to estimate only word frequencies, while logistic regression has to fit a weight per word and class from almost nothing. By 60 documents logistic regression has caught up. This is the classic pattern (Ng and Jordan, 2002): the generative model reaches its best level with less data, the discriminative model usually ends higher. ComplementNB estimates each class's weights from all the other classes' documents, which helps with imbalanced classes.
Variants and hyperparameters
| Class | Features | Note |
|---|---|---|
MultinomialNB |
counts or tf-idf | the text standard |
ComplementNB |
counts | better with imbalanced classes |
BernoulliNB |
binary present/absent | short texts; also penalises absent words |
CategoricalNB |
categorical codes | one distribution per feature value |
The main hyperparameter is alpha (smoothing, tuned on a log grid, often 0.01 to 1); the vectoriser's choices (n-grams, min_df, stop words, lowercasing) usually matter more.
Strengths, weaknesses, when to use it
Multinomial naive Bayes trains in one pass, handles huge sparse vocabularies, needs little data, supports partial_fit for streams, and its word weights are readable. It ignores word order and treats words as independent (so "not good" is just "not" plus "good"), its probabilities are overconfident on long documents, and with plenty of data discriminative models (logistic regression, linear SVM) or transformers do better. Use it as the first baseline for text classification, for small labelled sets, and where training must be instant.
Pitfalls
- . An unseen word gives a probability of exactly 0 for a class.
- Fitting the vectoriser on all documents. Fit it inside the pipeline so the test vocabulary does not leak into training.
- Comparing models on one tiny split. With 15 training documents results swing; use cross-validation or several splits.
Practice
- In class "ham", the word "prize" never occurs; the four ham messages have 21 words in total and the vocabulary has 29 words. What is with ?
Answer
, small but not zero, so one occurrence of "prize" lowers a message's ham score without vetoing it.
- Why is multinomial naive Bayes called a linear classifier?
Answer
Its log posterior is : a bias plus a weighted sum of the counts. The boundary between two classes, where the scores are equal, is a hyperplane in count space.
Test yourself
What does Laplace smoothing prevent in multinomial naive Bayes?
- Overfitting to long documents
- Zero probabilities for words not seen in a class during training
- Large vocabularies
- Class imbalance
How does multinomial naive Bayes score a document for a class?
- By the cosine similarity to the class centroid
- By the log prior plus the sum of word counts times the class's log word probabilities
- By the number of distinct words
- By a decision tree over words
With 15 training documents naive Bayes beat logistic regression; with 60 they were even. Why?
- Naive Bayes overfits large data
- A generative model with few parameters to estimate reaches its best level with less data
- Logistic regression cannot use counts
- Tf-idf is worse than counts