Sub topic 8
F1 score: combining precision and recall
This chapter assumes you can already build a confusion matrix and compute precision and recall from TP, FP, and FN. It also assumes basic Python and a train/test split. Here you will learn what the F1 score measures, why it uses a harmonic mean, how to compute it by hand and with scikit-learn, and where it misleads.
Why a single number is useful
Precision and recall describe different failures. Precision is TP / (TP + FP), the share of positive predictions that are correct. Recall is TP / (TP + FN), the share of real positives that the model found.
When you compare two models, you often get two numbers each. Model A has precision 0.90 and recall 0.50. Model B has precision 0.70 and recall 0.70. Neither is better on both metrics. Model selection, hyperparameter search, and dashboards usually need one number to sort by. The F1 score is the most common such number for binary classification.
Definition
F1 is the harmonic mean of precision and recall:
F1 = 2 * precision * recall / (precision + recall)Substituting the definitions of precision and recall gives an equivalent form that uses only confusion matrix counts:
F1 = 2 * TP / (2 * TP + FP + FN)The second form shows two facts. First, F1 never uses TN. Second, FP and FN carry equal weight in the denominator, so F1 treats the two error types symmetrically.
A worked example
Use the counts from earlier chapters: TP=3, FP=1, TN=5, FN=1. Precision is 3/4 = 0.75. Recall is 3/4 = 0.75. Then:
tp, fp, tn, fn = 3, 1, 5, 1
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(f1_from_pr, f1_from_counts) # 0.75 0.75Both forms agree. When precision and recall are equal, F1 equals that shared value. When they differ, F1 falls between them and sits closer to the smaller one.
Why a harmonic mean and not an average
The arithmetic mean of 1.0 and 0.01 is 0.505. That would rate a model as "about 50% good" even though it finds only 1% of the real positives. Such a model could be one that predicts positive for a single extremely obvious case and nothing else.
The harmonic mean punishes imbalance between the two inputs. It is dominated by the smaller value, so a model cannot hide a very low recall behind a perfect precision, or the reverse.
pairs = [(0.75, 0.75), (0.9, 0.5), (0.6, 1.0), (1.0, 0.01)]
for p, r in pairs:
arithmetic = (p + r) / 2
f1 = 2 * p * r / (p + r)
print(p, r, round(arithmetic, 3), round(f1, 3))
# 0.75 0.75 0.75 0.75
# 0.9 0.5 0.7 0.643
# 0.6 1.0 0.8 0.75
# 1.0 0.01 0.505 0.02| Precision | Recall | Arithmetic mean | F1 |
|---|---|---|---|
| 0.75 | 0.75 | 0.750 | 0.750 |
| 0.90 | 0.50 | 0.700 | 0.643 |
| 0.60 | 1.00 | 0.800 | 0.750 |
| 1.00 | 0.01 | 0.505 | 0.020 |
The last row is the important one. The arithmetic mean calls it passable, and F1 calls it nearly useless.
F1 along the decision threshold
Recall from the previous chapter that raising the decision threshold increases precision and decreases recall. F1 combines the two, so it usually peaks at some intermediate threshold. You can sweep thresholds and pick the one with the highest F1 on validation data.
y_true = [1, 1, 1, 0, 0, 0, 0, 0]
scores = [0.9, 0.6, 0.4, 0.7, 0.3, 0.2, 0.1, 0.05]
def f1_from_counts(tp, fp, fn):
denominator = 2 * tp + fp + fn
return 2 * tp / denominator if denominator else 0.0
results = []
for threshold in (0.3, 0.5, 0.8):
y_pred = [int(s >= threshold) for s in scores]
tp = sum(t == 1 and p == 1 for t, p in zip(y_true, y_pred))
fp = sum(t == 0 and p == 1 for t, p in zip(y_true, y_pred))
fn = sum(t == 1 and p == 0 for t, p in zip(y_true, y_pred))
f1 = f1_from_counts(tp, fp, fn)
results.append((threshold, f1))
print(threshold, round(f1, 2))
best = max(results, key=lambda pair: pair[1])
print("best threshold:", best[0])
# 0.3 0.75
# 0.5 0.67
# 0.8 0.5
# best threshold: 0.3At threshold 0.3 the model has precision 0.6 and recall 1.0. At 0.8 it has precision 1.0 and recall 0.33. F1 prefers the first, because its recall advantage outweighs its precision disadvantage. This is an outcome of equal weighting, not a general rule. A different cost structure can prefer a different threshold, which is covered below.
Computing F1 with scikit-learn
sklearn.metrics.f1_score takes the true labels and the predicted labels, in that order. It does not take scores, so apply the threshold first.
from sklearn.metrics import f1_score
y_true = [1, 0, 1, 1, 0, 0, 0, 0, 0, 1]
y_pred = [1, 0, 0, 1, 0, 1, 0, 0, 0, 1]
print(f1_score(y_true, y_pred)) # 0.75This matches the manual result. For binary problems, pos_label=1 is the default. If your positive class is labeled something else, such as "spam", pass pos_label="spam". Otherwise scikit-learn raises an error for string labels, or it scores the wrong class when the labels are 0 and 1 and you meant the other one.
F-beta: weighting recall or precision more
F1 gives precision and recall equal weight. The general F-beta score lets you shift that weight with a parameter beta:
F_beta = (1 + beta^2) * precision * recall / (beta^2 * precision + recall)beta > 1 favors recall. beta < 1 favors precision. beta = 1 is F1. A common choice is F2 when missed positives are costlier than false alarms, and F0.5 when false alarms are costlier.
from sklearn.metrics import fbeta_score
y_true = [1, 1, 1, 0, 0, 0, 0, 0]
y_pred = [1, 1, 1, 1, 1, 0, 0, 0] # threshold 0.3 from the sweep above
for beta in (0.5, 1, 2):
print(beta, round(fbeta_score(y_true, y_pred, beta=beta), 3))
# 0.5 0.652
# 1 0.75
# 2 0.882This prediction set has precision 0.6 and recall 1.0. As beta rises, the score rises toward the recall value, as you would expect.
Gotchas and failure modes
F1 ignores true negatives
TN never appears in the formula. This is useful on imbalanced data, because the large negative class cannot inflate the score. It is a drawback when correct rejections matter to you. Two models with identical TP, FP, and FN get identical F1 even if one has far more TN.
F1 depends on which class is positive
Accuracy is unchanged if you swap the class labels. F1 is not, because the positive class defines TP, FP, and FN. If you relabel a rare class as the negative one, you get a different F1 that mostly reflects the majority class. State which class is positive whenever you report F1.
F1 depends on class prevalence
F1 has no fixed "good" value. Suppose a fraction p of the examples are positive and a model predicts positive for every example. Then precision is p, recall is 1, and F1 is 2p / (1 + p).
- With 50% positives, this trivial model scores F1 = 0.667.
- With 1% positives, it scores F1 = 0.0198.
So an F1 of 0.67 is a strong result on a rare-event task and a weak one on a balanced task. Always compare against a trivial baseline measured on the same data.
Zero division
If a model predicts no positives, precision is 0 / 0. If the data has no real positives, recall is 0 / 0. In these cases scikit-learn returns 0.0 and issues an UndefinedMetricWarning by default. Set zero_division explicitly so the behavior is deliberate and the warning does not hide real problems:
from sklearn.metrics import accuracy_score, f1_score
# 1 fraud case in 100 transactions; the model predicts "not fraud" every time
y_true = [1] + [0] * 99
y_pred = [0] * 100
print(accuracy_score(y_true, y_pred)) # 0.99
print(f1_score(y_true, y_pred, zero_division=0)) # 0.0Accuracy says 0.99. F1 says 0.0, which is the honest answer for a model that never finds the fraud.
Equal weighting is an assumption
F1 is appropriate when you roughly care equally about false positives and false negatives. If a missed positive costs ten times more than a false alarm, F1 does not reflect that, and the threshold that maximizes it may not be the one that minimizes your real cost. Use F-beta or compute the expected cost directly.
F1 is a point on a threshold, not a curve
One F1 value describes one threshold. Two models with the same F1 at their default thresholds can behave very differently at other thresholds. If the final threshold is not fixed yet, compare models with a threshold-free method such as a precision-recall curve, and use F1 only after you fix the operating point.
Checklist for reporting F1
- Name the positive class.
- State the threshold, or say that it is the default 0.5 of the model's probability output.
- Report precision and recall next to F1, so readers can see which one is low.
- Report the F1 of a trivial baseline on the same data.
- Compute it on held-out data, with any threshold tuned on a separate validation set.
- Set
zero_divisiondeliberately.
Multiclass problems add one more decision, which is how to average per-class F1 scores. That is the subject of a later chapter.
Exercise
A model on a test set has TP=40, FP=10, FN=30, and TN=920. Compute precision, recall, and F1. Then say what the 920 true negatives contribute to F1.
Show answer
Precision = 40 / (40 + 10) = 0.80. Recall = 40 / (40 + 30) = 0.571. F1 = 2 40 / (2 40 + 10 + 30) = 80 / 120 = 0.667. The 920 true negatives contribute nothing, because TN does not appear in the F1 formula.
Exercise
Model A has precision 0.9 and recall 0.1. Model B has precision 0.5 and recall 0.5. Compare their arithmetic means and their F1 scores, and explain which model F1 prefers and why.
Show answer
Both have an arithmetic mean of 0.5, so the arithmetic mean cannot separate them. F1 for A is 2 0.9 0.1 / 1.0 = 0.18. F1 for B is 0.5. F1 prefers B, because the harmonic mean is pulled toward the smaller value, and A's recall of 0.1 drags its score down.
Exercise
A dataset has 2% positive examples. A model predicts positive for every example. What are its precision, recall, and F1, and what does this tell you about interpreting F1?
Show answer
Precision = 0.02 and recall = 1.0. F1 = 2 0.02 1.0 / (0.02 + 1.0) = 0.04 / 1.02, which is about 0.039. A trivial model already has F1 near 0.04 here, so F1 values must be judged against a baseline on the same data, and an F1 of 0.3 could be a real improvement on a task like this.