MLDay 22 of 50Supervised and Unsupervised Learning
Project 2
an SMS Spam Filter
A phone company wants a spam filter for text messages. Spam that slips into the inbox is annoying. A real message from a friend that lands in the spam folder is worse, because nobody looks there.
The idea
This project builds the filter the way a team would, and lets two models compete on equal terms.
- Load 5,574 labelled messages.
- Deduplicate first. Drop repeated texts before splitting. Otherwise a copy of a test message sits in training, and the test score rewards memory, the leak from Day 6.
- Split, stratified. A stratified split keeps the spam share the same in training and test.
- Two models, one protocol. Naive Bayes on word counts (Day 21) against TF-IDF + logistic regression (Day 20). Both get the same 5 folds of cross-validation (Day 10), the same cost and the same test set.
- Pick a threshold for the cost, on the training folds only, as in Day 13.
- Read the mistakes. A table of the real messages each model scored highest and the spam it scored lowest, on the test set.
- Name the winner, and why.
The stated cost: a real message blocked (a false positive, FP) costs 10 times as much as a spam let through (a false negative, FN).
The formula
The cost is what the threshold minimizes.
| Symbol | Meaning |
|---|---|
| false positives: real messages sent to the spam folder | |
| false negatives: spam messages let into the inbox | |
| 10, 1 | the price of each mistake, set by the business, not by the model |
Worked, logistic regression on the test set: . Naive Bayes: .
Precision and recall describe the chosen threshold in words a team can read.
| Symbol | Meaning |
|---|---|
| true positives: spam correctly blocked | |
| precision | of the messages blocked, the share that really is spam |
| recall | of all the spam, the share that gets blocked |
Worked, logistic regression: the test set has 131 spam and it misses 33, so . Precision is and recall is .
In code
The steps below are one script, run top to bottom.
Step 1: load. Each line of the file is a label (ham means a real message) and the text.
# script_id: day_022_project_sms_spam_filter/spam_filter
import os
from pathlib import Path
import matplotlib.pyplot as plt
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 average_precision_score, precision_recall_curve
from sklearn.model_selection import StratifiedKFold, cross_val_predict, 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)
print(df.shape, df["label"].value_counts().to_dict())
(5574, 2) {'ham': 4827, 'spam': 747}
Step 2: deduplicate before splitting. First, see what goes wrong without it.
# script_id: day_022_project_sms_spam_filter/spam_filter
leaky_train, leaky_test = train_test_split(df, test_size=0.2, stratify=df["label"], random_state=42)
print("test texts also in training:", leaky_test["text"].isin(leaky_train["text"]).sum(), "of", len(leaky_test))
df = df.drop_duplicates("text")
print("unique messages:", len(df))
test texts also in training: 135 of 1115
unique messages: 5171
Without the drop, 135 test messages are answers the model has already seen. Dropping the 403 repeats fixes that.
Step 3: a stratified split. stratify=y keeps about 12.6% spam on both sides.
# script_id: day_022_project_sms_spam_filter/spam_filter
y = (df["label"] == "spam").astype(int) # 1 = spam
X_train, X_test, y_train, y_test = train_test_split(
df["text"], y, test_size=0.2, stratify=y, random_state=42)
print(f"train {len(X_train):,} ({y_train.sum()} spam), test {len(X_test):,} ({y_test.sum()} spam)")
train 4,136 (522 spam), test 1,035 (131 spam)
Step 4: two models, one protocol. Each model is a pipeline, so the vocabulary is learned inside each
training fold. cross_val_predict gives every training message a spam probability from a model that never saw
it: an out-of-fold prediction. PR-AUC is Day 13's area under the precision-recall curve.
# script_id: day_022_project_sms_spam_filter/spam_filter
models = {
"Naive Bayes": make_pipeline(CountVectorizer(), MultinomialNB()),
"TF-IDF + LogReg": make_pipeline(TfidfVectorizer(), LogisticRegression()),
}
folds = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
oof = {name: cross_val_predict(m, X_train, y_train, cv=folds, method="predict_proba")[:, 1]
for name, m in models.items()}
for name, p in oof.items():
print(f"{name:<16} PR-AUC {average_precision_score(y_train, p):.3f}")
Naive Bayes PR-AUC 0.955
TF-IDF + LogReg PR-AUC 0.967
On the summary score, logistic regression is slightly ahead. The cost decides, though. Tuning logistic regression's C (Day 11) doesn't change the winner: even at its best of C = 1, 10 and 100 (C = 10), its training-fold cost is 130, still above Naive Bayes's 75.
Step 5: a threshold for the cost. Try every threshold from 0.01 to 0.99 on the out-of-fold predictions, and keep the cheapest.
# script_id: day_022_project_sms_spam_filter/spam_filter
def cost(y_true, p, t):
blocked = p >= t
fp = (blocked & (y_true == 0)).sum()
fn = (~blocked & (y_true == 1)).sum()
return 10 * fp + fn, fp, fn
thresholds = np.arange(0.01, 1.0, 0.01)
chosen = {}
for name, p in oof.items():
chosen[name] = thresholds[np.argmin([cost(y_train.to_numpy(), p, t)[0] for t in thresholds])]
c, fp, fn = cost(y_train.to_numpy(), p, chosen[name])
precision, recall, _ = precision_recall_curve(y_train, p)
print(f"{name:<16} threshold {chosen[name]:.2f}: {fp} FP, {fn} FN, cost {c}; "
f"recall at 100% precision {recall[precision == 1].max():.0%}")
Naive Bayes threshold 0.95: 0 FP, 75 FN, cost 75; recall at 100% precision 86%
TF-IDF + LogReg threshold 0.47: 3 FP, 128 FN, cost 158; recall at 100% precision 26%
The PR curves show why. The dots mark each chosen threshold.
# script_id: day_022_project_sms_spam_filter/spam_filter
FIG_DIR = Path(os.environ.get("ML_FIG_DIR", "figures"))
FIG_DIR.mkdir(exist_ok=True)
fig, ax = plt.subplots(figsize=(6, 4))
for (name, p), color in zip(oof.items(), ["#2a78d6", "#eb6834"]):
precision, recall, _ = precision_recall_curve(y_train, p)
ax.plot(recall, precision, color=color, lw=2, label=name)
hit = p >= chosen[name]
ax.plot(hit[y_train == 1].mean(), y_train[hit].mean(), "o", color=color, ms=8)
ax.set(title="Near 100% precision, Naive Bayes catches far more spam",
xlabel="Recall (share of spam blocked)", ylabel="Precision (share of blocked that is spam)",
ylim=(0.5, 1.02))
ax.grid(alpha=0.3)
ax.legend(loc="lower left")
fig.tight_layout()
fig.savefig(FIG_DIR / "pr_curves.png", dpi=120)
plt.close(fig)

