arrow_backBack to Projects
stacked_email

Email Spam or Ham Classifier

Machine Learning
Jul 22, 2026visibility1

A machine learning-powered application that classifies incoming email text into "spam" or "not spam". It features a FastAPI-based REST API for programmatic access and a responsive, interactive Streamlit dashboard for visual interaction.

PythonFastAPIStreamlitPandasScikit-LearnLogisticRegression

image.pngzoom_in

This might be the first time I've tried to deploy a machine learning model using joblib and fastAPI inference. And to be honest, this experience was thrilling, as this project can open a lot of doors for me to try deploying a model that others or I can use, rather than stopping at training.

Problem Statement

The goal of this project is to build and deploy a machine learning model that accurately classifies emails as spam or not spam based on their text content. The solution requires delivering a fast, robust REST API that exposes the model's predictions, along with an interface that allows testing of raw email text, inspecting prediction confidence, and analyzing word-frequency features.

Link to the Dataset

The model was trained using the following dataset from Kaggle: Email Spam Classification Dataset CSV

App Overview

As the name suggests, this project is an Email Classification application powered by a machine learning model that near-accurately detects and filters spam messages.

How It Works: When a user submits an email payload, the system processes the text through a predefined Natural Language Processing (NLP) pipeline:

  • Tokenization: The raw email text is normalized and split into individual words (tokens).
  • Feature Extraction: The application utilizes a Bag-of-Words (BoW) approach, counting the frequency of these words and matching them against the model's pre-trained vocabulary.
  • Inference: This structured feature data is fed into the machine learning model to calculate a probability score.
  • Classification: The app returns the final prediction (Spam or Ham) along with a confidence score indicating the model's certainty.

Example: If an input spam email is given:

Subject: Congratulations

You won a free prize. Click here now for a money cash dollar claim.

The system will extract key trigger words (e.g., "prize", "money", "cash", "claim"), map their occurrences to the trained feature set, and correctly flag the email as spam with a high confidence score.

image.pngzoom_in

The Architecture Used

The system is built with a decoupled and modular architecture:

  • Language & Package Management: Python 3.13+, using uv for lightning-fast dependency management.
  • Backend API: FastAPI serves the REST endpoints (POST /api/v1/classify), providing high-performance, asynchronous request handling.
  • Frontend UI: Streamlit is used as the frontend client, consuming the FastAPI backend over HTTP to provide an interactive dashboard.
  • Machine Learning: scikit-learn, pandas, and joblib.

Creating the Machine Learning Model

The model development, as documented in the Notebook, followed a rigorous, metric-driven approach:

  1. Data Exploration & Cleaning: The dataset consists of a 3,000-word vocabulary count per email and a prediction label. After verifying the absence of missing values, I analyzed the class distribution (Spam vs. Non-Spam). The distribution analysis showed 3,672 non-spam emails versus 1,500 spam emails, resulting in a class imbalance. I added this detail and connected it to the decision to use stratified sampling in the next step, ensuring it flows better.
  2. Data Splitting: I used an 80/20 train-test split with stratified sampling to ensure the training and testing sets accurately reflected the real-world distribution of spam.
  3. Model Evaluation & Comparison: I utilized Stratified 5-Fold Cross-Validation to evaluate three different algorithms:
    • Multinomial Naive Bayes: Achieved ~94.2% accuracy. However, its precision for spam was slightly lower than expected, which could lead to misclassifications that impact user trust.
    • Random Forest Classifier: Showed strong performance with ~97.2% accuracy and 96% overall F1-score.
    • Logistic Regression: Emerged as the best performer, achieving ~97.2% average accuracy during cross-validation, and an impressive 98% accuracy and 97% spam precision on the test set.
  4. Final Selection: Because Logistic Regression had the highest precision and overall accuracy, minimizing the risk of catastrophic false positives (important emails marked as spam), it was selected as the final model. The trained model (spam_model.pkl) and the vocabulary features (feature_names.pkl) were exported via joblib for integration into the FastAPI service.

log_reg score:

image.pngzoom_in

Final Thoughts

This project was fun to build and really interesting! It successfully bridges the gap between data science and software engineering. By pairing a highly accurate Logistic Regression model with a FastAPI backend and an intuitive Streamlit frontend, the result is a complete, ready-to-use AI product.

I might build more ML apps in the future!

Quokka AIQuokka