Sub topic 6
Estimating priors and likelihoods from data
This chapter assumes you know the naive Bayes decision rule, the conditional independence assumption, and basic Python. Earlier chapters showed that the classifier scores each class with P(y) × Π P(xᵢ | y). Here you will see where those numbers come from. Training a naive Bayes model means counting, and this chapter covers what to count and where each count goes.
What has to be estimated
The decision rule needs two kinds of parameters:
- Class priors P(y = c): how common each class is.
- Per-feature likelihoods P(xᵢ | y = c): how each feature behaves inside one class.
Independence is what keeps this tractable. Without it, you would estimate the joint distribution P(x₁, …, x_d | y), which needs a number of parameters that grows exponentially with the number of features. With it, you estimate d separate one-dimensional distributions for each class. A model with 10,000 words and 2 classes needs about 20,000 likelihood parameters, not a table over every possible word combination.
Estimating priors
The maximum likelihood estimate of a prior is the class frequency in the training set:
P(y = c) = N_c / N
N_c is the number of training examples with label c, and N is the total number of examples. If 40 of 100 emails are spam, the prior for spam is 0.4.
Two edge cases matter in practice:
- Imbalanced data. The prior reflects the training distribution. If your training set is 99% ham, the model leans heavily toward ham. This is correct only if production data looks the same. When it does not, you can pass explicit priors. In scikit-learn,
GaussianNBtakespriors=, and the discrete variants takeclass_prior=together withfit_prior=False. - Classes with no examples. A class with N_c = 0 gets a prior of 0 and can never be predicted. Libraries only learn the classes they see in
y.
Estimating likelihoods: the multinomial case
For bag-of-words text, the multinomial model treats each class as one long stream of word tokens. The estimate for word w in class c is a relative frequency:
P(w | c) = count(w, c) / Σ_w′ count(w′, c)
The numerator is how many times w appears in all training documents of class c. The denominator is the total number of tokens in class c. So the likelihoods within one class sum to 1 across the vocabulary.
This is also the maximum likelihood solution. For one class, you choose probabilities θw that maximize Σw nw log θw, where nw is the count of word w, subject to Σ θw = 1. Adding a Lagrange multiplier for the constraint and solving gives θw = nw / Σ n_w′. The "obvious" estimator is the likelihood-maximizing one.
A worked example
Use four tiny documents:
| Document | Label |
|---|---|
| free prize now | spam |
| meeting at noon | ham |
| free offer now | spam |
| project meeting notes | ham |
Two of four documents are spam, so both priors are 0.5. The spam class has 6 tokens in total: free ×2, now ×2, prize ×1, offer ×1. The ham class also has 6 tokens: meeting ×2, and at, noon, project, notes once each. The unsmoothed likelihoods are:
| Word | P(word \ | spam) | P(word \ | ham) |
|---|---|---|---|---|
| free | 2/6 ≈ 0.333 | 0 | ||
| now | 2/6 ≈ 0.333 | 0 | ||
| prize | 1/6 ≈ 0.167 | 0 | ||
| offer | 1/6 ≈ 0.167 | 0 | ||
| meeting | 0 | 2/6 ≈ 0.333 | ||
| at, noon, project, notes | 0 | 1/6 ≈ 0.167 each |
The code below computes the same numbers.
from collections import Counter, defaultdict
def estimate(docs, labels):
n_docs = len(labels)
class_counts = Counter(labels)
priors = {c: k / n_docs for c, k in class_counts.items()}
word_counts = defaultdict(Counter)
for doc, c in zip(docs, labels):
word_counts[c].update(doc)
likelihoods = {}
for c, counts in word_counts.items():
total = sum(counts.values())
likelihoods[c] = {w: k / total for w, k in counts.items()}
return priors, likelihoods
docs = [
["free", "prize", "now"],
["meeting", "at", "noon"],
["free", "offer", "now"],
["project", "meeting", "notes"],
]
labels = ["spam", "ham", "spam", "ham"]
priors, likelihoods = estimate(docs, labels)
print(priors)
for c in sorted(likelihoods):
print(c, {w: round(p, 3) for w, p in sorted(likelihoods[c].items())})Notice that likelihoods["ham"] has no entry for "free". The estimator only stores words it has seen in that class. If you scored "free meeting now" as ham, you would multiply by a probability of 0, and the whole ham score would collapse no matter how strongly "meeting" suggested ham. The next chapter fixes this with smoothing.
Other feature types estimate differently
The shape of the counting depends on the feature model:
- Multinomial (word counts): the denominator is total tokens in the class, as above. A word repeated five times in one document adds five to the count.
- Bernoulli (word present or absent): P(w | c) is the fraction of class-c documents that contain w. The denominator is N_c, not a token total. Absence also carries information, because each absent word contributes 1 − P(w | c).
- Gaussian (continuous values): for each feature and class, estimate a mean and variance from that class's rows, then evaluate the normal density at test time. The maximum likelihood variance divides by n, not n − 1.
All three are single-pass aggregate statistics. This has useful consequences. Training cost is linear in the data size, and counts from separate data shards can be added together. A model can also be updated incrementally, which is what partial_fit does in scikit-learn.
Checking what scikit-learn learned
A fitted MultinomialNB keeps the raw counts it used. Inspecting them is a good way to confirm your mental model.
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
import numpy as np
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_)
print(vec.get_feature_names_out())
print(nb.class_count_)
print(np.exp(nb.class_log_prior_))
print(nb.feature_count_)Classes are sorted alphabetically, so ham comes first. The output is:
['ham' 'spam']
['at' 'free' 'meeting' 'noon' 'notes' 'now' 'offer' 'prize' 'project']
[2. 2.]
[0.5 0.5]
[[1. 0. 2. 1. 1. 0. 0. 0. 1.]
[0. 2. 0. 0. 0. 2. 1. 1. 0.]]The feature_count_ rows are the numerators from the table above. alpha=1.0 is smoothing, which changes how the log probabilities in feature_log_prob_ are computed from these counts. The counts themselves stay raw.
Common errors
- Estimating likelihoods across all classes. The denominator must be the total within class c, not across the whole corpus. Otherwise the likelihoods are not conditional on the class.
- Mixing up Bernoulli and multinomial denominators. Documents are used for Bernoulli, tokens for multinomial. Feeding raw counts to
BernoulliNBsilently binarizes them by default (binarize=0.0). - Fitting the vocabulary on test data. Fit the vectorizer on training text only. Putting both steps in a pipeline prevents leakage.
- Trusting priors that do not match deployment. The estimated prior is only as good as the assumption that training and production class frequencies agree.
Exercise
A training set has 100 documents: 30 spam and 70 ham. The spam documents contain 300 tokens in total, and the word "free" appears 45 times among them. Using unsmoothed multinomial estimates, what are P(spam) and P(free | spam)? Would the same P(free | spam) change if the ham class were doubled in size?
Show answer
P(spam) = 30/100 = 0.3. P(free | spam) = 45/300 = 0.15. Doubling the ham class changes P(spam) because the document total changes. It does not change P(free | spam), because that likelihood uses only spam tokens in both numerator and denominator.
Exercise
Using the four-document example, compute the unsmoothed P(meeting | ham) and explain why scoring "free meeting now" as ham fails with these estimates.
Show answer
P(meeting | ham) = 2/6 ≈ 0.333, since "meeting" appears twice among the 6 ham tokens. The test document also contains "free" and "now", which never appear in ham training documents. Their likelihoods are 0, so the product for ham is 0 regardless of the other terms. Smoothing is needed to avoid this.