Lessons › Projects
Spam filter with Naive Bayes
A text classifier that spots spam messages, explains which words gave them away, and scores any message you type.
No setup needed. Run every step in your browser on Gradient Lab, or download it.
Open the notebookLevel: Beginner · Time: 30 min · You’ll practise: text to numbers, Naive Bayes, confusion matrix, precision and recall
Steps
1. Load the messages
Load 44 short messages labeled spam or ham (normal). It’s a small sample so you can read every row.
df = pd.read_csv("messages.csv")
print(df["label"].value_counts().to_string())2. Turn text into numbers: count how often each word appears
Turn text into numbers: CountVectorizer counts how often each word appears in each message.
vectorizer = CountVectorizer(lowercase=True)
X = vectorizer.fit_transform(df["text"])
y = (df["label"] == "spam").astype(int)
print("Vocabulary size:", len(vectorizer.vocabulary_))3. Train and test
Train Naive Bayes on 70% of the messages and predict the other 30%.
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=3, stratify=y) model = MultinomialNB().fit(X_train, y_train) pred = model.predict(X_test)
4. Grade it properly
Count the four outcomes (caught spam, missed spam, false alarms, correct normal) and compute precision and recall.
tn, fp, fn, tp = confusion_matrix(y_test, pred).ravel()
print(f"Caught spam (TP): {tp} Missed spam (FN): {fn}")
print(f"False alarms (FP): {fp} Correct normal (TN): {tn}")
print(f"Accuracy {accuracy_score(y_test, pred):.0%} Precision {precision_score(y_test, pred):.0%} Recall {recall_score(y_test, pred):.0%}")5. Which words scream spam?
Ask the model which words push hardest toward “spam”.
words = vectorizer.get_feature_names_out()
spamminess = model.feature_log_prob_[1] - model.feature_log_prob_[0]
top = spamminess.argsort()[::-1][:8]
print("Most spammy words:", ", ".join(words[i] for i in top))6. Try your own messages
Score your own messages and see the spam probability for each.
for msg in ["Claim your free prize now", "Are you coming to class tomorrow", "Verify your account at this link"]:
p = model.predict_proba(vectorizer.transform([msg]))[0][1]
print(f"{p:>5.0%} spam <- {msg}")Expected output
$ python spam_filter.py label ham 24 spam 20 Vocabulary size: 206 Caught spam (TP): 5 Missed spam (FN): 1 False alarms (FP): 1 Correct normal (TN): 7 Accuracy 86% Precision 83% Recall 83% Most spammy words: now, click, link, claim, win, prize, your, won 100% spam <- Claim your free prize now 3% spam <- Are you coming to class tomorrow 99% spam <- Verify your account at this link
Stretch goals
- Add 20 of your own messages to messages.csv and retrain.
- Download a public SMS spam dataset (search “SMS Spam Collection”) and run the same script on it.
- Swap
CountVectorizerforTfidfVectorizerand compare precision.