Sub topic 11
Bernoulli naive Bayes for binary features
This chapter assumes you know the naive Bayes decision rule, Laplace smoothing, and log-space scoring from earlier chapters. It covers the variant for features that are either present or absent.
The model
Bernoulli naive Bayes treats each feature as a yes/no value. In text, feature i is 1 if word i appears in the document and 0 if it does not. Counts are ignored.
For each class c and feature i, the model learns one number, p(c,i), which is the probability that feature i is present in a document of class c. Under the conditional independence assumption, the likelihood of a document is:
P(x | c) = ∏ p(c,i)^xi · (1 − p(c,i))^(1 − xi)
The exponents select a factor for each feature. A present word contributes p(c,i). An absent word contributes 1 − p(c,i). The class score is still the log prior plus the sum of log likelihoods.
Estimating the parameters
With Laplace smoothing, the estimate is:
p(c,i) = (N(c,i) + α) / (N(c) + 2α)
- N(c,i) is the number of training documents in class c that contain feature i.
- N(c) is the number of training documents in class c.
- The denominator adds 2α, not α times the vocabulary size. Each feature has two outcomes, present or absent.
The key difference from multinomial
Multinomial naive Bayes only scores the words that occur in a document. Bernoulli naive Bayes also scores the words that are missing. If "free" is common in spam and absent from a message, that absence counts as evidence against spam.
| Aspect | Multinomial NB | Bernoulli NB |
|---|---|---|
| Feature value | Count | 0 or 1 |
| Absent words | Ignored | Contribute log(1 − p) |
| Smoothing denominator | N_words(c) + α·V | N_docs(c) + 2α |
| Typical fit | Longer documents | Short texts, small vocabularies |
Using it in scikit-learn
BernoulliNB has a binarize parameter, with a default of 0.0. It turns every value above the threshold into 1. Setting binary=True in CountVectorizer makes the binary input explicit.
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import BernoulliNB
from sklearn.pipeline import make_pipeline
texts = [
"free prize now",
"meeting at noon",
"free offer now",
"project meeting notes",
]
labels = ["spam", "ham", "spam", "ham"]
clf = make_pipeline(CountVectorizer(binary=True), BernoulliNB(alpha=1.0))
clf.fit(texts, labels)
print(clf.predict(["free meeting now"]))
vectorizer, model = clf[0], clf[-1]
words = vectorizer.get_feature_names_out()
probs = np.exp(model.feature_log_prob_)
for cls, row in zip(model.classes_, probs):
print(cls, dict(zip(words, row.round(2))))The loop prints p(c,i) for every class and word. For "free" in the spam class, both spam documents contain it, so p = (2 + 1) / (2 + 2) = 0.75.
Common errors
- Passing counts and expecting count behavior. With the default
binarize=0.0, a count of 5 and a count of 1 are the same. Use multinomial if counts matter. - Forgetting that absences count. Long documents against a large vocabulary add many small absence terms. This can dominate the score and is why Bernoulli often does worse on long texts.
- Setting
alpha=0. A feature that is always present or always absent in a class gives probability 0 or 1. The log of 0 is undefined, and scikit-learn clips alpha to a small positive value with a warning.
Exercise
A class has 4 training documents. The word "offer" appears in 1 of them. With alpha = 1, what is p(c, "offer"), and what factor does a document that lacks "offer" contribute to the likelihood?
Show answer
p = (1 + 1) / (4 + 2) = 1/3. A document without "offer" contributes 1 − 1/3 = 2/3 (or log(2/3) in log space).