Lesson 5 of 10 · 2 min
Confusion Matrix
WHY: Accuracy alone is misleading. If 95% of emails are not spam, a model that always says “not spam” gets 95% accuracy but catches zero spam. The confusion matrix shows the full picture.
The 4 Cells
PREDICTED
0 (No) 1 (Yes)
ACTUAL 0 (No) TN FP
1 (Yes) FN TP| Cell | Full Name | Meaning | Analogy (disease test) |
|---|---|---|---|
| TP | True Positive | Predicted 1, Actually 1 | Diagnosed sick, IS sick ✔ |
| TN | True Negative | Predicted 0, Actually 0 | Diagnosed healthy, IS healthy ✔ |
| FP | False Positive | Predicted 1, Actually 0 | Diagnosed sick, IS healthy ✗ (Type I Error) |
| FN | False Negative | Predicted 0, Actually 1 | Diagnosed healthy, IS sick ✗ (Type II Error — most dangerous!) |
Which error is worse depends on the problem:
- Cancer detection: FN is worse (missed a real case = patient dies)
- Spam filter: FP is worse (important email goes to spam)
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
import matplotlib.pyplot as plt
# Generate confusion matrix
cm = confusion_matrix(y_test, y_pred)
print("Confusion Matrix:")
print(cm)
# Output (binary example):
# [[40 3]
# [ 2 69]]
# TN=40, FP=3, FN=2, TP=69
# Visualise it
disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=['Malignant', 'Benign'])
disp.plot(cmap='Blues')
plt.title('Confusion Matrix')
plt.show()
