In P0.1 a toy filter gave every word a score (spam count minus ham count) and added the scores. “Win cash prize now” came out at and “are you free for lunch” at . Those totals say which side an email is on, but not how sure the filter is. Is “almost certain” or “a little more than a coin flip”?
This lesson builds a second filter on the same eight emails that answers in probabilities, such as “98% spam”. It is called naive Bayes: Bayes’ rule (P1.D6) plus one simplifying assumption. At the end you can compare the two filters email by email.
Bayes’ rule for a class
In classification the hypothesis is the class (spam or ham) and the evidence is the features (the words). P1.D6 gave the rule
Here is the prior: how common the class is before you read the email. The likelihood says how likely these words are if the class is . The left side is the posterior: what we believe after reading. The filter picks the class with the largest posterior (an argmax, the class where the quantity is biggest).
Models that estimate and and then apply Bayes’ rule are called generative (P8.1 compares them with the discriminative models that estimate directly, such as logistic regression in P3.A7).
The prior is easy: count the share of spam among the training emails. The likelihood is the hard part. An email is a whole pattern of words, and is the chance of that exact pattern in a class. With only 19 different words, each either present or absent, there are possible patterns. A table of their probabilities needs free numbers for each class (the last one is fixed because they add to 1), and our eight emails cannot fill it. Real vocabularies have tens of thousands of words.
The naive step
Naive Bayes makes one assumption: given the class, the features are independent (P1.D5). Once you know an email is spam, whether it contains “prize” tells you nothing more about whether it contains “free”. Then the chance of the whole pattern is a product of one-word chances:
The table of 524,287 numbers shrinks to 19 numbers per class (for yes/no features; a multinomial model’s 19 word chances add to 1, so 18 of them are free).
Two points about this assumption.
- It is conditional. Naive Bayes does not say the words are independent in general. Across all emails, “free” and “prize” do appear together, because both point to spam. It says that inside one class they are treated as unrelated.
- It is usually false. Inside spam, “free” and “prize” still tend to come together. That is why the method is called naive. The classifier does not need the assumption to be true to rank the classes correctly. Only the winning class matters for the decision, and in practice the ranking is often still good, although the final probabilities can be badly off (see below, and the Go-deeper box on why it can still work). That is an experience from practice, not a guarantee.
The decision rule
With the product in place, the posterior is proportional to the prior times the word chances. The denominator does not depend on the class: it is the same number for spam and for ham. Dividing every class score by the same number cannot change which is largest, so it can be dropped when we only want the winning class:
If you also want the probability, divide each score by the sum of the scores of all classes. That sum is , so nothing is lost.
Training is counting
Training means estimating the numbers in the rule from the labelled data. For naive Bayes it is just counting, in one pass over the emails.
- Prior: the class count divided by the number of emails. P0.1 has 4 spam and 4 ham emails, so .
- Word probability in a class: the number of times the word appears in the class’s emails, divided by the total number of word occurrences in that class.
This is the maximum likelihood estimate (P1.D10), the same counting rule as the coin’s “heads divided by flips”. Here the class “spam” has word occurrences and the class “ham” has , so “prize” (3 times in spam, never in ham) has estimated probability in spam and in ham. In P0.1’s emails no word repeats inside an email, so the count of a word equals the number of emails that contain it. The next cell does the counting.
Build a spam filter
This is the signature part: a few short cells you can run and change, each followed by the output it should print. They use only the standard library, so they run in the page.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
Expected output:
emails: 4 spam, 4 ham
prior P(spam): 0.5
vocabulary size V: 19
spam words N_spam: 15
ham words N_ham: 15
prize spam=3 ham=0
free spam=3 ham=1
now spam=3 ham=1
lunch spam=0 ham=2
meeting spam=0 ham=2
cash spam=1 ham=0
The vocabulary size is the same 19 words that had scores in P0.1.
The zero-count problem
Take the P0.1 email “free prize now meeting”. In training, “prize” never appears in ham and “meeting” never appears in spam. With the raw counts, the ham score has a factor (for “prize”) and the spam score has a factor (for “meeting”). Both classes get probability , and the filter has no answer. The same happens in general: a single word that never occurred in a class makes that class impossible for every email containing the word, however strong the other evidence is. In log space it would be .
The fix is to pretend we saw every word a little: add a small count to every word in every class. This is add- smoothing, and with it is Laplace smoothing or add-one smoothing. For a vocabulary of words,
where is the count of word in class and is the class’s total word count. The denominator grows by so that the probabilities still add to 1. These are the pseudo-counts of P1.D11: the coin’s “one imagined head and one imagined tail” generalizes to “ imagined occurrences of every word”.
With and , the probability of “prize” is in spam and in ham. No word has probability any more.
The size of is a setting you choose (a hyperparameter, P3.A4). Small , such as , trusts the counts; large pulls every word toward “equally likely in both classes” and weakens the evidence. The cell below shows all three cases for the same email.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
Expected output:
alpha=0: spam 0.00e+00 ham 0.00e+00
both are 0: no answer
alpha=1: spam 4.79e-05 ham 8.98e-06
P(spam) = 0.8421
alpha=0.1: spam 3.65e-05 ham 3.11e-06
P(spam) = 0.9214
Words that were never seen in training at all, such as “the” in the P0.1 email “are you free for the meeting”, are simply skipped here (scikit-learn’s CountVectorizer also ignores them). That is fair in this data because both classes have 15 words, so a new word would get exactly the same probability in both and cancel.
Scoring an email by hand
Every denominator is in both classes, so it cancels when we compare. The odds of spam against ham (with equal priors) is then the product, over the words, of .
Email 4, “win cash prize now” (the one that P0.1’s one-word rule missed). The counts (spam, ham) are win , cash , prize and now :
Odds of to mean .
Email 7, “are you free for lunch” (the real email that P0.1’s one-word rule blocked). The counts are are , you , free , for and lunch :
so and the email is ham. “Lunch” alone contributes a factor of . Each word is one vote whose strength is the ratio of its smoothed chances.
The next cell computes the same numbers in code, with logs (explained below), for all eight training emails and five new ones.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
Expected output:
P(prize|spam) = 0.1176
P(prize|ham) = 0.0294
email 4 log scores: -10.234 -14.105
training: truth, pred, P(spam)
win free prize now spam spam 0.980
free money now spam spam 0.889
claim your free prize spam spam 0.970
win cash prize now spam spam 0.980
meeting at noon ham ham 0.077
lunch now with team ham ham 0.143
are you free for lunch ham ham 0.077
project meeting notes ham ham 0.077
new emails: pred, P(spam)
win cash now spam 0.923
are you free for the meeting ham 0.077
claim your prize now spam 0.970
free prize now meeting spam 0.842
are free lunch now ham 0.400
The log scores of email 4 are for spam and for ham. Their difference is , the same as the hand calculation.
Compared with the P0.1 score filter
Both filters get all 8 training emails right and the same 3 new emails right (P0.1’s “win cash now”, “are you free for the meeting” and “claim your prize now”). Getting all of 8 right on the emails it learned from says little (P3.A4). The difference shows on other emails. P0.1’s scores for “are free lunch now” are , so it says spam. Naive Bayes gives and says ham.
The reason is how the two filters treat evidence. The score filter subtracts counts, so “now” (3 in spam, 1 in ham) gets and “are” (0 in spam, 1 in ham) gets only . Naive Bayes compares ratios: after smoothing, “now” has ratio and “are” has ratio , the same strength in opposite directions. Neither answer is “the right one” for this email; with eight training emails the data cannot say. It does show that the two filters rank evidence differently. Only the naive Bayes output is a probability that belongs to a model of how emails arise.
The log odds are a sum of word contributions
Take the logarithm of the odds (P1.A2). A product becomes a sum, so the log odds of spam is the log prior odds plus one term per word:
Each term is the log likelihood ratio of one word: positive if the word points to spam, negative if it points to ham, and larger in size for stronger evidence. With in our data, “prize” has , “win” , “free” and “now” , and “lunch” . This is the readable part of naive Bayes: you can list exactly which words pushed an email which way. The widget draws these terms as bars.
Try “win cash prize now” first: four pink bars add up to , which is spam. Then try:
- “are you free for lunch”: four blue bars and one short pink bar (“free”) add up to , which is .
- “free free free free”: a repeated word counts again each time, because the multinomial model counts occurrences. Four copies give , .
- The prior slider. At nothing changes. Move it to and “win cash now” drops from to , because the prior bar adds . The prior is the filter’s starting belief, so it should match the mix of mail the filter will see, which may differ from the training mix (P3.A10 on class imbalance).
- The slider. Raise it and every bar shrinks toward . Lower it to and “win cash prize now” rises to almost .
Why logs are not optional
A real email has hundreds of words, each with a chance such as . The product of 300 such numbers is about , which is below the smallest positive number a 64-bit float can hold, so the computer stores (this is underflow, P1.G2). Both classes would then be and the comparison is lost. The logarithm of the same product is a perfectly ordinary number, , and logs keep the order of the scores, because is increasing. So the rule is used as
To turn two log scores into a probability, subtract the larger one before exponentiating (the log-sum-exp idea of P1.G2). The next cell shows both effects.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
Expected output:
product : 0.0
log sum : -898.7
exp(ls) = 0.0 exp(lh) = 0.0
P(spam) = 0.9933
Other kinds of features
The model of depends on what the feature is. The three common choices:
- Multinomial (built here): the email is a bag of words. is the chance that a randomly picked word of a class- email is , and a word that appears times contributes times. This is the usual choice for word counts.
- Bernoulli: each vocabulary word is a yes/no feature, “present in the email” or not. A word’s absence also counts as evidence: for “win cash now” the model multiplies in the chance that every one of the other 16 words is absent. Repeats do not matter. Its smoothed estimate is .
- Gaussian: for a numeric feature, such as the number of links in an email, assume that within each class the value follows a bell curve (P1.D3). Training estimates one mean and one variance per class and feature (maximum likelihood again), and is the density at the new value.
The Gaussian version in one feature, with made-up link counts for 4 spam and 4 ham emails:
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Expected output:
spam: mean 3.0 variance 0.5
ham : mean 0.5 variance 0.25
density spam 0.2076 density ham 0.0089
P(spam | 2 links) = 0.959
A density is not a probability, but the same density scale applies to both classes, so the comparison is fair. For many numeric features, you multiply one such density per feature, which is where the naive assumption enters again.
Go deeper The Bernoulli model on the same eight emails
With and 4 emails per class, the Bernoulli probability that “prize” is present is in spam and in ham. For an email, take the log of that probability for each word that is present and the log of one minus it for each of the 19 words that is absent. The log odds for the four new emails used in the code cell come out as , , and (probabilities , , and ), the same four decisions as the multinomial model, but with different confidence. Both models get all eight training emails right.
scikit-learn’s documentation says the Bernoulli model may do better on some data sets, especially those with shorter documents. Treat that as something to test, not a rule.
What naive Bayes is good and bad at
Good.
- Fast and small. Training is one counting pass over the data. Prediction is one lookup and one addition per word. Adding a new email just updates counts, so the model can learn as mail arrives.
- Little data. It needs far fewer examples than a model with many interacting parameters, because each word probability is estimated on its own.
- Many features. A vocabulary of tens of thousands of words is no problem, which is why text is its classic use. Bayesian classifiers for junk e-mail were published in the late 1990s (Sahami and others, 1998).
- Readable. Every decision splits into per-word contributions, as in the widget.
- Many classes. The same rule works with any number of classes: compute one score per class and take the largest.
Bad.
- Repeated evidence. If two features carry the same information, the model counts it twice. Copy every word as a second feature (a “twin” of each word) and email 4’s log odds go from to , and its probability from to , although no new information arrived. Correlated words in real emails do this in a milder form.
- Extreme probabilities. Because evidence from many words is added up as if independent, the reported probabilities tend to be pushed toward 0 and 1. The filter’s ranking can be good while the number “98%” is not a trustworthy frequency. With , five words are enough for for “are you free for lunch”, and with the same email gets . Calibration (P3.A10) checks and repairs this. If you only need the class, the extreme numbers do little harm; if you use the probability for a decision, check it.
- Linear for word counts. For the multinomial and Bernoulli models the log odds are a weighted sum of the features, so the boundary between classes is a flat surface. (Gaussian naive Bayes with different variances per class gets a curved one.) That is fine for text, but it cannot represent a feature combination such as “this word matters only when that one is absent”.
- A sensitive prior and . Both are inherited from the training data or chosen by you, and both change the answers, as the widget shows.
How to judge it
A filter that is right on the emails it was trained on has only memorized them (P3.A3). Split the emails (P3.A4), train on one part, and score the other. For spam, accuracy is not enough: letting a spam through and blocking a real email are not equally costly, so look at precision and recall and move the decision threshold (P3.A9).
Go deeper Why a wrong independence assumption can still give the right class
The class only needs the larger score to belong to the right class, not the scores to be right. Domingos and Pazzani (1997, Machine Learning 29) showed that the simple Bayesian classifier can be optimal for the zero-one loss (counting mistakes) even when the features are strongly dependent, so a wrong independence assumption does not by itself make the classes come out wrong. It can still give very wrong probabilities, as the twin-feature example shows. The result says when it may work, not that it always does.
Go deeper Naive Bayes and logistic regression have the same form
The log odds above are , with the count of word , weights and the log prior odds. Logistic regression (P3.A7) has the same form, a weighted sum of the features passed through a sigmoid. The difference is how the weights are found: naive Bayes counts each word separately, logistic regression adjusts all weights together to reduce a loss, so it can give correlated words smaller weights. Ng and Jordan (2001) compared the two: naive Bayes tends to reach its best accuracy with fewer training examples, and logistic regression tends to be better when there is plenty of data.
Go deeper Add-α as a prior, and what scikit-learn adds
Add- smoothing is the posterior mean of a Dirichlet prior with every parameter equal to (P1.D11). The prior says that all words are equally likely at first and counts for imagined occurrences of each. scikit-learn’s MultinomialNB(alpha=1.0) does exactly this, and it also accepts fractional counts, such as TF-IDF weights. GaussianNB adds a tiny var_smoothing to every variance so a feature that never varies does not give a division by zero. ComplementNB and CategoricalNB are further variants.
Intuition
Think of each word as a witness. The prior is where the jury leans before anyone speaks. “Prize” is a strong witness for spam, “lunch” a strong witness for ham, and “now” is a weak one. Each witness votes with a weight, and the weights add up to a verdict.
Where the comparison breaks: real witnesses are independent people. Words in one email are not. If two witnesses are really the same person repeating the claim, the jury counts the vote twice, which is exactly the twin-feature problem.
Math
For classes and features :
Multinomial. With the count of word in the email, , where , is the count of word in class and .
Bernoulli. With and ( emails of class containing word , emails of class ): .
Gaussian. with the class mean and variance of feature .
Two classes. The log odds are with and , and .
Parameters. A full joint table for binary features needs numbers per class; naive Bayes needs .
Code
The same model in scikit-learn, shown as a static block because scikit-learn is not available in the in-browser runner. The output is from a local run (scikit-learn 1.8.0). CountVectorizer turns each email into word counts, and MultinomialNB counts and smooths them. The probabilities equal the ones from Step 3.
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
spam = ["win free prize now", "free money now",
"claim your free prize", "win cash prize now"]
ham = ["meeting at noon", "lunch now with team",
"are you free for lunch", "project meeting notes"]
texts = spam + ham
y = [1, 1, 1, 1, 0, 0, 0, 0] # 1 = spam
vec = CountVectorizer() # words -> counts
X = vec.fit_transform(texts)
model = MultinomialNB(alpha=1.0).fit(X, y)
print("X shape:", X.shape)
print("priors:", np.exp(model.class_log_prior_))
print("training accuracy:", model.score(X, y))
new = ["win cash now", "are you free for the meeting",
"claim your prize now", "free prize now meeting"]
proba = model.predict_proba(vec.transform(new))[:, 1]
for e, p in zip(new, proba):
print(f"{e:29}{p:.4f}")
names = vec.get_feature_names_out()
ratio = model.feature_log_prob_[1] - model.feature_log_prob_[0]
for w in ["prize", "win", "free", "lunch"]:
print(w, round(float(ratio[list(names).index(w)]), 3))Output:
X shape: (8, 19)
priors: [0.5 0.5]
training accuracy: 1.0
win cash now 0.9231
are you free for the meeting 0.0769
claim your prize now 0.9697
free prize now meeting 0.8421
prize 1.386
win 1.099
free 0.693
lunch -1.099Try it
Use the widget and the cells above.
- In Step 3, add a ninth training email, “free cash for lunch”, as ham. Which probabilities move, and does the new-email “win cash now” stay spam?
- In the widget, type a sentence of your own that mixes spam and ham words, then move from to . At which value does the decision flip, if it does?
- In Step 2, change
alphato and and compare the probabilities for “free prize now meeting”.
Exercises
- With and , find and .
Show answer
“Lunch” appears twice in ham and never in spam, and each class has 15 words. In ham, . In spam, . Their ratio is , so points to ham. - Score “free lunch” by hand with equal priors.
Show answer
Free is and lunch is . The odds of spam are , so and the email is ham. The P0.1 score filter gives , which it calls ham as well (not above ). - Suppose the real mail is 1% spam. Using a prior of , what does the filter say about “win cash now”, whose odds are at equal priors?
Show answer
The prior odds are , so the posterior odds are and . It is called ham. The same words are weaker evidence when spam is rare. - A new email repeats “free” four times and has no other known words. Compare the multinomial and Bernoulli models in words.
Show answer
The multinomial model counts every occurrence, so “free” contributes four times , log odds and . The Bernoulli model counts presence only, so the repeats add nothing; the four extra copies cannot make the filter more sure. - How many free numbers does a full table of the chances of 19 yes/no words need per class, and how many does naive Bayes need?
Show answer
for the full table, and for naive Bayes (one chance per word per class). - In the Gaussian cell, what is for an email with links?
Show answer
The spam density at is . The ham density is . So : very sure, because links is far from the ham mean of in units of the ham’s small spread. A real filter would not trust it that much, which shows how extreme the Gaussian model’s confidence can be. - Suppose you add the ham email “free cash for lunch” (all four words are already in the vocabulary). Why does adding it change the probabilities of emails that do not contain any of its words?
Show answer
The ham word total grows from 15 to 19, so the denominator of every smoothed ham probability changes, and the priors become for spam and for ham. Every number in the model is a count divided by a total, and those totals moved.
Check your understanding
What does naive Bayes assume is independent?
The assumption is conditional: once the class is known, the features are treated as independent, so the likelihood of the whole email is the product of the one-word likelihoods. Plain independence of the words is not assumed, and clearly does not hold across all emails, since spam words tend to appear together. The class and its prior are not features, and independence of training and new emails is a different assumption about the data.
Why can the evidence be dropped when we only want the predicted class?
The evidence is the chance of the words over all classes together, so every class score is divided by the same number and the order of the scores is unchanged. It is not equal to 1 in general, it is not always smaller than the likelihood, and the prior does not contain it. It is needed again if you want the probability: the sum of the class scores is the evidence.
A word never appears in the spam training emails. Without smoothing, what happens to an email that contains it?
The likelihood is a product, so a single factor of makes the whole product . The word is not ignored, and its probability in ham is its ham count divided by the ham total, which is not . Probabilities cannot exceed . Add- smoothing avoids the problem by giving every word a small positive count.
An email has 300 words, each with probability about in a class. Why does the filter add logarithms instead of multiplying the probabilities?
The product is about , which underflows to , while is easy to store. The logarithm is increasing, so it keeps the order of the scores rather than changing it. It does not make probabilities sum to , and the product is defined for any number of words.
Every word feature is copied, so the filter sees each word twice. With equal priors, what happens to the log odds of an email?
Each feature adds its own log likelihood ratio, and a copy adds the same term again, so the sum of the word terms doubles (the prior term, which is here, would not). Email 4 went from to and from to . Copies do not cancel, the model does not divide by the number of features, and nothing makes the total .
Next: P3.A9 gives the numbers (precision, recall, ROC) for judging a filter, and P3.A10 shows how to check and repair its probabilities. P3.A7 builds the discriminative cousin with the same linear log odds. P6.2 uses the same counting and smoothing to predict the next word.