Sub topic 10
How the decision threshold reshapes the matrix
This chapter assumes you can read a binary confusion matrix (rows are actual labels, columns are predicted labels, in scikit-learn's orientation). It also assumes you know precision, recall and specificity, and that you can read short Python snippets. Here the question is where the cell counts come from, and how one choice, the decision threshold, moves counts between cells.
Scores come first, labels second
Most classifiers do not output a class. They output a score for the positive class, often a probability. A separate rule turns that score into a label:
predicted label = 1 if score >= threshold, else 0The threshold is the cutoff in that rule. Libraries often hide it. In scikit-learn, predict() on a probabilistic classifier uses 0.5 on the positive-class probability, but predict_proba() gives you the scores so you can pick your own cutoff. Some classifiers, such as support vector machines, use 0 on a decision function instead.
The model that produces the scores stays the same. The matrix you see depends on both the model and the threshold. Two people can train the same model, choose different thresholds, and report different matrices.
The same scores at three thresholds
Take ten examples with true labels and positive-class scores:
from sklearn.metrics import confusion_matrix
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]
print("threshold TN FP FN TP precision recall FPR")
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()
precision = tp / (tp + fp) if (tp + fp) else float("nan")
recall = tp / (tp + fn)
fpr = fp / (fp + tn)
print(f"{threshold:<9} {tn:>2} {fp:>2} {fn:>2} {tp:>2} "
f"{precision:9.3f} {recall:6.3f} {fpr:.3f}")The counts and metrics it computes:
| Threshold | TN | FP | FN | TP | Precision | Recall | FPR |
|---|---|---|---|---|---|---|---|
| 0.35 | 3 | 3 | 0 | 4 | 0.571 | 1.000 | 0.500 |
| 0.50 | 4 | 2 | 1 | 3 | 0.600 | 0.750 | 0.333 |
| 0.65 | 5 | 1 | 2 | 2 | 0.667 | 0.500 | 0.167 |
Each row is a different matrix built from identical scores. Raising the threshold from 0.35 to 0.65 does three things:
- Fewer examples are predicted positive, so the right-hand column of the matrix shrinks.
- False positives fall from 3 to 1, and those examples move into the true negative cell.
- False negatives rise from 0 to 2, and those examples move out of the true positive cell.
The row totals never change. There are always 4 actual positives and 6 actual negatives. Moving the threshold only shifts examples between the two cells in the same row. Actual positives slide between TP and FN. Actual negatives slide between FP and TN.
Which metrics move, and how
Recall and specificity respond predictably, because each uses only one row of the matrix:
- Recall is TP / (TP + FN), a ratio within the actual-positive row. Lowering the threshold never decreases it.
- Specificity is TN / (TN + FP), a ratio within the actual-negative row. Raising the threshold never decreases it.
- The false positive rate is 1 minus specificity, so it moves in the opposite direction to specificity.
Precision is TP / (TP + FP), and it mixes both rows. A higher threshold removes some false positives, which helps. It also removes some true positives, which hurts. Precision therefore tends to rise with the threshold, but it can go up and down along the way. In the table it happens to rise steadily, and with a small sample that is not guaranteed in general.
Accuracy also has no fixed direction. Here it is 0.7 at 0.35 and 0.5, and 0.7 at 0.65. Three different matrices produce the same accuracy, which is a good reason not to judge a threshold by accuracy alone.
Edge cases at the extremes
- Threshold at or below the lowest score. Every example is predicted positive. FN and TN are both 0, recall is 1, and FPR is 1.
- Threshold above the highest score. Nothing is predicted positive. TP and FP are both 0, so recall is 0 and FPR is 0. Precision is 0/0, which is undefined. scikit-learn's
precision_scorereturns 0.0 and warns, unless you setzero_division. State your convention when you report it. - Ties. Examples with exactly the threshold score fall on the positive side when you use
>=. If you write>, they fall on the negative side. At threshold 0.35 above, the negative example scoring 0.35 is a false positive only because of>=. Check which comparison your library uses. - Scores that are not probabilities. A score of 0.5 only means "50% likely" if the model is calibrated. Many models are not, especially after class weighting or resampling. A threshold of 0.5 is a default, not a property of the data.
Choosing a threshold
A threshold is a decision about which error costs more. Three approaches are common:
- Minimize expected cost. Put a cost on each false positive and each false negative, then pick the threshold with the lowest total.
- Meet a constraint. For example, "recall must be at least 0.95, then maximize precision". Screening tools often work this way.
- Maximize a summary metric. F1 is a common choice when both error types matter about equally.
Here is the first approach on the same data, with a false negative costing ten times as much as a false positive:
import numpy as np
from sklearn.metrics import confusion_matrix
y_true = np.array([1, 0, 1, 1, 0, 0, 1, 0, 0, 0])
scores = np.array([0.9, 0.2, 0.4, 0.8, 0.1, 0.7, 0.6, 0.55, 0.3, 0.35])
cost_fp, cost_fn = 1, 10
best_threshold, best_cost = None, None
for t in np.unique(scores):
y_pred = (scores >= t).astype(int)
tn, fp, fn, tp = confusion_matrix(y_true, y_pred, labels=[0, 1]).ravel()
cost = int(cost_fp * fp + cost_fn * fn)
if best_cost is None or cost < best_cost:
best_threshold, best_cost = float(t), cost
print(f"best threshold {best_threshold}, cost {best_cost}")
# best threshold 0.4, cost 2The loop tries each distinct score as a candidate threshold, because the matrix can only change at those values. The best choice is 0.4, which gives the matrix [[4 2] [0 4]]: two false alarms and no missed positives. The default 0.5 would cost 2 + 10 = 12, because it misses one positive. With these costs, the default threshold is six times worse than the best one.
For larger datasets, use sklearn.metrics.precision_recall_curve and sklearn.metrics.roc_curve. They return the metrics at every useful threshold in one call, so you don't need a loop.
Common mistakes
- Tuning the threshold on the test set. The threshold is a parameter you fit. Choose it on a validation set or with cross-validation, then report the matrix on held-out test data at that fixed threshold.
- Comparing models at different thresholds. A model with a precision of 0.8 at one threshold and a model with a precision of 0.7 at another are not comparable. Compare at equal recall, equal cost, or across all thresholds with a curve.
- Assuming the threshold transfers. If the share of positives changes in production, a threshold tuned on old data may no longer give the same precision. Recall and specificity are more stable under that shift, because each is computed within one row.
- Reporting only one matrix. A single matrix is a single point on a trade-off. Say which threshold produced it.
Summary of the idea
The model ranks examples by score. The threshold decides how many of the top-ranked examples count as positive. Every matrix is one cut through that ranking. Sliding the cut moves examples between cells in the same row, and recall, specificity and precision follow from where it lands.
Exercise
Using the ten scores above (positives score 0.9, 0.4, 0.8, 0.6; negatives score 0.2, 0.1, 0.7, 0.55, 0.3, 0.35), build the confusion matrix at threshold 0.75 with the rule score >= threshold. Then give recall and FPR, and say whether false negatives went up or down compared with threshold 0.65.
Show answer
Predicted positives are the scores 0.9, 0.8 (both actual positives) and none of the negatives, since 0.7 is below 0.75. So TP = 2, FN = 2, FP = 0, TN = 6, giving [[6 0] [2 2]]. Recall = 2/4 = 0.5 and FPR = 0/6 = 0. False negatives stay at 2, the same as at 0.65, so they did not go up. The only change from 0.65 is that the one false positive (the negative scoring 0.7) became a true negative.
Exercise
A fraud model is deployed with the default threshold of 0.5. Missing a fraud costs about 50 times as much as reviewing a legitimate transaction by hand. Should the threshold go up or down, and which matrix cells change?
Show answer
It should go down. A lower threshold moves false negatives into true positives, which removes expensive misses. The price is that some true negatives become false positives, which means more manual reviews. Because a false negative costs 50 times more, accepting several extra false positives per caught fraud is worth it. Pick the exact value by minimizing total cost on validation data.