Stop 08 · Supervised Learning: ClassificationProjects · 1/1

Spam Classifier With Naive Bayes

Part of the Machine Learning Roadmap

In short

Spam detection is the 'hello world' of text ML for good reason. In one small project you clean text, turn words into numbers, train a fast classifier and wrestle with the precision-recall trade-off that every real classifier faces.

Build a spam detector that turns messages into word counts or TF-IDF features and classifies them with Naive Bayes. It is a classic first text project that practises text preprocessing, pipelines and precision-recall trade-offs.

The jaadu dressed as a society watchman checks envelopes at a gate, tossing suspicious glittery ones into a bin and handing plain ones to residents.

Think of it like this

The society watchman's instinct

The watchman at your housing society has seen thousands of visitors. 'Free gift', 'lucky draw winner' and 'urgent KYC update' make him suspicious. 'Swiggy order' and 'it's me, Priya from 402' don't. He weighs each clue separately and adds them up. Naive Bayes does exactly this with words: each word nudges the odds of spam up or down.

Watch it happen

From raw message to spam score

Raw SMS
Clean
Count words
Naive Bayes
Spam or ham

1/5'Congratulations! You WON ₹50,000. Click now to claim your prize.'

The big ideas

What you need to know

Bayes rule, naively

It assumes words are independent given the class. That's false, but the ranking of spam vs ham is still surprisingly good.

MultinomialNB for counts

It works on word counts or TF-IDF. Training is just counting, so it's very fast even on millions of messages.

Smoothing matters

alpha=1 adds a pseudo-count so a word never seen in spam doesn't force the probability to zero.

Precision over recall here

Losing a real OTP or bank message is worse than letting one spam through, so tune for high precision.

How it works

Project steps

  1. 1

    Get data

    Use the UCI SMS Spam Collection: about 5,500 messages labelled spam or ham.

  2. 2

    Split

    Stratified train/test split, since only about 13% are spam.

  3. 3

    Pipeline

    CountVectorizer or TfidfVectorizer followed by MultinomialNB.

  4. 4

    Evaluate

    Confusion matrix, precision, recall and a precision-recall curve.

  5. 5

    Explain

    List the words with the highest spam log-probability and test your own messages.

See it in code

Walk through the code

python
1import pandas as pd2from sklearn.feature_extraction.text import CountVectorizer3from sklearn.metrics import classification_report4from sklearn.model_selection import train_test_split5from sklearn.naive_bayes import MultinomialNB6from sklearn.pipeline import make_pipeline7 8df = pd.read_csv("SMSSpamCollection", sep="\t", names=["label", "text"])9y = (df["label"] == "spam").astype(int)10 11X_tr, X_te, y_tr, y_te = train_test_split(12    df["text"], y, test_size=0.2, stratify=y, random_state=4213)14 15model = make_pipeline(16    CountVectorizer(lowercase=True, stop_words="english", ngram_range=(1, 2)),17    MultinomialNB(alpha=1.0),18)19model.fit(X_tr, y_tr)20print(classification_report(y_te, model.predict(X_te), target_names=["ham", "spam"]))21 22msgs = ["URGENT: your KYC is pending, click link to avoid account block",23        "Reached Indore station, will call you in 10 min"]24print(model.predict_proba(msgs)[:, 1].round(3))

1/5The file is tab-separated with a label and the message. Convert the label to 1 for spam.

A complete spam filter in about 20 lines, using the UCI SMS Spam Collection file.

Save yourself the pain

Common mistakes

Oops

Bragging about 97% accuracy.

Do this instead

About 87% of messages are ham, so predicting 'ham' every time already scores around 87%. Report spam precision and recall.

Oops

Fitting the vectoriser before splitting the data.

Do this instead

Keep the vectoriser inside the pipeline so its vocabulary comes from training messages only.

Your mission

Ship your spam filter

~60 min

Quick check

Why does MultinomialNB use alpha (Laplace smoothing)?

Go deeper

  1. 1Use the SMS Spam Collection dataset and a TfidfVectorizer plus MultinomialNB pipeline.
  2. 2Report precision and recall, and explain why false positives annoy users.
  3. 3Test it on a few messages you write yourself and share the results in the README.

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge