Skip to content

MLDay 21 of 50Supervised and Unsupervised Learning

Naive Bayes

A text arrives: "Claim your free prize now."

9 min read

A text arrives: "Claim your free prize now." Every word in it is a clue, and your filter has thousands of labelled texts to learn from. Naive Bayes learns those clues just by counting words, and Bayes' rule turns them into a chance that the text is spam.

The idea

A spam filter needs two kinds of knowledge.

  1. The prior: how common spam is before you read a word. If 1 text in 5 is spam, P(spam)=0.2P(\text{spam}) = 0.2.
  2. The likelihoods: how typical each word is of each class. P(free∣spam)P(\text{free} \mid \text{spam}), read "the chance of free given spam", is how often spam uses the word free.

You can count likelihoods from labelled texts. But you want the reverse: the chance of spam given the words. Bayes' rule flips one into the other.

A message has many words, so Naive Bayes multiplies their likelihoods together. That is only right if the words are independent once you know the class: seeing free says nothing about whether prize shows up. Real spam breaks this, since free and prize travel together. Assuming it anyway is the naive part.

Training is one pass of counting, with no gradient descent, so it fits in seconds. It differs from logistic regression, which learns one weight per word to separate the classes. Naive Bayes instead learns how each class writes.

A tiny example

Six short texts, two of them spam:

Spam Ham (not spam)
free cash lunch today
free prize call later
free lunch
see you
  • Prior: 2 of 6 texts are spam, so P(spam)=1/3P(\text{spam}) = 1/3 and P(ham)=2/3P(\text{ham}) = 2/3.
  • Likelihoods: spam has 4 words, and 2 are free, so P(free∣spam)=2/4P(\text{free} \mid \text{spam}) = 2/4. Ham has 8 words, and 1 is free, so P(free∣ham)=1/8P(\text{free} \mid \text{ham}) = 1/8.

Score a new text, "free". Multiply each class's prior by its likelihood:

  • spam: 1/3×1/2=1/61/3 \times 1/2 = 1/6
  • ham: 2/3×1/8=1/122/3 \times 1/8 = 1/12

As a probability, P(spam∣free)=1/61/6+1/12=2/3P(\text{spam} \mid \text{free}) = \frac{1/6}{1/6 + 1/12} = 2/3.

Now score "free lunch". Lunch never appears in spam, so P(lunch∣spam)=0P(\text{lunch} \mid \text{spam}) = 0. The spam score becomes 0, and the answer is "certainly ham", whatever else the text says. One unseen word vetoes everything.

The fix is Laplace smoothing: add 1 to every word's count in every class, so no likelihood is ever 0. The formula below finishes this example with it.

The formula

Bayes' rule turns the likelihood of a word into the probability of spam:

P(spam∣word)=P(word∣spam) P(spam)P(word∣spam) P(spam)+P(word∣ham) P(ham)P(\text{spam} \mid \text{word}) = \frac{P(\text{word} \mid \text{spam})\, P(\text{spam})}{P(\text{word} \mid \text{spam})\, P(\text{spam}) + P(\text{word} \mid \text{ham})\, P(\text{ham})}
Symbol Meaning
P(spam)P(\text{spam}) the prior: the share of texts that are spam
P(ham)P(\text{ham}) 1−P(spam)1 - P(\text{spam})
P(word∣spam)P(\text{word} \mid \text{spam}) the likelihood: how often spam uses the word
P(spam∣word)P(\text{spam} \mid \text{word}) the answer: the chance of spam once you've seen the word

The bottom line is just the top line plus the same score for ham, so the two answers add up to 1.

Worked, for a filter with P(spam)=0.2P(\text{spam}) = 0.2, P(free∣spam)=0.3P(\text{free} \mid \text{spam}) = 0.3 and P(free∣ham)=0.02P(\text{free} \mid \text{ham}) = 0.02: 0.3×0.20.3×0.2+0.02×0.8=0.060.06+0.016≈0.79\frac{0.3 \times 0.2}{0.3 \times 0.2 + 0.02 \times 0.8} = \frac{0.06}{0.06 + 0.016} \approx 0.79. Free is 15 times as common in spam, so a 20% prior jumps to 79%.

