ProjectIntermediate·60 min·0/52 done

Project: Spam Message Classifier

Train a real machine learning model with pandas and scikit-learn that flags spam messages, measure its accuracy, and save it to a file like an MLOps pipeline.

Why it matters: This is the full ML loop interviewers ask about: data, features, train/test split, model, metric, and a saved model file that can be deployed.

Step 1

What you will build

A model that reads a message and says spam or ham (a normal message). Unlike the word rules in the Module 1 project, nobody writes the rules here: the model learns which words matter from labelled examples.

You will:

  • load 40 labelled messages into a pandas DataFrame
  • turn text into numbers with TF-IDF
  • train a Naive Bayes classifier inside a Pipeline
  • check accuracy on messages the model never saw
  • on your laptop, save the trained model to a file

Step 2

Text becomes numbers

Models only understand numbers. TfidfVectorizer gives every word a column, and each message a row of weights. Words that appear in few messages (like "prize") get more weight than common ones (like "now").

Tiny example

TF-IDF gives each word a weight per message.

from sklearn.feature_extraction.text import TfidfVectorizer
vec = TfidfVectorizer()
X = vec.fit_transform(["free prize now", "team meeting now"])
print(vec.get_feature_names_out())
print(X.shape)

Step 3

Train and test

Never test a model on the data it learned from: it would look better than it is. train_test_split keeps 25% aside. stratify keeps the same share of spam in both parts.

Tiny example

Hold back some messages to test honestly.

from sklearn.model_selection import train_test_split
texts = ["a", "b", "c", "d", "e", "f", "g", "h"]
labels = [0, 0, 0, 0, 1, 1, 1, 1]
X_tr, X_te, y_tr, y_te = train_test_split(texts, labels, test_size=0.25, random_state=42, stratify=labels)
print(len(X_tr), "train,", len(X_te), "test")

Step 4

One pipeline, one object

A Pipeline keeps the text step and the model together. That matters in production: you save one file, and new messages always go through the same TF-IDF step the model was trained with.

Tiny example

A Pipeline chains the steps so fit and predict run them all.

from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
model = Pipeline([("tfidf", TfidfVectorizer()), ("nb", MultinomialNB())])
model.fit(["free prize", "free cash now", "team lunch", "class notes"], ["spam", "spam", "ham", "ham"])
print(model.predict(["free cash prize"]))

Build it here · answer checked automatically

Build the project

Build model as a Pipeline of TfidfVectorizer then MultinomialNB, fit it on the training split, set accuracy with accuracy_score on the test split, and finish predict_label(message) so it returns "spam" or "ham" from the model.

Edit the code, then press Run & check. Passing it marks this project done.

python console

Project

# packages: numpy, pandas, scikit-learn

~/lesson.py

Ctrl+Enter

console output

ready

$ waiting for Run...

On your laptop

Run the real thing on your computer

On your laptop the data lives in a CSV file, like real projects, and the trained model is saved to spam_model.joblib so another program (an API, for example) can load it.

  1. 1

    Make a folder called spam-classifier, save the files below into it, and open a terminal there.

  2. 2

    Create a virtual environment, so this project's packages stay inside this folder. On Mac and Linux, type python3 instead of python everywhere.

    python -m venv .venv
  3. 3

    Turn it on. Windows: .venv\Scripts\activate. Mac or Linux: source .venv/bin/activate. Your terminal line now starts with (.venv).

  4. 4

    Install the packages listed in requirements.txt:

    pip install -r requirements.txt

spam_classifier.py

"""Spam Message Classifier: TF-IDF features + Naive Bayes, trained with scikit-learn."""
import joblib
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics import accuracy_score, classification_report
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import Pipeline


def main():
    data = pd.read_csv("messages.csv")
    print(f"Loaded {len(data)} messages:", data["label"].value_counts().to_dict())

    X_train, X_test, y_train, y_test = train_test_split(
        data["text"], data["label"], test_size=0.25, random_state=42, stratify=data["label"]
    )

    model = Pipeline([
        ("tfidf", TfidfVectorizer()),
        ("nb", MultinomialNB()),
    ])
    model.fit(X_train, y_train)

    predictions = model.predict(X_test)
    print("Accuracy:", round(accuracy_score(y_test, predictions), 3))
    print(classification_report(y_test, predictions, zero_division=0))

    joblib.dump(model, "spam_model.joblib")
    print("Saved the trained model to spam_model.joblib")

    for message in [
        "WIN a FREE iPhone now! Click this link to claim your prize",
        "Can we move the team meeting to 4 pm?",
    ]:
        print(f"{model.predict([message])[0]:>4} | {message}")


if __name__ == "__main__":
    main()

messages.csv

