ContentsChapter 5 · Classification2 of 3

5.2

Naive Bayes

In this chapter
  1. 5.1Logistic regression
  2. 5.2Naive Bayes
  3. 5.3Evaluation metrics
Before you readA message contains “free” and “prize”. If spam is rare, is that enough to call it spam?
Watch: Naive Bayes, Clearly Explained! · StatQuest with Josh Starmer

Logistic regression learns P(y∣x)P(y\mid x) directly. Naive Bayes learns the class prior P(y)P(y) (how common the class is) and how likely each feature is within each class. Bayes’ rule then turns those into a probability for the class given the features.

Suppose x1x_1 records whether a message contains “free” and x2x_2 whether it contains “prize”. Instead of estimating how often every combination occurs, assume the features are independent given the class:

P(x∣y)=∏jP(xj∣y).P(x\mid y)=\prod_j P(x_j\mid y).

That is the “naive” part. It says that among spam messages, seeing “free” does not change the chance of seeing “prize”. It makes no claim that the words are independent across all messages.

For each class, multiply the prior by the likelihood to get a score sy=P(y)P(x∣y)s_y=P(y)P(x\mid y) Predict the class with the larger score. To get a posterior probability, divide the score by the sum of the scores. For spam this is P(y=1∣x)=s1/(s0+s1)P(y=1\mid x)=s_1/(s_0+s_1)

Before reading10% spamAfter “free” and “prize”64% spam
Spam score: 0.10×0.8×0.50.10 \times 0.8 \times 0.5Not spam: 0.90×0.2×0.1250.90 \times 0.2 \times 0.125Spam posterior: 64%Prediction: spam
The two words are more common in spam. Lower the prior: how rare does spam have to be before the same words no longer tip the decision towards spam?

With yes/no features, the likelihood factors can be estimated by counting within each class. A zero count would wipe out the whole product. Laplace smoothing adds one count to each possible outcome before computing the fractions. Smoothing helps with rare words, but not with duplicated evidence: two copies of the same clue can make the model too confident.

Recall
What does naive Bayes assume about the features?
Recall
Why can you compare the scores without first turning them into probabilities?
Exercise
The prior probability of spam is 0.20.2 Among spam messages, half contain “free”; among other messages, one in eight does. What is the posterior probability of spam given “free”?
Exercise
None of four spam messages contains “prize”. With Laplace smoothing, what probability do you assign to seeing “prize” in a spam message?