Most spam filters are black boxes: they say “spam” and you have to take their word for it. I built an SMS spam classifier that explains itself – TF-IDF plus logistic regression, trained on the SMS Spam Collection – and for every message it shows the exact words that pushed the score toward spam. You do not just get a verdict, you get the reasons.

What it does
It learns from the SMS Spam Collection, the classic dataset of real spam and ham messages, then scores any new message as spam or ham – and lists the top words that drove the decision, with their weights. A Streamlit UI wraps it so you can paste a message and see the verdict and the explanation side by side.
- TF-IDF turns each message into word weights
- Logistic regression scores it as spam or ham
- Every verdict comes with the top spam words and their weights
What it caught
On the built-in 60-message sample (48 train, 12 test) it scored accuracy 0.917, precision for spam 0.857, and recall for spam 1.000 – it caught 6 of 6 spam messages and got 5 of 6 ham messages right. One miss, honestly reported: the ham message “Call me when you get a chance, nothing urgent” was flagged spam, because of the word “urgent”. Note: these metrics are from the 60-message sample, not the full SMS Spam Collection.

| Metric | Value |
|---|---|
| Accuracy | 0.917 (11 of 12 correct) |
| Precision (spam) | 0.857 (6 of 7 spam calls correct) |
| Recall (spam) | 1.000 (6 of 6 spam caught) |
| Spam caught | 6 of 6 |
| Ham correct | 5 of 6 |
Here is the classifier explaining itself on a classic spam message: “Congratulations! You have won a FREE prize, claim your cash now” scores SPAM at 77.3%, with the top words free +0.194, claim +0.194, prize +0.184, cash +0.172, and won +0.156. You can see exactly which words pushed it over the line – and why “urgent” alone was enough to misfire on a harmless message.
How it works
Each message is turned into numbers with TF-IDF, then logistic regression weighs those numbers and outputs a spam probability. The explanation is free: the model’s own weights say how much each word pushed the score up or down, so the top words are simply the biggest positive weights in that message.

- TF-IDF turns the message into word weights
- Logistic regression scores it as spam or ham
- The top words explain the score
The maths
TF-IDF in plain words: TF is how often a word appears in this message, and IDF is how rare the word is across all messages – log of total messages divided by messages containing the word. TF-IDF is TF times IDF, so a word scores highest when it appears a lot in this message but rarely anywhere else. That is why “free” and “prize” light up in spam and ordinary words do not.
Precision and recall, worked from the test numbers: the test set had 6 spam and 6 ham. The classifier called 7 messages spam – 6 real spam and 1 ham – so precision = 6 / 7 = 0.857. It caught all 6 real spam, so recall = 6 / 6 = 1.000. Accuracy = 11 correct out of 12 = 0.917.
What you need
- Python 3.12
- scikit-learn for TF-IDF and logistic regression
- Streamlit for the UI
Build it
Install the dependencies, train the model, and try a prediction.
pip install -r requirements.txtpython train.pypython predict.py "Congratulations! You have won a FREE prize, claim your cash now"Prefer a UI? Start the Streamlit app:
streamlit run app.pyThe code

sms-spam-classifier/
+-- classifier.py
+-- train.py
+-- predict.py
+-- app.py
+-- config.pyclassifier.py holds the model and the explanation – the top words are the biggest weights:
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
vectorizer = TfidfVectorizer(stop_words="english")
clf = LogisticRegression(max_iter=1000)
def explain(text, top_n=5):
vec = vectorizer.transform([text])
prob = clf.predict_proba(vec)[0][1]
weights = clf.coef_[0] * vec.toarray()[0]
words = vectorizer.get_feature_names_out()
ranked = sorted(zip(words, weights), key=lambda pair: -pair[1])
return prob, ranked[:top_n]train.py trains on the 60-message sample and prints the metrics:
from sklearn.metrics import accuracy_score, precision_score, recall_score
from classifier import vectorizer, clf
from data import load_sample
texts, labels = load_sample()
X_train, X_test, y_train, y_test = train_test_split(texts, labels)
X_train_vec = vectorizer.fit_transform(X_train)
clf.fit(X_train_vec, y_train)
pred = clf.predict(vectorizer.transform(X_test))
print("accuracy", accuracy_score(y_test, pred))
print("precision", precision_score(y_test, pred))
print("recall", recall_score(y_test, pred))What broke
Two bugs, both honest ones. First, requests was imported at the top level, so offline training crashed before it even started – the import now lives inside the download function, where it belongs. Second, explain() used clf.coef_[1] instead of coef_[0]: for a binary classifier the weights live in row 0, so every explanation was reading the wrong row. With coef_[0], the top words finally match the score – free, claim, prize, cash, won, exactly as the numbers say.
Download the project
Unzip the project, pip install the requirements, then run train.py and predict.py to see the classifier explain itself.
Premium Download
Get the complete project code
