Python ML Build a Spam Classifier
A spam classifier sorts messages into spam and ham. Ham is the normal mail, and spam is the junk.
Two columns, one tab apart
Each line holds a label, a tab, and a message. Splitting on the tab gives the label and the text.
lines = ["ham\tHello, are we still on for lunch?", "spam\tWINNER! Call now to claim your prize"]
for line in lines:
label, message = line.split("\t", 1)
print(label, "->", message)Words become numbers
The vectorizer learns six words from three short messages. Each row counts one message.
from sklearn.feature_extraction.text import TfidfVectorizer
sample = ["Free prize, call now", "See you at lunch tomorrow", "Claim your free cash"]
vectors = TfidfVectorizer(stop_words="english")
matrix = vectors.fit_transform(sample)
print("Shape:", matrix.shape)
print("Words:", sorted(vectors.vocabulary_))Precision and recall on five guesses
The guesses catch two of three spam messages and never cry wolf. Precision is perfect, and recall is two out of three.
from sklearn.metrics import precision_score, recall_score
truth = ["spam", "ham", "spam", "ham", "spam"]
guess = ["spam", "ham", "ham", "ham", "spam"]
print("Precision:", round(precision_score(truth, guess, pos_label="spam"), 2))
print("Recall:", round(recall_score(truth, guess, pos_label="spam"), 2))Example
import io
import urllib.request
import zipfile
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, precision_score, recall_score
from sklearn.model_selection import train_test_split
url = "https://archive.ics.uci.edu/static/public/228/sms+spam+collection.zip"
with urllib.request.urlopen(url) as response:
data = response.read()
with zipfile.ZipFile(io.BytesIO(data)) as zipped:
text = zipped.read("SMSSpamCollection").decode("utf-8")
labels = []
messages = []
for line in text.splitlines():
label, message = line.split("\t", 1)
labels.append(label)
messages.append(message)
print("Messages:", len(messages))
print("Spam share:", round(labels.count("spam") / len(labels), 4))
X_train, X_test, y_train, y_test = train_test_split(
messages, labels, test_size=0.2, random_state=42)
vectors = TfidfVectorizer(stop_words="english")
X_train_vec = vectors.fit_transform(X_train)
X_test_vec = vectors.transform(X_test)
model = LogisticRegression(max_iter=1000, random_state=42)
model.fit(X_train_vec, y_train)
pred = model.predict(X_test_vec)
print("Accuracy:", round(accuracy_score(y_test, pred), 4))
print("Spam precision:", round(precision_score(y_test, pred, pos_label="spam"), 4))
print("Spam recall:", round(recall_score(y_test, pred, pos_label="spam"), 4))Key points
- Spam classification: sorting messages into junk and normal mail
- Ham: a normal message that is not spam
- Use urllib to download the SMS Spam Collection from the UCI archive
- Use TfidfVectorizer to turn the messages into numbers
- Use LogisticRegression to learn which words mark a message as spam
- Precision: the share of messages called spam that really are spam
- Recall: the share of real spam messages the model catches
In this example, urllib downloads the SMS Spam Collection zip from the UCI archive, and zipfile reads the SMSSpamCollection file inside it. Each line splits on a tab into a label and a message. The collection holds 5,574 messages, and 13.4 percent are spam. train_test_split holds back 20 percent of the messages for testing. TfidfVectorizer turns the messages into numbers, and LogisticRegression learns which words mark a message as spam. The accuracy is 0.965. The spam precision is 0.9841, so nearly every message called spam really is spam. The spam recall is 0.7702, so the model catches about three quarters of the spam and misses the rest. In short, a spam classifier is a text model that learns which words mark a message as junk, then proves itself with precision and recall.
Note
A spam filter that misses spam is annoying, but one that hides real mail is worse. Recall and precision measure the two mistakes.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does spam recall measure?