Chapter 9 // Classification

Naive Bayes.

A message contains the word "free". How much more likely is it to be spam?

Reading time
17 min
Data

Logistic regression learns a boundary. Nearest neighbours compares with stored examples. This chapter’s classifier works a third way: it reasons about evidence. It asks how well each possible answer would explain what it sees, and it does so with nothing more than counting.

Reasoning backwards

Start with a question people reliably get wrong. A test for an illness catches 90% of the people who have it, and wrongly flags 9% of the people who do not. You test positive. How likely is it that you are ill?

Most people say about 90%. The right answer depends on something the question left out: how common the illness is.

Figure

What a positive test means

Before the test: chance of illness
10%
After a positive test
90 of 171 = 53%
10%
90%
9%
A thousand people take the test. Dark boxes are ill people who test positive; orange boxes are healthy people who test positive. Try it: with the illness at 10%, read the answer. Then drag the first slider down to 1% and watch what a positive result is worth.

When 10% of people are ill, 90 ill people test positive and so do 81 healthy ones. A positive result means a 53% chance of illness, not 90%. When only 1% are ill, the healthy false alarms swamp the real cases and a positive result means about 9%.

The 90% was the answer to a different question: if I am ill, how likely is a positive test? We wanted the reverse: given a positive test, how likely am I ill? Turning one into the other is the job of , and the figure just did it by counting. It needs two ingredients:

  • The : how likely the answer was before any evidence. Here, how common the illness is.
  • How well the evidence fits each answer: how often ill people, and healthy people, test positive.

The result, the updated belief, is called the .

Checkpoint

A smoke alarm sounds in 99% of real fires. It also sounds on 1 night in 100 with no fire, and real fires happen on 1 night in 10,000. The alarm goes off. What is the best conclusion?

One word as evidence

Now swap the illness for spam and the test for a word. Our data is a small inbox of 34 messages, 14 of them spam. So before reading a message, the chance that it is spam is 14/3414/34, about 41%. That is the prior.

Take the word “free”. Count the messages that contain it:

Contains “free”Out ofShare
Spam91464%
Normal1205%

Each share is a : how probable the evidence is under one answer. (The probability toolkit chapter has more on probabilities that depend on what is known.) “Free” is about thirteen times more common in spam, so seeing it should shift our belief strongly.

ExampleBayes' rule with the counts

Imagine the 34 messages. Of the 14 spam, 9 contain “free”. Of the 20 normal ones, 1 does. So 10 messages contain “free”, and 9 of them are spam:

P(spam∣free)=99+1=90%P(\text{spam} \mid \text{free}) = \frac{9}{9 + 1} = 90\%

One word moved the estimate from 41% to 90%.

As a formula, Bayes’ rule says the same thing:

P(spam∣word)=P(spam)×P(word∣spam)P(word)P(\text{spam} \mid \text{word}) = \frac{P(\text{spam}) \times P(\text{word} \mid \text{spam})}{P(\text{word})}

chance of spam given the word = prior × how well spam explains the word, divided by the total chance of seeing the word

Many words, one naive assumption

A message has many words, and we want to use all of them. Doing that exactly would mean knowing how likely every combination of words is in spam, and there are far too many combinations to count.

So we make a bold simplification: pretend that each word appears independently of the others, given the kind of message. Then the evidence from separate words can simply be multiplied together.

P(spam∣message)  ∝  P(spam)×P(w1∣spam)×P(w2∣spam)×…P(\text{spam} \mid \text{message}) \;\propto\; P(\text{spam}) \times P(w_1 \mid \text{spam}) \times P(w_2 \mid \text{spam}) \times \dots

This is the classifier. The assumption of is plainly false. “Prize” is far more likely when “win” is already there. That is why the method is called naive. It turns out to work well anyway, for reasons we will come to.

Multiplying many small numbers is awkward, so in practice we add their logarithms instead. Each word then contributes a push: positive toward spam, negative toward normal. The pushes add up to a score, and the score becomes a probability exactly as in logistic regression.

Figure

Every word gets a vote

↑ more like spam↓ more like a normal messageStarting point from how common spam is: -0.36free: +1.99lunch: -1.18tomorrow: -1.59-0.36+1.99-1.18-1.59
Sum of all pushes
-1.14
Chance it is spam
24%
Verdict
normal
Words not in the inbox (ignored)
none
The grey bar is the starting point from how common spam is. Each dark bar is one word's push, learned from the 34 messages. Try it: type your own messages. See how 'free lunch tomorrow' ends up normal although it contains 'free', then try 'free prize'.

The message “free lunch tomorrow” contains the spammiest common word in the inbox, yet scores as normal. “Free” pushes up by 1.99, but “lunch” and “tomorrow” push down by 1.18 and 1.59, and the starting point is already slightly negative because most messages are not spam. The model weighs all the evidence, not just the alarming part.

