Confusion matrix
A confusion matrix is a cross-tabulation of actual class labels against predicted class labels in supervised classification. For binary tasks it records True Positives, True Negatives, False Positives, and False Negatives, forming the exact foundation for derived metrics such as precision, recall, specificity, accuracy, and F1-score.
Study Card: Confusion Matrix
Direct Answer
A confusion matrix is a contingency table used to evaluate classification models by comparing ground-truth labels against predicted labels across all classes. In binary classification, its four cells—True Positives (TP), True Negatives (TN), False Positives (FP), and False Negatives (FN)—reveal how errors occur, enabling calculation of task-appropriate metrics rather than relying solely on overall accuracy:
Key Terms
- True Positive (TP): Correctly predicting the positive class.
- True Negative (TN): Correctly predicting the negative class.
- False Positive (FP) / Type I Error: Incorrectly predicting positive when the true class is negative (false alarm).
- False Negative (FN) / Type II Error: Incorrectly predicting negative when the true class is positive (miss).
- Axis Ordering Convention: Textbook tables often place Positive first (
[[TP, FN], [FP, TN]]), whereasscikit-learn’sconfusion_matrixorders sorted labels[0, 1]as[[TN, FP], [FN, TP]](sotn, fp, fn, tp = cm.ravel()).
Example
Consider a medical screening model predicting disease (Positive) versus healthy (Negative):
| Predicted Positive | Predicted Negative | |
|---|---|---|
| Actual Positive | 100 (TP) | 20 (FN) |
| Actual Negative | 10 (FP) | 90 (TN) |
Here, , , and . Because missing 20 sick patients (FN) carries high clinical cost, you might lower the positive decision threshold to boost recall even if FP increases slightly.
Code Implementation
import matplotlib.pyplot as plt
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (
ConfusionMatrixDisplay,
classification_report,
confusion_matrix,
)
from sklearn.model_selection import train_test_split
# Generate a synthetic binary classification dataset
X, y = make_classification(
n_samples=1000, n_features=2, n_informative=2, n_redundant=0, random_state=42
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=42, stratify=y
)
model = LogisticRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
# In scikit-learn, binary labels [0, 1] yield [[TN, FP], [FN, TP]]
cm = confusion_matrix(y_test, y_pred)
tn, fp, fn, tp = cm.ravel()
print(f"True Positives: {tp}")
print(f"True Negatives: {tn}")
print(f"False Positives: {fp}")
print(f"False Negatives: {fn}")
print("\nClassification Report:")
print(classification_report(y_test, y_pred))
disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=model.classes_)
disp.plot(cmap=plt.cm.Blues)
plt.title("Confusion Matrix")
plt.show()
Related Concepts
- Precision vs. Recall Tradeoff: Adjusting the probability threshold shifts counts between FP and FN; high precision minimizes false alarms, while high recall minimizes missed detections.
- Multi-class Confusion Matrix: Generalizes to matrices where off-diagonal cells reveal which specific classes the model confuses with each other, enabling macro-, micro-, and weighted-averaged F1 scores.
- Accuracy Paradox: On imbalanced data (e.g., 99% negative), accuracy hides catastrophic FN counts—making the full confusion matrix essential.
- ROC-AUC and PR-AUC: Threshold-free metrics evaluating classifier ranking across all possible confusion matrices induced by varying the probability cutoff.