Traditional models · lesson 3 of 16
Parts in this lesson
ACountVectorizer().fit_transform(texts)4.2: one column per word, one count per message
B(counts + alpha) / (counts.sum() + alpha * V)word probabilities, smoothed
CMultinomialNB(alpha=1.0)naive Bayes for counts
DGaussianNB()naive Bayes for measurements

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 c (spam or ok) and a message x:

p(c∣x)=p(x∣c)p(c)p(x)

To classify, you only need to know which class has the bigger p(c∣x). The bottom, p(x), is the same for every class, so it can be ignored:

cˆ=argmaxc⁡p(c)p(x∣c)

p(c), the prior, is how common each class is. p(x∣c), 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:

p(x∣c)=∏jp(wj∣c)

where wj is the message's jth 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):

naive-bayes.ipynb

16 messages, 81 different words. Add up each word's counts in each class:

naive-bayes.ipynb

"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 p(claim∣spam) is 467.

Wrong way: a word never seen

Use those raw fractions on "click the link for the meeting notes":

naive-bayes.ipynb

Both come out exactly 0. "meeting" was never seen in spam, so p(meeting∣spam)=0, 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:

p(w∣c)=count(w,c)+α∑w′count(w′,c)+αV

with V the number of different words (81). With α=1, "meeting" in spam becomes 0+167+81=1148: 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:

naive-bayes.ipynb

The product is 10−1200, far below the smallest number a float can hold (about 10−308), 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:

cˆ=argmaxc⁡[log⁡p(c)+∑jlog⁡p(wj∣c)]

The whole classifier, by hand, smoothed and in logs:

naive-bayes.ipynb

"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:

Word scalesnaive Bayes, trained on 16 messages
spamclaim 1.6your 1.6free 1.4load 0.7now 1.4not spam

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:

naive-bayes.ipynb

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:

naive-bayes.ipynb

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

When to use naive Bayes

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

Why is naive Bayes called naive?
Without smoothing, a new message contains “refund”, a word that appeared only in ok messages in training. What is its spam score?
Why does naive Bayes add log-probabilities instead of multiplying probabilities?

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.

All sources for Simple Machine Learning