The word never seen

There is a trap in multiplying. The word “meeting” appears in four normal messages and in no spam at all. Its count in spam is zero, so its likelihood under spam is zero, and anything multiplied by zero is zero. A single such word makes a message impossible to be spam, whatever else it says.

That is far too strong a conclusion from 14 spam messages. Not having seen something is weak evidence that it never happens.

The standard fix is : add 1 to every count before computing the shares. A word never seen in spam is then treated as rare in spam, not impossible.

P(word∣spam)=count of the word in spam+1total words in spam+number of different wordsP(\text{word} \mid \text{spam}) = \frac{\text{count of the word in spam} + 1}{\text{total words in spam} + \text{number of different words}}

For “meeting” this gives (0+1)/(79+68)≈0.7%(0 + 1) / (79 + 68) \approx 0.7\% instead of zero.

Figure

One unseen word, with and without smoothing

↑ more like spam↓ more like a normal messageStarting point from how common spam is: -0.36free: +1.99now: +1.59your: +1.12meeting: -1.41-0.36+1.99+1.59+1.12-1.41
Sum of all pushes
+2.94
Chance it is spam
95%
Verdict
spam
Words not in the inbox (ignored)
none
A bar labelled ∞ is an infinite push: it overrules everything else.
The message has three spammy words and one word that never appeared in spam. Try it: read the verdict with smoothing on. Then switch smoothing off and watch one bar overrule all the others.

With smoothing the message is judged about 95% likely to be spam. Without it, “meeting” has an infinite push the other way and the answer is 0%.

Why something so naive works

The independence assumption is wrong, so the probabilities Naive Bayes produces are wrong too. Related words get counted as separate pieces of evidence when they are really one, which makes the model overconfident: it says 99.9% where 90% would be honest.

But classification needs only the right side of 50%, not the right number. Overcounting evidence usually pushes the score further in the direction it was already going. The ranking of messages stays sensible even when the probabilities are exaggerated.

The simplicity also buys real advantages:

  • Training is one pass of counting. No gradient descent, no learning rate, nothing to tune except the smoothing.
  • It needs little data. Each word’s counts are estimated separately, so a few dozen examples already give a usable model.
  • It handles thousands of features without trouble, where nearest neighbours would be lost.

Its weakness is the one already named: when features are strongly related, or when you need trustworthy probabilities, logistic regression is usually the better choice.

Checkpoint

A Naive Bayes spam filter says a message is 99.99% likely to be spam. How should you read that number?

In code

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import make_pipeline

# texts: a list of message strings.   is_spam: 1 for spam, 0 for normal.
model = make_pipeline(
    CountVectorizer(),            # turns each message into word counts
    MultinomialNB(alpha=1.0),     # alpha is the smoothing: add 1 to every count
)
model.fit(texts, is_spam)

print(model.predict(["free lunch tomorrow"]))          # [0]: normal
print(model.predict_proba(["free prize"])[0, 1])       # 0.97: chance of spam

CountVectorizer builds the table of word counts and MultinomialNB applies Bayes’ rule to it. Training on a million messages takes seconds.

Key Takeaways

  • Bayes’ rule turns “how likely is this evidence if the answer is yes” into “how likely is yes given this evidence”. It needs the prior.
  • Rare things stay unlikely even after strong evidence. Ignoring how rare they are is the classic mistake.
  • Naive Bayes treats every feature as independent evidence and multiplies, or adds logs.
  • Smoothing stops one unseen word from vetoing everything else.
  • It is fast, needs little data and ranks well, but its probabilities are overconfident.
You can now
  • Use Bayes’ rule to turn “how likely is the evidence” into “how likely is the cause”.
  • Classify a short message by hand with Naive Bayes.
  • Explain what smoothing fixes.
  • Say why the method works despite its assumption being false, and where it should not be trusted.

Exercises

Try each one before opening its solution. Getting stuck for a few minutes is where most of the learning happens.

Exerciseby hand

A test catches 90% of the people who have an illness and wrongly flags 5% of the people who do not. One person in a hundred has the illness. Someone tests positive. How likely is it that they are ill? Work it out by imagining 10,000 people.

Hint

Of 10,000 people, how many are ill and test positive? How many are healthy and test positive?

Solution

Of 10,000 people, 100 are ill and 9,900 are healthy.

  • Ill and positive: 90% of 100 is 90.
  • Healthy and positive: 5% of 9,900 is 495.

There are 585 positive results, and 90 of them belong to ill people: 90/585≈15%90 / 585 \approx 15\%.

A positive result raised the chance from 1% to about 15%. That is a big change, and still far from the 90% most people guess. The healthy group is so much larger that even a small error rate produces more false alarms than there are real cases.

