Project Goal
We will build a model that reads an SMS message and decides whether it is spam or ham (a normal message). The famous SMS Spam Collection dataset has about 5,500 messages, and roughly 13 percent of them are spam.
Step 1: Load and Explore
python
import pandas as pd
# Columns: label (ham or spam) and text
df = pd.read_csv("spam.csv", encoding="latin-1")[["v1", "v2"]]
df.columns = ["label", "text"]
print(df.shape)
print(df["label"].value_counts())
print(df.sample(3))
df["target"] = (df["label"] == "spam").astype(int)
Dataset note: The file is available on the UCI Machine Learning Repository and on Kaggle as spam.csv. If your file has different column names, adjust the code.
Step 2: Split
python
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
df["text"].values, df["target"].values,
test_size=0.2, stratify=df["target"], random_state=42)
stratify keeps the same spam percentage in both parts, which is important for imbalanced data.
Step 3: Vectorize and Build the Model
python
import keras
from keras import layers
vectorize = layers.TextVectorization(max_tokens=10000, output_sequence_length=50)
vectorize.adapt(X_train)
model = keras.Sequential([
keras.Input(shape=(1,), dtype="string"),
vectorize,
layers.Embedding(10000, 32, mask_zero=True),
layers.Bidirectional(layers.GRU(32)),
layers.Dropout(0.3),
layers.Dense(1, activation="sigmoid"),
])
model.compile(optimizer="adam", loss="binary_crossentropy",
metrics=["accuracy", keras.metrics.Precision(name="precision"),
keras.metrics.Recall(name="recall")])
Step 4: Train with Class Weights
python
import numpy as np
from sklearn.utils.class_weight import compute_class_weight
weights = compute_class_weight("balanced", classes=np.array([0, 1]), y=y_train)
class_weight = {0: weights[0], 1: weights[1]}
print(class_weight)
history = model.fit(
X_train, y_train, epochs=15, batch_size=32, validation_split=0.15,
class_weight=class_weight,
callbacks=[keras.callbacks.EarlyStopping(patience=3, restore_best_weights=True)])
Step 5: Evaluate Properly
python
from sklearn.metrics import classification_report, confusion_matrix
probs = model.predict(X_test).ravel()
y_pred = (probs > 0.5).astype(int)
print(confusion_matrix(y_test, y_pred))
print(classification_report(y_test, y_pred, target_names=["ham", "spam"]))
You should reach about 98 percent accuracy and an F1 score above 0.9 for spam. Pay attention to precision: a good email wrongly marked as spam is worse than a missed spam message.
Step 6: Try It and Save
python
tests = ["WINNER!! You have won a free prize, call now to claim",
"Hey, are we still meeting for lunch tomorrow?"]
for t, p in zip(tests, model.predict(np.array(tests)).ravel()):
print(f"{p:.2f} {t}")
model.save("spam_detector.keras")
Ideas for Improvement
- Change the threshold to increase precision
- Try a pretrained model from KerasHub
- Build a Streamlit page for it
Conclusion
This project covered the full workflow: data, split, model, imbalance, evaluation and saving. It reuses the same skills for any text classification problem.
Quick Summary: Stratified split, TextVectorization, Bidirectional GRU, class weights and precision-recall evaluation.