Sub topic 3
Reading the Confusion Matrix: Precision, Recall and F1
This chapter assumes you can train a scikit-learn binary classifier and call predict. It also assumes you know the previous chapter's point: a model that always predicts the majority class can score high accuracy while finding no rare cases. Here you learn the metrics that expose this.
The four outcomes
A binary classifier makes one of four kinds of result on each example. The rare class you care about is called the positive class.
- True positive (TP): a real positive, predicted positive.
- False positive (FP): a real negative, predicted positive. This is a false alarm.
- False negative (FN): a real positive, predicted negative. This is a missed case.
- True negative (TN): a real negative, predicted negative.
The confusion matrix is a table that counts these four outcomes. Scikit-learn puts actual classes in rows and predicted classes in columns.
| Row | Predicted negative | Predicted positive |
|---|---|---|
| **Actual negative** | TN | FP |
| **Actual positive** | FN | TP |
Three metrics built from the counts
- Precision = TP / (TP + FP). Of the cases the model flagged, how many were real? Low precision means many false alarms.
- Recall = TP / (TP + FN). Of the real cases, how many did the model find? Low recall means many misses. It is also called sensitivity.
- F1 = 2 × precision × recall / (precision + recall). This is the harmonic mean of the two.
The harmonic mean punishes imbalance between the two numbers. With precision 0.9 and recall 0.1, the plain average is 0.5, but F1 is about 0.18. A model cannot hide a terrible recall behind a good precision.
Accuracy is (TP + TN) / total. Because TN is huge when negatives dominate, accuracy barely reacts to changes in TP, FP and FN. Precision, recall and F1 never use TN, so the abundant class cannot inflate them.
A worked example
Suppose a test set of 2,500 examples contains 125 positives. The model produces TP = 80, FN = 45, FP = 20 and TN = 2,355.
- Accuracy = (80 + 2,355) / 2,500 = 0.974
- Precision = 80 / 100 = 0.80
- Recall = 80 / 125 = 0.64
- F1 = 2 × 0.80 × 0.64 / 1.44 ≈ 0.711
Accuracy says 97.4%, yet the model misses over a third of the real cases.
Computing them in scikit-learn
This script is self-contained. It computes the metrics by hand and checks them against the library functions.
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (
confusion_matrix, precision_score, recall_score, f1_score
)
X, y = make_classification(
n_samples=10000, n_features=20, n_informative=5,
weights=[0.95, 0.05], flip_y=0.01, random_state=42,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=42
)
model = LogisticRegression(max_iter=1000).fit(X_train, y_train)
pred = model.predict(X_test)
tn, fp, fn, tp = confusion_matrix(y_test, pred).ravel()
print("TN, FP, FN, TP:", tn, fp, fn, tp)
precision = tp / (tp + fp)
recall = tp / (tp + fn)
f1 = 2 * precision * recall / (precision + recall)
print("by hand:", round(precision, 3), round(recall, 3), round(f1, 3))
print("sklearn:", round(precision_score(y_test, pred), 3),
round(recall_score(y_test, pred), 3),
round(f1_score(y_test, pred), 3))The exact counts depend on your library version. The two printed lines should always agree.
Common errors
- Reading the matrix transposed. Rows are actual classes and columns are predicted classes. Mixing them up swaps FP and FN, and so swaps precision and recall.
- Wrong positive class. The metrics default to label
1as positive. If your rare class is coded differently, passpos_label. - Averaging over both classes. Using
average="macro"or"weighted"blends in the majority class's good scores. For one rare class, report the positive-class metrics. - Dividing by zero. If the model predicts no positives, precision is 0/0. Scikit-learn warns and returns 0 by default. Set
zero_divisionto choose the value deliberately.
Which metric to watch
Choose by the cost of each mistake. If a missed case is costly, as in disease screening, push recall up. If false alarms are costly, as in manually reviewing flagged transactions, push precision up. F1 is a reasonable single number when both matter about equally.
Exercise
A model on a test set gives TP = 30, FP = 10, FN = 60, TN = 900. Compute precision, recall and F1, and say what accuracy would be.
Show answer
Precision = 30 / (30 + 10) = 0.75. Recall = 30 / (30 + 60) ≈ 0.333. F1 = 2 × 0.75 × 0.333 / (0.75 + 0.333) ≈ 0.462. Accuracy = (30 + 900) / 1,000 = 0.93, which looks strong even though the model finds only a third of the real positives.