Confusion Matrix & Metrics Cheat Sheet
How to read a confusion matrix and compute precision, recall, F1, and accuracy for binary and multi-class classification with scikit-learn.
1 PageBeginnerMar 15, 2026
Confusion Matrix & Report
Build and visualize a confusion matrix.
python
from sklearn.metrics import confusion_matrix, classification_report, ConfusionMatrixDisplayimport matplotlib.pyplot as plty_true = [1, 0, 1, 1, 0, 1, 0, 0]y_pred = [1, 0, 0, 1, 0, 1, 1, 0]cm = confusion_matrix(y_true, y_pred)print(cm)# [[TN FP]# [FN TP]]print(classification_report(y_true, y_pred, target_names=["neg", "pos"]))ConfusionMatrixDisplay(cm, display_labels=["neg", "pos"]).plot()plt.show()
Metric Formulas
How each metric is derived from TP/TN/FP/FN.
python
# TP = true positive, TN = true negative# FP = false positive (Type I error), FN = false negative (Type II error)accuracy = (TP + TN) / (TP + TN + FP + FN)precision = TP / (TP + FP) # of predicted positives, how many correctrecall = TP / (TP + FN) # of actual positives, how many found (sensitivity)specificity = TN / (TN + FP) # of actual negatives, how many foundf1_score = 2 * (precision * recall) / (precision + recall)
Metric Definitions
Core classification evaluation terms.
- True Positive (TP)- model correctly predicts the positive class
- True Negative (TN)- model correctly predicts the negative class
- False Positive (FP)- model predicts positive but actual is negative (Type I error)
- False Negative (FN)- model predicts negative but actual is positive (Type II error)
- Precision- TP / (TP + FP); how trustworthy positive predictions are
- Recall (Sensitivity)- TP / (TP + FN); how many actual positives were caught
- F1 Score- harmonic mean of precision and recall; good for imbalanced classes
- Accuracy- overall fraction correct; can be misleading on imbalanced datasets
Which Metric to Prioritize
Choosing metrics based on the cost of errors.
- High cost of false positives- optimize for precision (e.g. spam filtering)
- High cost of false negatives- optimize for recall (e.g. cancer screening)
- Balanced classes, balanced costs- accuracy is a reasonable single-number summary
- Imbalanced classes- prefer F1, precision-recall curves, or balanced accuracy over raw accuracy
- Multi-class problems- use macro/micro/weighted averages of precision, recall, and F1
Pro Tip
On imbalanced datasets, accuracy can look great while the model just predicts the majority class every time — always check precision, recall, and F1 for the minority class, or look at the confusion matrix directly.
Was this cheat sheet helpful?
Explore Topics
#ConfusionMatrixMetrics#ConfusionMatrixMetricsCheatSheet#DataScience#Beginner#ConfusionMatrixReport#MetricFormulas#MetricDefinitions#WhichMetricToPrioritize#OOP#MachineLearning#CheatSheet#SkillVeris
Advertisement
Sri Hayavadhana Info-Tech
Professional Web Designing Services
- Responsive Websites
- E-commerce Solutions
- SEO Friendly Design
- Fast & Secure
- Support & Maintenance