Sub topic 8
F1: combining precision and recall
This chapter assumes you can already compute precision and recall from the four cells of a binary confusion matrix. You should also be comfortable reading short Python snippets that use scikit-learn. Here you will learn what F1 measures, why it uses a harmonic mean, what it ignores, and where it misleads.
Why one number is tempting
Precision answers "when the model says positive, how often is it right?" Recall answers "of the real positives, how many did the model find?" Models trade one against the other, so comparing two models on two numbers is awkward. If model A has higher precision and model B has higher recall, neither is clearly better.
F1 folds both into one score between 0 and 1. It is high only when precision and recall are both high.
The definition
F1 is the harmonic mean of precision and recall:
F1 = 2 * precision * recall / (precision + recall)Substituting the cell counts gives a form that is often easier to compute:
F1 = 2 * TP / (2 * TP + FP + FN)This second form shows two facts:
- F1 depends only on TP, FP and FN. The true negative count TN does not appear.
- Every error, whether a false positive or a false negative, counts the same in the denominator.
For the matrix used earlier in this tutorial (TN = 4, FP = 2, FN = 1, TP = 3):
- precision = 3 / 5 = 0.6
- recall = 3 / 4 = 0.75
- F1 = 2 × 3 / (2 × 3 + 2 + 1) = 6 / 9 ≈ 0.667
from sklearn.metrics import confusion_matrix, f1_score
y_true = [1, 0, 1, 1, 0, 0, 1, 0, 0, 0]
y_pred = [1, 0, 0, 1, 0, 1, 1, 1, 0, 0]
tn, fp, fn, tp = confusion_matrix(y_true, y_pred, labels=[0, 1]).ravel()
precision = tp / (tp + fp)
recall = tp / (tp + fn)
f1_from_pr = 2 * precision * recall / (precision + recall)
f1_from_counts = 2 * tp / (2 * tp + fp + fn)
print(round(f1_from_pr, 3)) # 0.667
print(round(f1_from_counts, 3)) # 0.667
print(round(f1_score(y_true, y_pred), 3)) # 0.667All three lines agree. If your hand calculation and the library disagree, the usual cause is a mix-up of which class is positive or which axis holds the actual labels. Check the layout first.
Why a harmonic mean
You might expect the plain average of precision and recall. That average hides a failure that F1 exposes.
Imagine a model that flags only the one case it is most sure about. Its precision is 1.0, because that single flag is correct. Its recall is 0.01, because it found one positive out of a hundred. The arithmetic mean says the model is about 50% good. That is a poor description of a model that misses 99% of the positives.
The harmonic mean is dominated by the smaller value:
| Precision | Recall | Arithmetic mean | F1 (harmonic mean) |
|---|---|---|---|
| 0.60 | 0.75 | 0.675 | 0.667 |
| 1.00 | 0.01 | 0.505 | 0.020 |
| 0.90 | 0.90 | 0.900 | 0.900 |
When precision and recall are equal, F1 equals both. As they drift apart, F1 falls toward the weaker one. You cannot buy a good F1 by maximizing one side and ignoring the other.
F1 and class imbalance
Earlier you saw that a model predicting "negative" for every case scores 95% accuracy on a 95/5 split. F1 does not fall for this trap. That model has TP = 0, so recall is 0 and F1 is 0.
from sklearn.metrics import accuracy_score, f1_score
y_true = [0] * 95 + [1] * 5
y_pred = [0] * 100 # always predicts the negative class
print(accuracy_score(y_true, y_pred)) # 0.95
print(f1_score(y_true, y_pred, zero_division=0)) # 0.0The zero_division=0 argument matters here. This model never predicts positive, so precision is 0 / 0, which is undefined. Without the argument, scikit-learn returns 0.0 but emits a warning. Setting it explicitly documents your choice and keeps logs clean.
What F1 ignores
Because TN is absent from the formula, F1 has two properties you should keep in mind.
It does not reward correct negatives. Adding a thousand easy negatives that the model classifies correctly raises accuracy sharply and leaves F1 unchanged. That is useful when negatives are plentiful and uninteresting, such as searching for rare defects. It is a problem when negative predictions matter to you, for example when a false alarm triggers an expensive action and you care about specificity.
It depends on which class you call positive. Switch the labels and the counts in the formula change. Using the same predictions as above with class 0 as positive gives TP = 4, FP = 1, FN = 2:
from sklearn.metrics import f1_score
y_true = [1, 0, 1, 1, 0, 0, 1, 0, 0, 0]
y_pred = [1, 0, 0, 1, 0, 1, 1, 1, 0, 0]
print(round(f1_score(y_true, y_pred, pos_label=1), 3)) # 0.667
print(round(f1_score(y_true, y_pred, pos_label=0), 3)) # 0.727Neither value is wrong. They answer different questions. Always report which class is positive next to the F1 number.
F1 at a single threshold
F1 is computed from hard predictions, so it describes the model at one decision threshold. Change the threshold and the cells move, so F1 moves too. Reusing the scores from the threshold chapter:
from sklearn.metrics import confusion_matrix, f1_score
y_true = [1, 0, 1, 1, 0, 0, 1, 0, 0, 0]
scores = [0.9, 0.2, 0.4, 0.8, 0.1, 0.7, 0.6, 0.55, 0.3, 0.35]
for threshold in (0.35, 0.5, 0.65):
y_pred = [1 if s >= threshold else 0 for s in scores]
tn, fp, fn, tp = confusion_matrix(y_true, y_pred, labels=[0, 1]).ravel()
print(threshold, (tn, fp, fn, tp), round(f1_score(y_true, y_pred), 3))
# 0.35 (3, 3, 0, 4) 0.727
# 0.5 (4, 2, 1, 3) 0.667
# 0.65 (5, 1, 2, 2) 0.571On this small sample, the lowest threshold gives the best F1. It finds every positive (recall 1.0) at the cost of precision 0.571. With only ten examples, treat this as an illustration. On real data you would pick the threshold on a validation set, then report F1 on a separate test set.
Two models compared at their default thresholds may not be compared fairly. One may simply have a threshold that suits F1 better. If you want to judge the ranking quality of the scores themselves, use a threshold-free measure instead.
Weighting recall or precision: F-beta
F1 treats precision and recall as equally important. When they are not, use the F-beta score:
F_beta = (1 + beta^2) * precision * recall / (beta^2 * precision + recall)A beta above 1 weights recall more. A beta below 1 weights precision more. F1 is the special case beta = 1.
from sklearn.metrics import fbeta_score
y_true = [1, 0, 1, 1, 0, 0, 1, 0, 0, 0]
y_pred = [1, 0, 0, 1, 0, 1, 1, 1, 0, 0]
print(round(fbeta_score(y_true, y_pred, beta=2), 3)) # 0.714
print(round(fbeta_score(y_true, y_pred, beta=0.5), 3)) # 0.625Recall (0.75) is higher than precision (0.6) for this model, so favoring recall with beta = 2 raises the score and favoring precision with beta = 0.5 lowers it. Pick beta from the cost of the errors, before you look at the results.
Multiclass F1
For more than two classes, F1 is computed per class, treating each class in turn as positive and all others as negative. You then need a single summary. Macro, micro and weighted averaging do that, and a later chapter covers them. For now, note that f1_score on multiclass labels raises an error unless you pass an average argument or ask for average=None to get one score per class.
Common errors
- Averaging precision and recall by hand. Use the harmonic formula. The arithmetic mean overstates lopsided models.
- Computing F1 from averaged precision and averaged recall. The F1 of averages differs from the average of F1 scores. Decide which one you are reporting and say so.
- Treating F1 as threshold-independent. It describes one operating point.
- Ignoring TN when TN matters. If false alarms or correct rejections carry real cost, check specificity too.
- Comparing F1 across datasets with different class balance. Precision depends on how common positives are, so the same model gives different F1 values on different test sets.
- Not stating the positive class. The number is meaningless without it.
- Reporting a tiny improvement without checking sample size. A change of 0.01 on a few hundred examples is often noise.
Exercise
A binary classifier produces TP = 40, FP = 10, FN = 30 and TN = 920. Compute precision, recall and F1. Then say what happens to each of the three values if the test set gains 1,000 more correctly classified negatives.
Show answer
Precision = 40 / 50 = 0.8. Recall = 40 / 70 ≈ 0.571. F1 = 2 × 40 / (2 × 40 + 10 + 30) = 80 / 120 ≈ 0.667. Adding correctly classified negatives raises only TN, which appears in none of the three formulas. All three values stay the same, while accuracy would rise.
Exercise
A model has precision 0.95 and recall 0.05. Does the arithmetic mean or F1 give the better picture of this model, and what is F1?
Show answer
F1 gives the better picture. The arithmetic mean is 0.50, which suggests a mediocre model. F1 = 2 × 0.95 × 0.05 / (0.95 + 0.05) = 0.095, which reflects that the model finds only 5% of the real positives.