For a whole message, each class gets a score: its prior times the likelihood of every word in the text.

score(c)=P(c)∏i=1kP(wi∣c),P(w∣c)=count(w,c)+1words(c)+V\text{score}(c) = P(c) \prod_{i=1}^{k} P(w_i \mid c), \qquad P(w \mid c) = \frac{\text{count}(w, c) + 1}{\text{words}(c) + V}
Symbol Meaning
cc a class: spam or ham
w1,…,wkw_1, \dots, w_k the kk words in the text
∏\prod multiply all the terms together
count(w,c)\text{count}(w, c) how many times word ww appears in class cc's training texts
words(c)\text{words}(c) the total number of words in class cc's training texts
VV the vocabulary size: how many different words training saw

P(spam∣text)P(\text{spam} \mid \text{text}) is then the spam score divided by the sum of both scores.

Worked, "free lunch" with smoothing: the six texts use V=9V = 9 different words, so spam's likelihoods become 2+14+9=313\frac{2+1}{4+9} = \frac{3}{13} for free and 0+113\frac{0+1}{13} for lunch. Ham's are 1+18+9=217\frac{1+1}{8+9} = \frac{2}{17} and 2+117=317\frac{2+1}{17} = \frac{3}{17}. The spam score is 13×313×113≈0.0059\frac{1}{3} \times \frac{3}{13} \times \frac{1}{13} \approx 0.0059, and the ham score is 23×217×317≈0.0138\frac{2}{3} \times \frac{2}{17} \times \frac{3}{17} \approx 0.0138. So P(spam∣free lunch)=0.00590.0059+0.0138≈0.30P(\text{spam} \mid \text{free lunch}) = \frac{0.0059}{0.0059 + 0.0138} \approx 0.30: unlikely, but no longer ruled out.

Try it

Read a text word by word

Tick the words the message contains. Each one multiplies the odds of spam by its ratio P(word | spam) / P(word | ham): above 1 pushes toward spam, below 1 toward ham.

Each word's likelihoods and evidence
in the message?P(word | spam)P(word | ham)ratiolog-odds
0.30.02×15+2.71
0.10.002×50+3.91
0.40.05×8+2.08
0.330.29×1.14+0.13
0.010.1×0.1-2.3
0.0050.025×0.2-1.61

odds of spam: prior 1 = 1

P(spam | message) = 0.5 / (0.5 + 0.5) = 0.5

P(spam) before reading 0.5P(spam | message) 0.50 of 6 words ticked

In the last sum, the first number is P(spam) · Π P(word | spam) and the second is P(ham) · Π P(word | ham): Bayes' rule, treating the words as independent once you know the class (the “naive” part). Unticked words are left out.

The prior starts at 0.5, but spam is far rarer than half. Set it to 0.2 and tick free to get the worked 0.79, then tick later and watch it fall to 0.27. Ticking free and prize gives 0.99, because the filter counts two clues that usually come together as separate evidence. Then drag the prior to 0.01 with only free ticked: the same word now gives just 0.13.

In code

MultinomialNB is scikit-learn's Naive Bayes for word counts, and CountVectorizer makes the counts. On the six texts it reproduces the hand numbers.

# script_id: day_021_naive_bayes/toy
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB

texts = ["free cash", "free prize",                                    # spam
         "lunch today", "call later", "free lunch", "see you"]        # ham
labels = [1, 1, 0, 0, 0, 0]                                            # 1 = spam

vec = CountVectorizer()
nb = MultinomialNB().fit(vec.fit_transform(texts), labels)             # alpha=1.0: add 1 to every count
probs = np.exp(nb.feature_log_prob_)                                   # rows: ham, spam
for word in ["free", "lunch"]:
    j = vec.vocabulary_[word]
    print(f"P({word} | spam) = {probs[1, j]:.3f}   P({word} | ham) = {probs[0, j]:.3f}")
