Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!
Lesson 1 of 9
Confusion Matrix Deep Dive: Precision, Recall, F1-Score & Specificity
A confusion matrix cross-tabulates true ground truth against predicted class decisions: True Positives (TP), False Positives (FP), False Negatives (FN), and True Negatives (TN). From these four atomic counts, core classification metrics are derived: Precision = TP / (TP + FP) (reliability of positive alerts), Recall / Sensitivity = TP / (TP + FN) (ability to detect positive cases), Specificity = TN / (TN + FP) (avoidance of false alarms), and F1-Score = 2 * (Precision * Recall) / (Precision + Recall) (harmonic mean).
Confusion Matrix Analysis & Asymmetric Business Costs
import numpy as np
import pandas as pd
from sklearn.metrics import confusion_matrix, classification_report, fbeta_score
# Ground truth vs predicted decisions on 10,000 security intrusion events
np.random.seed(42)
n = 10_000
# 2% true intrusions, 98% benign traffic
y_true = np.random.choice([0, 1], size=n, p=[0.98, 0.02])
# Model detects 80% of attacks, but incurs a 3% false alarm rate on benign traffic
predicted_probs = np.where(y_true == 1, np.random.beta(5, 2, n), np.random.beta(1, 15, n))
threshold = 0.35
y_pred = (predicted_probs >= threshold).astype(int)
# 1. ATOMIC CONFUSION MATRIX
cm = confusion_matrix(y_true, y_pred)
tn, fp, fn, tp = cm.ravel()
print("=== CONFUSION MATRIX BREAKDOWN ===")
print(f"True Negatives (Benign correctly allowed) : {tn:,}")
print(f"False Positives (Benign blocked - False Alarm): {fp:,}")
print(f"False Negatives (Intrusion missed - Breach!) : {fn:,}")
print(f"True Positives (Intrusion caught) : {tp:,}")
# 2. DERIVED METRICS
precision = tp / (tp + fp)
recall = tp / (tp + fn)
specificity = tn / (tn + fp)
f1 = 2 * (precision * recall) / (precision + recall)
# F2-Score weights Recall twice as heavily as Precision (optimal for security/medicine)
f2 = fbeta_score(y_true, y_pred, beta=2)
print(f"\nDerived Statistical Metrics:")
print(f" Precision : {precision*100:.2f}% (When alert fires, how often is it real?)")
print(f" Recall : {recall*100:.2f}% (What % of total breaches did we stop?)")
print(f" Specificity : {specificity*100:.2f}% (What % of legitimate traffic passed safely?)")
print(f" F1-Score : {f1:.4f} (Harmonic balance)")
print(f" F2-Score : {f2:.4f} (Recall-prioritized metric)")Pro Tip: When to Use F-Beta with Custom Beta Values
Use `fbeta_score(beta=0.5)` when False Positives are costlier than False Negatives (e.g. email spam filtering, where filtering an important client email is worse than letting one spam slip through). Use `beta=2.0` when False Negatives are costlier (e.g. cancer detection, security intrusion).
F1 = harmonic mean of Precision and Recall (balanced metric)
Hands-On Challenge: Build a Confusion Matrix Heatmap Display
Using `sklearn.metrics.ConfusionMatrixDisplay`, create an annotated heatmap that displays both the raw counts and normalized percentages (`normalize='true'`), showing per-class recall directly on the diagonal.
Quick Quiz & Key Concept Checks
Common Pitfall: Optimizing for Accuracy on Imbalanced Datasets
A security model with 98% True Negatives and 0% True Positives has 98% accuracy. Accuracy computes `(TP + TN) / Total`, so massive counts of easy true negatives completely mask zero detection capability on the target class.
Finished this lesson?