Naive Bayes
Last updated
The first spam filters that really worked, in the late 1990s, did nothing cleverer than count words. How often does “claim” appear in spam? In ordinary messages? Bayes' rule turns those counts into a probability that a new message is spam. The method makes an assumption everyone knows is false, and works well anyway. You'll build it by hand, break it twice, fix it twice, and then use scikit-learn's version.
By the end of this lesson you can
- Apply Bayes' rule to choose a class, and explain the naive independence assumption
- Estimate word probabilities from counts, with Laplace smoothing
- Explain why naive Bayes adds logs instead of multiplying probabilities
- Fit MultinomialNB on text and GaussianNB on numbers, and say when to use them
Bayes' rule for classes
Lesson 1.9's Bayes' rule, with a class (spam or ok) and a message :
To classify, you only need to know which class has the bigger . The bottom, , is the same for every class, so it can be ignored:
, the prior, is how common each class is. , the likelihood, is how likely this message would be if it were spam, or if it were ok. The prior is easy: count. The likelihood of a whole message is the hard part. No message has been seen before, word for word.
The naive assumption
The way out is an assumption: given the class, every word appears independently of every other. Then the likelihood of a message is just the product of its words' likelihoods:
where is the message's th word. It's called naive because it's plainly false. In spam, "click" and "link" go together far more than chance. But the classifier only needs the right class to come out on top, not the probabilities to be right, and Domingos and Pazzani showed that it often does even when the words depend on each other strongly. The probabilities themselves come out too extreme, close to 0 or 1; don't trust them as they are.
Counting words
Sixteen short messages, eight spam and eight ok, turned into word counts (lesson 4.2):
16 messages, 81 different words. Add up each word's counts in each class:
"claim" is in spam 4 times and ok messages never; "meeting" the other way round; "the" is in both. Across all the spam there are 67 words, and 65 across the ok messages. So the obvious estimate of is .
Wrong way: a word never seen
Use those raw fractions on "click the link for the meeting notes":
Both come out exactly 0. "meeting" was never seen in spam, so , and a product with one 0 in it is 0, whatever the other words say. "click" and "link" were never in ok messages, so that side is 0 too. One unseen word vetoes a whole class, and here both classes are vetoed.
The fix, Laplace smoothing, pretends every word was seen extra times in every class:
with the number of different words (81). With , "meeting" in spam becomes : unlikely, but not impossible. Words never seen in any training message are simply skipped.
Logs, to avoid underflow
A long message multiplies many small probabilities. 400 words of probability 0.001 each:
The product is , far below the smallest number a float can hold (about ), so it underflows to 0.0, and every class ties. The sum of the logs is −2,763, a perfectly ordinary number. Since log only ever goes up when its input goes up, the class with the biggest product also has the biggest sum of logs:
The whole classifier, by hand, smoothed and in logs:
"claim your free load now" scores −18.99 as spam and −25.61 as ok: spam, clearly. "see you at the meeting on sunday" goes the other way. Each word adds its own log weight to each side, like weights on a balance:
Spam pan 6.62, not-spam pan 0: a score of 6.62, so naive Bayes says spam, with p(spam) = 0.999. Each word’s weight is the log of how many times likelier it is in spam than in ordinary messages.
MultinomialNB
scikit-learn's MultinomialNB is exactly this, for counts. In a pipeline with the vectoriser:
The spelling-game spam ("Fr3e l0ad") is still caught, by "for", "you", "reply" and "yes", and the message about Sunday's photos is ok even though it has "click" and "link" in it. The probabilities in the second cell are the class probabilities, ok first then spam, in alphabetical order. They're very confident: naive Bayes' probabilities usually are (step 2).
Sixteen messages is a toy. A real filter trains on thousands, and the same few lines of code work: naive Bayes trains in one pass over the data, just counting.
Numbers too: GaussianNB
For measurements instead of counts, GaussianNB assumes each feature follows a bell curve (lesson 1.10) within each class, and learns each curve's mean and spread:
97.1% of penguins right, cross-validated, from four bell curves per species. The table is what it learned: each species' mean of each measurement. A new penguin is scored by how likely its measurements are under each species' curves.
There's no naive Bayes for regression. It's a classifier only.
When to use it
Good at
- Text: word counts, spam, topics, sentiment
- Very little training data
- Speed: trains in one pass, and works with many thousands of features
- A first baseline for any classification
Bad at
- Features that depend on each other strongly (it counts the same evidence twice)
- Probabilities: too close to 0 and 1 to use as they are
- Beating a tuned logistic regression when there is plenty of data
Needs from you
- Counts or frequencies for MultinomialNB; roughly bell-shaped numbers for GaussianNB
- No scaling
- Choose the smoothing, alpha, by cross-validation
In scikit-learn
- Classification:
MultinomialNB,GaussianNB,ComplementNB(for uneven classes) - Regression: none
Check what you learned
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- scikit-learn: Naive Bayes: MultinomialNB, GaussianNB and the smoothing parameter alpha
- Domingos and Pazzani, On the optimality of the simple Bayesian classifier under zero-one loss, Machine Learning 29, 1997: why naive Bayes classifies well even when its independence assumption is false
- Manning, Raghavan and Schütze, Introduction to Information Retrieval, chapter 13, Cambridge University Press, 2008: text classification with multinomial naive Bayes, and add-one smoothing