Skip to main content

Lesson 5 of 12

Step 4: Evaluate the Model

After training, we measure how well the model performs on the test set. Understanding evaluation metrics is essential for knowing if your model is good enough.

12 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Key Evaluation Metrics

Accuracy: the percentage of predictions that are correct. Looks good but can be misleading on imbalanced data.

Precision: of all the emails the model said were spam, what percentage actually were spam? High precision means few false alarms.

Recall: of all actual spam emails, what percentage did the model correctly catch? High recall means few missed spam.

F1 Score: the harmonic mean of precision and recall. Useful when you need to balance both.

For spam detection, high recall is often more important: you would rather see a few legitimate emails in spam (low precision) than miss spam in your inbox (low recall).

Diagram
Loading diagram…

Educational visual guide for step 4 evaluate the model.

Evaluate the Classifier

Evaluate the Classifier
# Complete evaluation of the spam classifier
# (Continuing from Step 3 - all code together)

import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix

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"])
vectorizer = CountVectorizer(lowercase=True, stop_words="english")
X = vectorizer.fit_transform(df["email"])
y = df["label"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)
model = MultinomialNB()
model.fit(X_train, y_train)

# Evaluate
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)

print("Model Evaluation Results:")
print(f"  Accuracy: {accuracy*100:.1f}%")
print()
print("Classification Report:")
print(classification_report(y_test, y_pred, target_names=["Not Spam", "Spam"]))

# Show predictions on test set
print("Test Set Predictions:")
X_test_array = X_test.toarray()
test_emails = [emails[i][0] for i in range(int(len(emails)*0.8), len(emails))]
for i, (pred, actual) in enumerate(zip(y_pred, y_test)):
    status = "OK" if pred == actual else "WRONG"
    spam_label = "SPAM" if pred == 1 else "not spam"
    print(f"  [{status}] Predicted: {spam_label}")

Understanding Confusion Matrix

Understanding Confusion Matrix
# Understanding the confusion matrix

# A confusion matrix shows 4 types of predictions:
#
#                Predicted NOT SPAM  |  Predicted SPAM
# Actual NOT SPAM   True Negative   |   False Positive (false alarm)
# Actual SPAM       False Negative  |   True Positive  (caught spam!)
#
# For spam detection:
# False Positive: legitimate email goes to spam (annoying but minor)
# False Negative: spam email appears in inbox (worse - spam gets through)

print("Confusion Matrix Explanation:")
print()

example_matrix = {
    "True Negative (TN)":   {"count": 8, "meaning": "Correctly said NOT SPAM (legitimate email)"},
    "False Positive (FP)":  {"count": 1, "meaning": "Said SPAM but was actually legitimate (false alarm)"},
    "False Negative (FN)":  {"count": 1, "meaning": "Said NOT SPAM but was actually spam (missed spam)"},
    "True Positive (TP)":   {"count": 8, "meaning": "Correctly said SPAM (caught spam)"},
}

for name, info in example_matrix.items():
    print(f"  {name}: {info['count']}")
    print(f"    -> {info['meaning']}")
    print()

tn, fp, fn, tp = 8, 1, 1, 8
precision = tp / (tp + fp)
recall = tp / (tp + fn)
f1 = 2 * precision * recall / (precision + recall)

print(f"Precision: {precision:.2f} ({precision*100:.0f}% of spam predictions were correct)")
print(f"Recall:    {recall:.2f} ({recall*100:.0f}% of actual spam was caught)")
print(f"F1 Score:  {f1:.2f}")

Topics in This Module

0/12 done