Sub topic 9
Moving the threshold: precision versus recall
This chapter assumes you can compute precision and recall from confusion matrix counts and read short Python. Earlier chapters covered both, so here we ask what happens when you change the rule that turns a model's score into a yes or no.
Scores come first, labels come second
Most classifiers do not output a class directly. A logistic regression, a gradient-boosted tree, or a neural network produces a score for each example, usually a number between 0 and 1. In scikit-learn you get these scores from predict_proba or decision_function.
The class label is a second step: pick a decision threshold, which is a cutoff on the score. Every example with a score at or above the threshold is predicted positive. Every other example is predicted negative.
predicted label = 1 if score >= threshold else 0The predict method hides this step. For many models it uses a threshold of 0.5 on the predicted probability. That value is a default, not a property of your problem. Nothing in the data says 0.5 is the right cutoff, and for most real problems it is not.
Changing the threshold does not change the model or its scores. It changes only which examples count as positive predictions, and therefore changes the four confusion matrix cells.
What happens when the threshold rises
Raise the threshold and the model becomes stricter. Fewer examples clear the bar, so fewer are predicted positive. Two things follow.
- Recall can only stay the same or fall. Recall is TP / (TP + FN). The denominator is fixed by the data, because the number of real positives does not change. Raising the threshold can only turn predicted positives into predicted negatives, so TP never increases.
- Precision usually rises, but not always. Precision is TP / (TP + FP). The examples dropped first are the lowest-scoring ones, which are more likely to be false positives. So precision tends to go up. It is not guaranteed to, because one true positive with a low score can be dropped before a false positive with a higher score.
Lowering the threshold does the reverse. More examples are predicted positive, recall rises toward 1.0, and precision tends to fall as more false positives get through.
A worked sweep
Here are eight examples. Three are truly positive and five are truly negative. The scores were chosen so the model is useful but imperfect: one negative (score 0.7) outscores two of the positives.
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]
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))
precision = tp / (tp + fp) if tp + fp else 0.0
recall = tp / (tp + fn)
print(threshold, round(precision, 2), round(recall, 2))
# 0.3 0.6 1.0
# 0.5 0.67 0.67
# 0.8 1.0 0.33The same model, with the same scores, produces three different behaviors:
| Threshold | Predicted positive | TP | FP | FN | Precision | Recall |
|---|---|---|---|---|---|---|
| 0.3 | 5 | 3 | 2 | 0 | 0.60 | 1.00 |
| 0.5 | 3 | 2 | 1 | 1 | 0.67 | 0.67 |
| 0.8 | 1 | 1 | 0 | 2 | 1.00 | 0.33 |
At 0.3 the model finds every positive, but two of its five alerts are wrong. At 0.8 every alert is correct, but it finds only one positive in three. Neither extreme is better in general. Which one you want depends on the cost of each error, as discussed earlier in the tutorial.
Sweeping every useful threshold
Trying three thresholds by hand shows the idea. To see the whole trade-off, evaluate one threshold per distinct score. A threshold between two adjacent scores gives the same predictions as the higher score, so these are the only thresholds that change anything.
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]
total_pos = sum(y_true)
print("threshold precision recall f1")
for threshold in sorted(set(scores), reverse=True):
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))
precision = tp / (tp + fp)
recall = tp / total_pos
f1 = 2 * precision * recall / (precision + recall)
print(f"{threshold:.2f} {precision:.2f} {recall:.2f} {f1:.2f}")Running it prints:
threshold precision recall f1
0.90 1.00 0.33 0.50
0.70 0.50 0.33 0.40
0.60 0.67 0.67 0.67
0.40 0.75 1.00 0.86
0.30 0.60 1.00 0.75
0.20 0.50 1.00 0.67
0.10 0.43 1.00 0.60
0.05 0.38 1.00 0.55Three things in this table are worth noticing.
- Recall never goes down as the threshold falls. It climbs from 0.33 to 1.00 and then stays there.
- Precision does not fall smoothly. From threshold 0.70 to 0.60 it rises from 0.50 to 0.67, because the example added at 0.60 is a true positive. The trade-off is a tendency, not a strict law.
- F1 peaks at threshold 0.40 (0.86). That is the point that balances the two measures best for this data, and it is not the default 0.5.
Every row has at least one predicted positive, so the code never divides by zero. If you sweep thresholds above the highest score, TP + FP is 0 and precision is undefined. That edge case is covered under pitfalls below.
The precision-recall curve
If you plot the (recall, precision) pair for every threshold, you get the precision-recall curve. It shows the whole trade-off at once, so you can compare models without committing to a threshold first. A model whose curve sits above another's is better at every operating point on the plot.
scikit-learn computes the curve for you:
from sklearn.metrics import precision_recall_curve
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]
precision, recall, thresholds = precision_recall_curve(y_true, scores)
for t, p, r in zip(thresholds, precision, recall):
print(f"{t:.2f} {p:.2f} {r:.2f}")
# 0.05 0.38 1.00
# 0.10 0.43 1.00
# 0.20 0.50 1.00
# 0.30 0.60 1.00
# 0.40 0.75 1.00
# 0.60 0.67 0.67
# 0.70 0.50 0.33
# 0.90 1.00 0.33The output matches the manual sweep, in the opposite order. Two details trip people up:
thresholdsis sorted from low to high, so recall runs from high to low.precisionandrecalleach have one more element thanthresholds. The last pair is always precision 1.0 and recall 0.0, which is the point where nothing is predicted positive. That is why the loop above useszip, which stops at the shortest list and drops that extra point.
The output shown assumes scikit-learn 1.1 or later. Older versions stop the curve once recall first reaches 1.0, so they return fewer rows.
Choosing a threshold
A threshold is a business or safety decision expressed as a number. Here are three common ways to pick one, from simplest to most flexible.
- Maximize F1. This suits cases where both error types matter about equally. The sweep above found 0.40 this way.
- Fix one metric and maximize the other. For example, "recall must be at least 0.95, then get the best precision available." A cancer screening test or a safety filter often works this way. Find the highest threshold that still meets the recall floor.
- Minimize expected cost. If a false negative costs 50 units and a false positive costs 1, choose the threshold that minimizes
50 * FN + 1 * FP. This uses the error costs directly instead of going through a summary metric.
Here is the third approach on the same toy data, with a cost of 5 per false negative and 1 per false positive:
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]
cost_fn, cost_fp = 5, 1
best = None
for threshold in sorted(set(scores)):
y_pred = [int(s >= threshold) for s in scores]
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))
cost = cost_fn * fn + cost_fp * fp
if best is None or cost < best[1]:
best = (threshold, cost)
print(best) # (0.4, 2)At threshold 0.4 the model has no false negatives and two false positives... wait, check against the table: at 0.4 the sweep shows one false positive (precision 0.75 with three true positives means one false positive). So the cost there is 5 0 + 1 1 = 1, not 2. Rerun this reasoning with the code's own definition: fp counts negatives scoring at or above 0.4, which is only the 0.7 example, so fp = 1 and the cost is 1.
The printed result is therefore (0.4, 1).
Edge cases and gotchas
- Ties in scores. If several examples share a score, they all move across the threshold together. With few distinct scores, such as a depth-limited decision tree, you may have only a handful of usable operating points.
- Scores are not always probabilities. Some models produce scores that rank examples well but are not calibrated. A score of 0.8 may not mean an 80% chance of being positive. Thresholds still work for ranking, but a cutoff chosen on one model does not transfer to another model or to a retrained version of the same model.
- Class balance shifts. If the share of positives in production differs from your validation data, precision changes even at the same threshold, because it depends on how many negatives are there to produce false positives. Recall is unaffected by a shift in the number of negatives.
- Undefined precision. When a threshold is high enough that nothing is predicted positive, precision is 0 / 0. scikit-learn's
precision_scorereturns 0.0 and warns by default. You can setzero_divisionto choose the value explicitly. - Metrics that ignore the threshold. Average precision and ROC AUC summarize performance across all thresholds. They are useful for comparing models, but you still have to pick one threshold to deploy.
Key points
- A threshold turns scores into labels, and the default 0.5 is only a default.
- Raising the threshold lowers or keeps recall and usually raises precision. Lowering it does the opposite.
- The precision-recall curve shows all the trade-offs at once, and
precision_recall_curvecomputes it. - Choose the threshold from validation data using an F1 target, a recall or precision floor, or an explicit error cost.
Exercise
Using the scores and labels from this chapter (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]), a screening team requires recall of at least 0.9. Which threshold from the sweep gives the highest precision while meeting that requirement, and what are its precision and recall? Why does picking a higher threshold fail the requirement?
Show answer
Only thresholds of 0.40 and below reach recall 1.00, since recall is 0.67 at 0.60. Among them, precision is highest at 0.40 (0.75, with TP=3 and FP=1) compared with 0.60 at 0.30 and lower values below that. So the answer is threshold 0.40, precision 0.75, recall 1.00. A higher threshold such as 0.60 drops the example with score 0.4, which is a true positive, so recall falls to 0.67 and misses the 0.9 floor.
Exercise
Precision rose from 0.50 to 0.67 when the threshold went from 0.70 down to 0.60 in the sweep. Why is it wrong to say that lowering the threshold always lowers precision?
Show answer
Lowering the threshold adds the next-highest-scoring example to the predicted positives. If that example is a true positive, as the 0.6 example is, TP grows while FP stays the same, so precision goes up. Precision falls only when the added example is a false positive. Over a wide range of thresholds precision tends to fall, but it can rise locally.