Lesson 7 of 12
Step 6: Improve the Model
Our basic classifier works. Now let us see common ways to improve it: better features, TF-IDF weighting, and trying different algorithms.
Improvement 1: TF-IDF Instead of Raw Counts
CountVectorizer uses raw word counts. A word like 'the' appears in every email, so its count is high but carries no useful information.
TF-IDF (Term Frequency, Inverse Document Frequency) weights words by:
- How often they appear in a document (TF: useful words appear more)
- How rare they are across all documents (IDF: rare words are more informative)
Words like 'free', 'win', and 'prize' that appear frequently in spam but rarely in legitimate emails will get high TF-IDF scores, making them better spam indicators.
Educational visual guide for step 6 improve the model.
TF-IDF and Multiple Algorithms
# Comparing different approaches to improve the classifier
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.naive_bayes import MultinomialNB
from sklearn.linear_model import LogisticRegression
from sklearn.svm import LinearSVC
import numpy as np
emails = [
("Hi Alex, the meeting is rescheduled to Thursday at 3pm. Please confirm.", 0),
("WIN A FREE iPhone NOW! Click here to claim your prize immediately!", 1),
("Your monthly bank statement is ready. Log in to view it.", 0),
("CONGRATULATIONS! You have been selected for a $1000 gift card. Act fast!", 1),
("Can you send me the project report by end of day? Thanks, Sarah.", 0),
("Urgent! Your account will be suspended. Verify your information now.", 1),
("Reminder: Your dentist appointment is tomorrow at 10am.", 0),
("Make $5000 a week from home! No experience needed. Limited spots!", 1),
("The quarterly financial results are attached for your review.", 0),
("FREE pills! Lose 20 pounds in 10 days guaranteed! Order now!", 1),
("Team lunch is scheduled for Friday. Please RSVP by Wednesday.", 0),
("You won a lottery! Claim your prize of $500,000. Reply with your details.", 1),
("Please review the updated terms of service and provide feedback.", 0),
("Hot singles in your area! Click here to meet them tonight!", 1),
("The server maintenance will occur this Sunday from 2am to 4am.", 0),
("Buy cheap medications online! No prescription needed!", 1),
("Your package has been shipped. Track it at the link below.", 0),
("FINAL NOTICE: Pay now or face legal consequences. Click here.", 1),
("Let us catch up this week. Are you free for coffee on Tuesday?", 0),
("Earn unlimited income working from home. Sign up free today!", 1),
]
df = pd.DataFrame(emails, columns=["email", "label"])
y = df["label"]
print("Comparing Feature Extraction + Algorithm Combinations:")
print()
# Feature extractors
feature_configs = {
"CountVectorizer": CountVectorizer(stop_words="english"),
"TfidfVectorizer": TfidfVectorizer(stop_words="english"),
"Tfidf + bigrams": TfidfVectorizer(stop_words="english", ngram_range=(1, 2)),
}
# Algorithms
algorithms = {
"Naive Bayes": MultinomialNB(),
"Logistic Regression": LogisticRegression(max_iter=200, random_state=42),
}
best_score = 0
best_config = ""
for feat_name, vectorizer in feature_configs.items():
X = vectorizer.fit_transform(df["email"])
for alg_name, model in algorithms.items():
# Skip LinearSVC with MultinomialNB-incompatible features
try:
scores = cross_val_score(model, X, y, cv=4, scoring="f1")
avg_score = np.mean(scores)
print(f" {feat_name} + {alg_name}:")
print(f" F1 Score: {avg_score:.3f} (+/- {np.std(scores):.3f})")
if avg_score > best_score:
best_score = avg_score
best_config = f"{feat_name} + {alg_name}"
except Exception:
print(f" {feat_name} + {alg_name}: Not compatible")
print()
print(f"Best configuration: {best_config}")
print(f"Best F1 Score: {best_score:.3f}")Tip
Tip
In a real project, you would use a much larger dataset (thousands to millions of emails). With 20 examples, the results will vary a lot. The real SpamAssassin public dataset contains 6,000+ labeled emails and is a great starting point for a real spam detection project.
Finished this lesson?