print(f"P(spam) = {np.exp(nb.class_log_prior_[1]):.3f}")
print(f"P(spam | 'free lunch') = {nb.predict_proba(vec.transform(['free lunch']))[0, 1]:.2f}")
P(free | spam) = 0.231   P(free | ham) = 0.118
P(lunch | spam) = 0.077   P(lunch | ham) = 0.176
P(spam) = 0.333
P(spam | 'free lunch') = 0.30

These are 3/133/13, 2/172/17, 1/131/13 and 3/173/17 from the smoothed formula. alpha is the number added to every count: 1.0 by default. The model stores log probabilities (feature_log_prob_), because multiplying hundreds of small numbers would round down to 0.

Now the real SMS Spam Collection: 5,574 texts, 13.4% of them spam. The script drops the 403 repeated texts first, so no copy lands in both the training and test sets (D06). Then it puts Naive Bayes next to D20's TF-IDF + logistic regression, each in a Pipeline.

# script_id: day_021_naive_bayes/sms
import os
from pathlib import Path

import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import precision_score, recall_score
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import make_pipeline

DATA_DIR = Path(os.environ.get("ML_DATA", "datasets"))
df = pd.read_csv(DATA_DIR / "sms_spam" / "SMSSpamCollection", sep="\t", header=None,
                 names=["label", "text"], quoting=3)
df = df.drop_duplicates("text")                    # 403 repeats out, before splitting
y = (df["label"] == "spam").astype(int)
X_tr, X_te, y_tr, y_te = train_test_split(df["text"], y, test_size=0.25, stratify=y, random_state=42)

models = {"Naive Bayes, counts": make_pipeline(CountVectorizer(), MultinomialNB()),
          "LogReg, TF-IDF (D20)": make_pipeline(TfidfVectorizer(), LogisticRegression())}
for name, model in models.items():
    p = model.fit(X_tr, y_tr).predict_proba(X_te)[:, 1]
    pred = (p > 0.5).astype(int)
    sure = np.mean((p < 0.01) | (p > 0.99))        # share of near-certain answers
    print(f"{name:21} precision {precision_score(y_te, pred):.3f}  recall {recall_score(y_te, pred):.3f}  "
          f"near-certain {sure:.0%}")

nb_model = models["Naive Bayes, counts"]
vec, nb = nb_model[0], nb_model[1]
ratio = np.exp(nb.feature_log_prob_[1] - nb.feature_log_prob_[0])   # P(word | spam) / P(word | ham)
top = np.argsort(ratio)[::-1][:5]
words = vec.get_feature_names_out()
print("strongest spam words:", ", ".join(f"{words[i]} x{ratio[i]:.0f}" for i in top))
Naive Bayes, counts   precision 0.949  recall 0.914  near-certain 91%
LogReg, TF-IDF (D20)  precision 0.967  recall 0.730  near-certain 1%
strongest spam words: claim x183, prize x172, nokia x112, 150p x106, co x93

Precision and recall are D13's. At the default 0.5 cut-off, Naive Bayes catches 91% of the test spam, and logistic regression catches 73%. Part of that gap is the cut-off itself, which D13 shows how to move. The word ratios are the playground's ratio column, learned from real texts: claim is 183 times as likely in spam.

Quick check

Quick check

1. P(spam) = 0.5, P("free" | spam) = 0.3 and P("free" | ham) = 0.02. What is P(spam | "free")?

2. A word never appeared in any training spam. Without smoothing, what happens to a new text that contains it?

3. What is "naive" about Naive Bayes?

Next

D22: Project 2: an SMS Spam Filter pits Naive Bayes against logistic regression under one protocol, with a tuned cut-off and a look at their mistakes.

Data: SMS Spam Collection v.1 (UCI Machine Learning Repository, dataset 228), CC BY 4.0; cite Almeida, T. A., Gómez Hidalgo, J. M. and Yamakami, A. (2011), "Contributions to the Study of SMS Spam Filtering: New Collection and Results", Proceedings of the 2011 ACM Symposium on Document Engineering.

Next · Day 22 · 10 minProject 2: an SMS Spam Filter← Previous: Day 20 · Turn Text into Features: Bag-of-Words and TF-IDF
Not tapped yet