label,text
spam,"WIN a FREE iPhone today! Click the link to claim your prize"
spam,"Congratulations! You have won a 1000 rupees gift card. Claim now"
spam,"URGENT: your account is blocked. Click here to verify your bank details"
spam,"You won a cash prize of 50000. Call now to claim"
spam,"Limited offer! Get 90% off, buy now, click the link"
spam,"FREE recharge for you. Reply YES to claim your free gift"
spam,"Earn 5000 per day from home. No experience needed. Click now"
spam,"Your loan is approved instantly. Click the link to get cash today"
spam,"Claim your free lottery reward now, only today"
spam,"Exclusive deal just for you! Win big prizes, click here"
spam,"Your KYC is pending. Update now or your account will be closed"
spam,"Get rich fast with this crypto offer. Join now and win"
spam,"You have been selected for a free holiday. Call now to claim"
spam,"Final notice: claim your cash reward before midnight"
spam,"Double your money in 7 days. Click the link to invest now"
spam,"Free entry to win a new car. Text WIN to claim"
spam,"Your number won the lucky draw! Claim your prize money now"
spam,"Act now! Cheap loans with zero documents, click here"
spam,"Get a free gift voucher worth 5000. Click to claim today"
spam,"Winner! You are chosen for a cash bonus, reply now"
ham,"Can we move the team meeting to 4 pm tomorrow?"
ham,"Please review my pull request when you get time"
ham,"The model training finished, accuracy is 91 percent"
ham,"Are you coming for lunch today?"
ham,"I pushed the fix for the Docker build, please check"
ham,"Let us meet at the library after class"
ham,"Mom asked if you reached home safely"
ham,"The MLOps class starts at 7 pm on Saturday"
ham,"Can you send me the notes from the last lecture?"
ham,"Happy birthday! Have a great day"
ham,"The deployment to staging went fine, no errors"
ham,"Thanks for the help with the interview prep"
ham,"I am at home now, call me when you are free"
ham,"Did you finish the assignment today?"
ham,"Here is the link to the class recording"
ham,"Thank you for coming today, see you next week"
ham,"Can you check the build logs now?"
ham,"The interview is today at 3 pm, all the best"
ham,"Dinner is ready, come home soon"
ham,"Your order of notebooks will arrive tomorrow"

requirements.txt

pandas>=2.2
scikit-learn>=1.5

README.md

# Spam Message Classifier

A machine learning model that labels messages as spam or ham, built with
pandas and scikit-learn (TF-IDF + Multinomial Naive Bayes).

## How to run

    python -m venv .venv
    pip install -r requirements.txt
    python spam_classifier.py

## Results

About 80% accuracy on 10 held-out test messages (it was trained on only 30),
and the trained model is saved to spam_model.joblib.

## What I learned

- Turning text into features with TF-IDF
- Train/test split and why the test set must stay unseen
- Saving a whole pipeline with joblib so it can be deployed

## Next ideas

- Train on the public SMS Spam Collection dataset (about 5,500 messages)
- Serve the saved model with FastAPI

.gitignore

__pycache__/
.venv/
*.joblib

Run it from the same folder:

python spam_classifier.py

You should see something like:

Loaded 40 messages: {'spam': 20, 'ham': 20}
Accuracy: 0.8
(a precision / recall table per class)
Saved the trained model to spam_model.joblib
spam | WIN a FREE iPhone now! Click this link to claim your prize
 ham | Can we move the team meeting to 4 pm?

Show it to recruiters

Put it on GitHub

  1. 1

    Create a free account at github.com if you do not have one yet.

  2. 2

    Click + (top right), then New repository. Name it spam-classifier, choose Public, and click Create repository.

  3. 3

    Easiest way: on the new repository page, click uploading an existing file, drag in spam_classifier.py, messages.csv, requirements.txt, README.md, .gitignore, and click Commit changes. Done.

  4. 4

    The way companies work: install Git from git-scm.com, open a terminal in your project folder, and run these. Replace YOUR-USERNAME with your GitHub username. The two git config lines are needed only once per computer. The first push asks you to sign in: on Windows a browser window opens. On Mac or Linux, GitHub does not accept your account password here, so use a personal access token as the password, or publish with GitHub Desktop instead.

    git config --global user.name "Your Name"
    git config --global user.email "you@example.com"
    git init
    git add .
    git commit -m "First version of spam-classifier"
    git branch -M main
    git remote add origin https://github.com/YOUR-USERNAME/spam-classifier.git
    git push -u origin main
  5. 5

    Put the repository link on your resume and LinkedIn under Projects, with one line on what it does and one on what you learned. Recruiters open these.

Takeaways

  • 1TF-IDF turns text into numbers a model can learn from.
  • 2Always measure on a test split the model never saw.
  • 3A Pipeline plus joblib.dump gives you one model file you can deploy.