Tuesday , December 1 2026
Confusion matrix explained with a tested scikit-learn example: TP, TN, FP, FN, classification report, metrics formulas and the effect of thresholds.

Confusion Matrix in Machine Learning (with Python Example)

Updated: 29 November 2026Level: BeginnerReading time: about 8 minutesscikit-learn · tested

A confusion matrix is a table that shows how a classifier’s predictions compare with the true labels. Accuracy, precision, recall and F1 are all calculated from it.

What You Will Learn

  • TP, TN, FP and FN
  • Build and read a confusion matrix
  • Classification report
  • How thresholds change the matrix
  • Choosing the right metric

The Four Cells

Predicted negative Predicted positive
Actual negative True Negative (TN) False Positive (FP) – Type I error
Actual positive False Negative (FN) – Type II error True Positive (TP)

Example: Breast-Cancer Classifier

Example
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix, classification_report

X, y = load_breast_cancer(return_X_y=True)        # 1 = benign, 0 = malignant
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)).fit(X_tr, y_tr)
pred = model.predict(X_te)
print(confusion_matrix(y_te, pred))
Output
[[52  1]
 [ 1 89]]

Explanation: Rows are true classes, columns are predictions (scikit-learn order: class 0 first). 52 malignant and 89 benign tumours are correct; one of each is misclassified.

Example
print(classification_report(y_te, pred, digits=3))
Output
              precision    recall  f1-score   support

           0      0.981     0.981     0.981        53
           1      0.989     0.989     0.989        90

    accuracy                          0.986       143
   macro avg      0.985     0.985     0.985       143
weighted avg      0.986     0.986     0.986       143

Metrics from the Matrix

Metric Formula Question
Accuracy (TP+TN) / all How often is it right overall?
Precision TP / (TP+FP) When it says positive, how often is it right?
Recall (sensitivity) TP / (TP+FN) Of all real positives, how many did it find?
Specificity TN / (TN+FP) Of all real negatives, how many were correct?
F1 2·P·R / (P+R) Balance of precision and recall

More in Accuracy, Precision, Recall and F1.

Thresholds Change Everything

Example
proba = model.predict_proba(X_te)[:, 1]
for th in [0.5, 0.3, 0.8]:
    print(th, confusion_matrix(y_te, (proba >= th).astype(int)).ravel())   # tn fp fn tp
Output
0.5 [52  1  1 89]
0.3 [50  3  0 90]
0.8 [52  1  6 84]

Explanation: predict() uses a 0.5 probability threshold. Lowering it predicts “benign” more often (more FP); raising it to 0.8 makes the model cautious and misses 6 benign cases (more FN). Choose the threshold based on which error costs more – see ROC and AUC.

Plot It

Example
from sklearn.metrics import ConfusionMatrixDisplay
ConfusionMatrixDisplay.from_predictions(y_te, pred, display_labels=["malignant", "benign"])
Note: With imbalanced data (1% fraud), a model that always predicts “not fraud” has 99% accuracy and zero recall. Always look at the full matrix.

Series

ML fundamentals series: What is ML · Types of ML · Train/Test Split · Overfitting & Bias-Variance · Regularization · Confusion Matrix · ROC & AUC · Cross-Validation · Ensembles · DBSCAN

Interview Questions

Q: What is a false positive?
Predicting the positive class when the true class is negative.

Q: When is recall more important than precision?
When missing a positive is costly: cancer screening, fraud detection.

Q: Why can accuracy mislead?
On imbalanced data, predicting the majority class gives high accuracy but no useful predictions.

Practice Exercises

  1. Compute precision and recall by hand from [[52, 1], [1, 89]].
  2. Find the threshold that gives zero false negatives for class 1 with the fewest false positives.

Summary

The confusion matrix counts TN, FP, FN and TP. All classification metrics come from it, and the decision threshold moves errors between FP and FN.

Next: ROC Curve and AUC

About Machine Learning

Check Also

Regularization in Machine Learning: Ridge, Lasso and Elastic Net

Ridge (L2), Lasso (L1) and Elastic Net regularization compared on real data with tested scikit-learn code, alpha tuning and feature selection.