Logistic regression pulls ahead only past about 90% recall, where precision has started to fall. This cost lives on the flat top of the curve, where almost nothing real gets blocked. There, Naive Bayes still catches 86% of spam and logistic regression only 26%.
Step 6: score the test set once, and read the mistakes. Each model is refitted on all training messages. The table lists each model's three highest-scored real messages and three lowest-scored spam messages.
# script_id: day_022_project_sms_spam_filter/spam_filter
texts, truth = X_test.str.slice(0, 45).to_numpy(), y_test.to_numpy()
for name, m in models.items():
p = pd.Series(m.fit(X_train, y_train).predict_proba(X_test)[:, 1])
c, fp, fn = cost(truth, p.to_numpy(), chosen[name])
tp = truth.sum() - fn
print(f"{name}: {fp} FP, {fn} FN, precision {tp / (tp + fp):.1%}, recall {tp / (tp + fn):.1%}, cost {c}")
for i in [*p[truth == 0].nlargest(3).index, *p[truth == 1].nsmallest(3).index]:
blocked = p[i] >= chosen[name]
tag = ("FP" if blocked else "ok ham") if truth[i] == 0 else ("ok spam" if blocked else "FN")
print(f" {tag:<7} {p[i]:.3f} {texts[i]}")
Naive Bayes: 0 FP, 18 FN, precision 100.0%, recall 86.3%, cost 18
ok ham 0.947 Nokia phone is lovly..
ok ham 0.916 I (Career Tel) have added u as a contact on I
ok ham 0.871 Have you laid your airtel line to rest?
FN 0.000 In The Simpsons Movie released in July 2007 n
FN 0.000 Babe: U want me dont u baby! Im nasty and hav
FN 0.000 Would you like to see my XXX pics they are so
TF-IDF + LogReg: 4 FP, 33 FN, precision 96.1%, recall 74.8%, cost 73
FP 0.652 Are you free now?can i call now?
FP 0.602 I (Career Tel) have added u as a contact on I
FP 0.562 Sir, i am waiting for your call, once free pl
FN 0.046 In The Simpsons Movie released in July 2007 n
FN 0.063 Hi its LUCY Hubby at meetins all day Fri & I
FN 0.077 Babe: U want me dont u baby! Im nasty and hav
What the mistakes say:
- Both models miss chatty spam. A quiz and fake personal messages use everyday words, so word counts can't tell them from a friend.
- Logistic regression blocks friends who say "free" and "call". Those are strong spam words, but "are you free now?" is not an offer.
- One label looks wrong. The "Career Tel" message reads like spam, yet it's labelled ham. A few such labels put a floor under any model's errors.
- Naive Bayes's margin is thin. Its top real message scored 0.947, just under the 0.95 threshold.
Step 7: the winner. Naive Bayes, at a test cost of 18 against 73. It multiplies the evidence from every word, so a message full of spam words scores near 1, while real messages rarely do. That suits a cost that punishes blocking a real message. Ship the model with its threshold:
# script_id: day_022_project_sms_spam_filter/spam_filter
spam_filter, cut = models["Naive Bayes"], chosen["Naive Bayes"]
new = ["URGENT! You have won a 1 week FREE membership. Txt WIN to 80086 now",
"Running 10 min late, save me a seat"]
for text, p in zip(new, spam_filter.predict_proba(new)[:, 1]):
print(f"{'spam' if p >= cut else 'inbox':<6}{p:.3f} {text}")
spam 1.000 URGENT! You have won a 1 week FREE membership. Txt WIN to 80086 now
inbox 0.051 Running 10 min late, save me a seat
Quick check
Quick check
1. Why drop duplicate texts before the split, not after?
2. A false positive costs 10 and a false negative costs 1. Threshold A gives 2 FP and 40 FN; B gives 0 FP and 55 FN. Which is cheaper?
3. Logistic regression had the higher PR-AUC. Why did Naive Bayes still win?
Next
Text was the last stop for linear models: Day 23 starts on decision trees, which choose one question at a time.
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.