MLDay 21 of 50Supervised and Unsupervised Learning
Naive Bayes
A text arrives: "Claim your free prize now."
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.
- The prior: how common spam is before you read a word. If 1 text in 5 is spam, .
- The likelihoods: how typical each word is of each class. , 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 and .
- Likelihoods: spam has 4 words, and 2 are free, so . Ham has 8 words, and 1 is free, so .
Score a new text, "free". Multiply each class's prior by its likelihood:
- spam:
- ham:
As a probability, .
Now score "free lunch". Lunch never appears in spam, so . 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:
| Symbol | Meaning |
|---|---|
| the prior: the share of texts that are spam | |
| the likelihood: how often spam uses the 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 , and : . 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.
| Symbol | Meaning |
|---|---|
| a class: spam or ham | |
| the words in the text | |
| multiply all the terms together | |
| how many times word appears in class 's training texts | |
| the total number of words in class 's training texts | |
| the vocabulary size: how many different words training saw |
is then the spam score divided by the sum of both scores.
Worked, "free lunch" with smoothing: the six texts use different words, so spam's likelihoods become for free and for lunch. Ham's are and . The spam score is , and the ham score is . So : 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.
| in the message? | P(word | spam) | P(word | ham) | ratio | log-odds | |
|---|---|---|---|---|---|
| 0.3 | 0.02 | ×15 | +2.71 | ||
| 0.1 | 0.002 | ×50 | +3.91 | ||
| 0.4 | 0.05 | ×8 | +2.08 | ||
| 0.33 | 0.29 | ×1.14 | +0.13 | ||
| 0.01 | 0.1 | ×0.1 | -2.3 | ||
| 0.005 | 0.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 , , and 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.