Sub topic 11
Bernoulli naive Bayes for binary features
This chapter assumes you know the naive Bayes decision rule, how smoothed likelihoods are estimated, and why scores are summed in log space. It covers the variant for features that are either present or absent, and the one way it differs from multinomial naive Bayes.
The model
Bernoulli naive Bayes treats each feature as a yes/no event. Typical examples are "the email contains the word free" or "the user clicked the banner". For a class c and feature j, the model has one parameter:
θ_cj = P(x_j = 1 | c): the probability that featurejis present in a document of classc.
If the feature is absent, its probability is 1 − θ_cj. A single formula covers both cases:
P(x_j | c) = θ_cj^x_j * (1 − θ_cj)^(1 − x_j)With the naive independence assumption, the score for class c is the log prior plus one log term for every feature in the vocabulary:
score(c) = log P(c) + Σ_j [ x_j * log θ_cj + (1 − x_j) * log(1 − θ_cj) ]The predicted class is the one with the highest score. The sum runs over the whole vocabulary, not only the features that appear in the document.
Estimating the parameters
Let N_cj be the number of training documents in class c that contain feature j. Let N_c be the number of documents in class c. The smoothed estimate is:
θ_cj = (N_cj + α) / (N_c + 2α)The denominator uses 2α, not α times the vocabulary size as in multinomial naive Bayes. Each feature is a separate two-outcome event (present or absent), so smoothing adds α pseudo-observations to each of those two outcomes. This keeps θ_cj strictly between 0 and 1. That matters here because both log θ and log(1 − θ) are used. Without smoothing, a word seen in every document of a class gives θ = 1, and a later document without that word gets log(0).
Absence is evidence
The main difference from multinomial naive Bayes is that Bernoulli naive Bayes scores absent features. A document that lacks the word meeting adds log(1 − θ_c,meeting) to each class. If meeting is common in ham and rare in spam, its absence pushes the score toward spam.
Multinomial naive Bayes only scores words that occur, and it weights them by how many times they occur. Bernoulli ignores counts and scores every vocabulary entry.
| Property | Bernoulli NB | Multinomial NB |
|---|---|---|
| Feature meaning | Present or absent | Count of occurrences |
| Absent features | Contribute `log(1 − θ)` | Contribute nothing |
| Smoothing denominator | `N_c + 2α` | total word count in class `+ α·V` |
| Document length | Not modeled directly | Longer documents add more terms |
| Often better for | Short texts, small vocabularies | Longer documents |
Because every feature is scored, a large vocabulary adds many small "absent" terms. For long documents these terms can dominate and make Bernoulli less reliable than multinomial. Short texts such as tweets, subject lines, and product titles are where it tends to do well.
From-scratch implementation
This NumPy version uses the same toy spam data as earlier chapters. The columns are the words free, prize, now, meeting, and noon.
import numpy as np
vocab = ["free", "prize", "now", "meeting", "noon"]
X = np.array([
[1, 1, 1, 0, 0], # free prize now
[0, 0, 0, 1, 1], # meeting at noon
[1, 0, 1, 0, 0], # free offer now
[0, 0, 0, 1, 0], # project meeting notes
])
y = np.array(["spam", "ham", "spam", "ham"])
def fit(X, y, alpha=1.0):
classes = np.unique(y)
log_prior = np.log([np.mean(y == c) for c in classes])
theta = np.array([
(X[y == c].sum(axis=0) + alpha) / ((y == c).sum() + 2 * alpha)
for c in classes
])
return classes, log_prior, theta
def predict(x, classes, log_prior, theta):
scores = log_prior + x @ np.log(theta).T + (1 - x) @ np.log(1 - theta).T
return classes[np.argmax(scores)]
classes, log_prior, theta = fit(X, y)
print(classes)
print(np.round(theta, 2))
x_new = np.array([1, 0, 0, 0, 0]) # the single word "free"
print(predict(x_new, classes, log_prior, theta))The theta array has one row per class and one column per word. The spam row is [0.75, 0.5, 0.75, 0.25, 0.25]. For example, free appears in 2 of the 2 spam documents, so (2 + 1) / (2 + 2) = 0.75. The matrix products compute both sums at once: x @ log(theta).T handles present features and (1 - x) @ log(1 - theta).T handles absent ones. The script prints spam for the one-word document.
Bernoulli naive Bayes in scikit-learn
BernoulliNB implements the same model. Use CountVectorizer(binary=True) to produce 0/1 features.
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 now"]))
print(clf.predict_proba(["free now"]))
nb = clf[-1]
print(clf[0].get_feature_names_out())
print(np.round(np.exp(nb.feature_log_prob_), 2))feature_log_prob_ stores log θ with one row per class. Exponentiating it gives back the θ values from the formula above. Note that the vocabulary here includes at, offer, notes, and project, so the numbers differ from the NumPy example.
Common errors
- Forgetting
binarize.BernoulliNBhas abinarizeparameter, which defaults to0.0. Every value above the threshold becomes 1, so raw counts are silently turned into presence flags. Setbinarize=Noneonly when your input is already 0/1. For continuous inputs, choose the threshold deliberately instead of accepting the default. - Using it on long documents without checking. The "absent" terms from thousands of vocabulary entries can swamp the evidence from the few words that appear. Compare against
MultinomialNBwith cross-validation. - Setting
alphato 0. A feature seen in every training document of a class givesθ = 1, and a later document that lacks it scoreslog(0). Keepalpha > 0. The default of 1.0 is a reasonable start, and smaller values such as 0.1 are often worth tuning. - Assuming the probabilities are calibrated. As with the other variants,
predict_probatends to be too close to 0 or 1, because many correlated features are multiplied as if they were independent.
Choosing between the three variants
Pick the variant from the type of the feature, not from habit:
- Continuous measurements: Gaussian naive Bayes.
- Counts or term frequencies, especially in longer documents: multinomial naive Bayes.
- True binary features, or short texts where presence matters more than frequency: Bernoulli naive Bayes.
When unsure, fit all that are plausible and compare them on held-out data. They train in a single pass, so the comparison is cheap.
Exercise
In a training set, the word "prize" appears in 3 of the 10 spam documents. With alpha = 1, what is θ for "prize" in the spam class, and what does a document without "prize" add to the spam score for that feature?
Show answer
θ = (3 + 1) / (10 + 2·1) = 4/12 ≈ 0.333. A document without "prize" adds log(1 − 0.333) = log(0.667) ≈ −0.405 to the spam score.
Exercise
Why does Bernoulli naive Bayes smooth with a denominator of N_c + 2α, while multinomial naive Bayes uses the total word count plus α times the vocabulary size?
Show answer
Bernoulli models each feature as its own two-outcome event (present or absent), so α pseudo-observations are added to each of the two outcomes, giving 2α in the denominator. Multinomial models one distribution over all V words, so α pseudo-counts are added for each of the V words.