Sub topic 3
Reading the confusion matrix: precision, recall and F1
This chapter assumes you can train a scikit-learn classifier, call predict and predict_proba, and split data into train and test sets. It builds on the previous chapter, where a model that always predicts the majority class reached high accuracy while finding none of the rare class. Here you will learn the metrics that expose that failure and measure the rare class directly.
The confusion matrix
A confusion matrix counts predictions by combining the true label with the predicted label. For binary classification, call the rare class of interest the positive class (label 1). Every test example falls into one of four cells:
| Row | Predicted positive | Predicted negative |
|---|---|---|
| Actually positive | True positive (TP) | False negative (FN) |
| Actually negative | False positive (FP) | True negative (TN) |
- A true positive (TP) is a positive example the model flagged as positive.
- A false negative (FN) is a positive example the model missed.
- A false positive (FP) is a negative example the model wrongly flagged.
- A true negative (TN) is a negative example the model correctly left alone.
Accuracy is (TP + TN) / (TP + TN + FP + FN). On imbalanced data, TN is huge, so it swamps the other cells. The metrics below ignore TN or use it carefully, so the rare class stays visible.
Precision, recall and F1
Each metric answers a different question.
- Precision is
TP / (TP + FP). Of everything the model flagged as positive, how much was really positive? Low precision means many false alarms. - Recall (also called sensitivity or true positive rate) is
TP / (TP + FN). Of all real positives, how many did the model find? Low recall means many misses. - F1 is the harmonic mean of precision and recall:
2 * P * R / (P + R). It is high only when both are high.
The harmonic mean punishes imbalance between the two numbers. If precision is 1.0 and recall is 0.01, the arithmetic mean is about 0.5, but F1 is about 0.02. That is the behavior you want, since a model that finds almost nothing should not look good.
There is a tradeoff. Making the model flag more cases raises recall and usually lowers precision. Flagging fewer cases does the reverse. Later chapters on threshold tuning use this tradeoff directly.
A worked example by hand
Suppose a test set has 1,000 examples, of which 50 are positive. A model flags 40 examples. Of those, 30 are truly positive.
- TP = 30
- FP = 40 − 30 = 10
- FN = 50 − 30 = 20
- TN = 1000 − 30 − 10 − 20 = 940
Then:
- Accuracy = (30 + 940) / 1000 = 0.970
- Precision = 30 / 40 = 0.750
- Recall = 30 / 50 = 0.600
- F1 = 2 × 0.75 × 0.60 / (0.75 + 0.60) ≈ 0.667
Accuracy says 97%. Recall says the model misses 40% of the cases you care about. Both statements are true, but only recall describes the rare class.
Computing the metrics in scikit-learn
The code below reproduces the setup from the first example in this tutorial, trains a class-weighted logistic regression, and prints the confusion matrix and the three metrics. It runs as shown.
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,
classification_report,
)
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(class_weight="balanced", max_iter=1000)
model.fit(X_train, y_train)
pred = model.predict(X_test)
cm = confusion_matrix(y_test, pred)
tn, fp, fn, tp = cm.ravel()
print(cm)
print("TN, FP, FN, TP:", tn, fp, fn, tp)
print("precision:", precision_score(y_test, pred))
print("recall:", recall_score(y_test, pred))
print("F1:", f1_score(y_test, pred))
print(classification_report(y_test, pred, digits=3))Exact numbers depend on your scikit-learn version, but the pattern is stable: recall on the rare class is reasonably high because of the class weights, and precision is much lower.
Reading scikit-learn's output correctly
Two details cause frequent mistakes.
- Matrix layout.
confusion_matrixputs true labels on rows and predicted labels on columns, with classes in sorted order. For labels0and1, the result is[[TN, FP], [FN, TP]]. Theravel()ordertn, fp, fn, tpfollows from this. If your labels are strings or reversed, passlabels=[0, 1]explicitly to control the order. - Which class is positive.
precision_score,recall_scoreandf1_scoredefault topos_label=1for binary data. If your rare class is not labeled1, setpos_labelyourself. Otherwise you silently score the wrong class.
Reading the classification report
classification_report prints precision, recall, F1 and support (the number of true examples) for each class, followed by averages.
| Average | What it does | Use on imbalanced data |
|---|---|---|
| Macro | Averages per-class scores with equal weight | Shows weak rare-class performance |
| Weighted | Averages per-class scores weighted by support | Dominated by the majority class, so it can hide problems |
| Micro | Pools all TP, FP, FN across classes | In single-label problems it equals accuracy |
For a rare class, read the row for that class first. The weighted average can look excellent even when the rare class is poorly handled, which repeats the accuracy pitfall in a new form.
The cost of each error type
Precision and recall are not interchangeable. Which one to prioritize depends on what each mistake costs.
| Situation | Costly error | Metric to favor |
|---|---|---|
| Cancer screening before a confirmatory test | Missing a sick patient (FN) | Recall |
| Automatically blocking a customer's card | Blocking a legitimate user (FP) | Precision |
| Spam filter for an inbox | Losing a real email (FP) | Precision |
| Manual review queue with fixed capacity | Too many alerts to review (FP) | Precision at a fixed alert count |
When both errors matter and you want one number, F1 weights them equally. When they do not, use the F-beta score, which generalizes F1:
F_beta = (1 + beta^2) * P * R / (beta^2 * P + R)
A beta above 1 favors recall, and a beta below 1 favors precision. In scikit-learn, use fbeta_score(y_true, y_pred, beta=2).
from sklearn.metrics import fbeta_score
# Continues from the previous example (y_test, pred).
print("F2 (recall-weighted):", fbeta_score(y_test, pred, beta=2))
print("F0.5 (precision-weighted):", fbeta_score(y_test, pred, beta=0.5))Edge cases and common errors
Division by zero
If the model predicts no positives, TP + FP = 0 and precision is undefined. Scikit-learn returns 0.0 and emits an UndefinedMetricWarning. You can control this with the zero_division argument, for example precision_score(y_test, pred, zero_division=0). The always-majority baseline from the previous chapter triggers exactly this case. A warning about undefined precision is a sign that your model predicted no positives at all.
Metrics depend on the threshold
predict applies a default cutoff, usually 0.5 on the predicted probability. Precision, recall and F1 describe the model at that single cutoff. Change the cutoff and all three change. The next chapter looks at curves that summarize behavior across all cutoffs.
Metrics depend on prevalence
Recall does not depend on how many negatives exist, but precision does. If the positive rate in production is 1% and in your test set it is 5%, the production precision will be lower than the test precision, even for the same model. When you resample or reweight the test set, you change the prevalence and the precision. Keep the test set at its natural class ratio so the numbers reflect real use.
Small support makes estimates noisy
With a 5% positive rate and 2,500 test examples, you have about 125 positives. Each missed positive moves recall by about 0.8 percentage points. Differences of a few points between two models can be noise. Use stratified cross-validation, which the later chapter on splitting covers, and compare the spread of scores, not a single value.
Multiclass problems
For more than two classes, you must choose an averaging scheme (average="macro", "weighted" or "micro"). Use macro averaging when every class matters equally, since it exposes poor results on small classes.
Putting it together
A practical routine when you evaluate an imbalanced classifier:
- Compute the confusion matrix and look at the raw counts first.
- Read recall and precision for the rare class, not overall accuracy.
- Decide which error is more costly, and pick F1 or an F-beta score that matches.
- Check the support of the rare class in your test data to judge how noisy the numbers are.
- Remember that these numbers belong to one decision threshold.
Exercise
A test set has 2,000 examples, 40 of them positive. A model flags 50 examples as positive, and 30 of those are truly positive. Compute TP, FP, FN, TN, accuracy, precision, recall and F1.
Show answer
TP = 30. FP = 50 − 30 = 20. FN = 40 − 30 = 10. TN = 2000 − 30 − 20 − 10 = 1940. Accuracy = (30 + 1940) / 2000 = 0.985. Precision = 30 / 50 = 0.60. Recall = 30 / 40 = 0.75. F1 = 2 × 0.60 × 0.75 / (0.60 + 0.75) = 0.90 / 1.35 ≈ 0.667. Accuracy of 98.5% looks excellent, but one in four positives is missed and two in five alarms are false.
Exercise
A classifier predicts the negative class for every example in a test set that contains positives. What are its precision, recall and F1 for the positive class, and what does scikit-learn do when you compute precision?
Show answer
TP = 0 and FP = 0, so recall = 0 / (0 + FN) = 0. Precision is 0 / 0, which is undefined. Scikit-learn returns 0.0 and raises an UndefinedMetricWarning unless you set zero_division. F1 is 0. This is why these metrics catch the failure that accuracy hides.
Exercise
A fraud team can only review 100 alerts per day, and each wrongly blocked customer causes complaints. Should the team favor recall or precision, and would you use F2 or F0.5 as a summary score?
Show answer
The team should favor precision, because the review capacity is limited and false alarms are costly. F0.5 weights precision more than recall, so it fits better than F2. Even so, recall should be reported alongside it, since a model with very high precision but tiny recall would catch little fraud.