Exerciseby hand

An inbox has 10 spam messages and 20 normal ones. The spam messages contain 100 words in total, with “prize” appearing 6 times and “meeting” once. The normal messages contain 200 words, with “prize” appearing once and “meeting” 10 times. Classify the message “prize meeting” without smoothing.

Hint

For each class, multiply the prior by the share of each word. Then compare the two products.

Solution

Priors: 10/30=1/310/30 = 1/3 for spam and 2/32/3 for normal.

Word shares in spam: “prize” 6/100=0.066/100 = 0.06, “meeting” 1/100=0.011/100 = 0.01. In normal: “prize” 1/200=0.0051/200 = 0.005, “meeting” 10/200=0.0510/200 = 0.05.

Multiply the prior by the share of each word:

  • Spam: 13×0.06×0.01=0.0002\tfrac{1}{3} \times 0.06 \times 0.01 = 0.0002
  • Normal: 23×0.005×0.05≈0.000167\tfrac{2}{3} \times 0.005 \times 0.05 \approx 0.000167

Spam has the larger score. As a probability, 0.0002/(0.0002+0.000167)≈55%0.0002 / (0.0002 + 0.000167) \approx 55\%. The two words pull in opposite directions and nearly cancel, so the model is barely more sure than a coin.

Exerciseby hand

In the same inbox the word “lottery” appears 3 times in spam and never in normal messages. The inbox uses 50 different words. What share does “lottery” get in each class without smoothing, and with it? Why does the difference matter?

Hint

Smoothing adds 1 to the count on top and the number of different words to the total underneath.

Solution

Without smoothing. Spam: 3/100=0.033 / 100 = 0.03. Normal: 0/200=00 / 200 = 0.

With smoothing. Spam: (3+1)/(100+50)≈0.027(3 + 1) / (100 + 50) \approx 0.027. Normal: (0+1)/(200+50)=0.004(0 + 1) / (200 + 50) = 0.004.

Without smoothing, the zero wipes out the whole product for the normal class. Any message containing “lottery” is declared spam with complete certainty, whatever else it says. With smoothing, “lottery” is still strong evidence for spam, about seven times more likely there, but other words can outweigh it.

Exercisethink

Naive Bayes assumes the words in a message are independent of each other given the class. Give an example where that is plainly false, and say what effect it has on the model’s output.

Hint

Think of two words that tend to turn up together in spam.

Solution

“Free” and “prize” tend to appear together in spam. Once you have seen “free”, seeing “prize” is less of a surprise and so carries less new information. The model does not know that. It counts both words at full strength, as if they were two separate pieces of evidence.

The effect is overconfidence. Related words are double-counted, pushing probabilities towards 0% and 100%. The side that wins is usually still the right one, because the evidence does point that way, so the classification is good even though the stated probability is not. Trust the ranking, and be wary of the percentage.

Exercisewith the figure

In the figure “What a positive test means”, set the share of people who are ill to 10%, then 5%, then 1%, and write down what a positive result means each time. Why does the same test give such different answers?

Hint

The test did not change. Count how many healthy people there are to raise false alarms.

Solution

At 10% a positive result means a 53% chance of illness. At 1% it means about 9%. At 5% it falls in between, at roughly a third.

The test catches the same share of ill people and wrongly flags the same share of healthy people throughout. What changes is how many healthy people there are. When the illness is rare, the healthy group is so large that its small share of false alarms outnumbers the real cases. This is why the prior belongs in every such calculation.

Going further

Numbers instead of words

For numeric features, such as height or temperature, there is nothing to count. Gaussian Naive Bayes instead fits a bell curve to each feature within each class, and uses the height of the curve as the likelihood. Everything else is unchanged.

Models that describe the data

Naive Bayes is a generative model: it learns what each class looks like, and classifies by asking which class best explains the input. Logistic regression is discriminative: it learns only the boundary between classes. Generative models can cope with missing features and tiny datasets; discriminative ones usually win when data is plentiful.

References and further reading

Last updated Spotted a mistake? Suggest an editWhat changed

In this chapter
  1. Top of the chapter
  2. 9.1Reasoning backwards
  3. 9.2One word as evidence
  4. 9.3Many words, one naive assumption
  5. 9.4The word never seen
  6. 9.5Why something so naive works
  7. 9.6In code
  8. Exercises
Search

    The Book of Machine Learning
    Search
    Reading settings
    Text size
    Colours

    Saved in this browser only.

    Keyboard shortcuts
    /
    Search the book
    ← →
    Previous and next chapter
    g
    Glossary
    c
    Table of contents
    e
    Jump to the exercises
    t
    Reading settings
    ?
    Show this list
    Esc
    Close a window or pop-in