Sub topic 10
Tuning the Decision Threshold
This chapter assumes you know how to train a scikit-learn binary classifier, read a confusion matrix, and interpret precision, recall and the precision-recall curve. It also assumes you can use stratified cross-validation. It builds on the earlier chapters on metrics and class weights.
Why the default threshold is rarely right
Most classifiers produce a score for the positive class. In scikit-learn this is usually predict_proba(X)[:, 1]. The predict method then turns the score into a label with a fixed rule: predict positive if the score is at least 0.5.
A threshold of 0.5 treats both kinds of error as equally costly. It also assumes the scores mean what they say. On imbalanced data neither assumption usually holds:
- A model trained on 5% positives often assigns low scores to most true positives, because the prior probability of the positive class is low. Few cases cross 0.5, so recall is poor.
- A model trained with
class_weight="balanced"or with oversampling has the opposite shift. Scores for positives are pushed up, and the model may flag too many cases, so precision drops. - The business cost of a missed fraud case is rarely the same as the cost of a false alarm.
The threshold is a free parameter. Changing it does not retrain the model. It moves the operating point along the precision-recall curve that the model already defines.
What moving the threshold does
Lowering the threshold labels more cases as positive. Recall goes up or stays the same, because every case that was positive stays positive. Precision usually goes down, because the extra cases include more false positives. Raising the threshold does the reverse.
| Change | Predicted positives | Recall | Precision (typical) |
|---|---|---|---|
| Lower threshold | More | Rises or stays equal | Falls |
| Raise threshold | Fewer | Falls or stays equal | Rises |
Precision is not strictly monotonic. With few positives predicted, one case can swing it. This is why the precision-recall curve is jagged at its high-threshold end.
Choosing a threshold: three common criteria
The right criterion depends on what the model is for.
- Maximize F1. This balances precision and recall equally. It is a reasonable default when you have no cost information.
- Meet a constraint. For example, "recall of at least 0.90, then the best precision we can get," or "precision of at least 0.80, then the best recall." Review queues with limited staff often have this shape.
- Minimize expected cost. If a missed positive costs
C_fnand a false alarm costsC_fp, pick the threshold that minimizesC_fn * FN + C_fp * FP. This is the most direct option when you can estimate the costs.
If the model's scores are well calibrated, the cost-minimizing threshold has a closed form: C_fp / (C_fp + C_fn). A missed case that costs nine times a false alarm gives a threshold of 0.1. Calibration is covered in the next chapter. Until you have checked it, treat this formula as a starting point and verify it empirically.
Do not tune on the test set
The threshold is a hyperparameter. If you pick it by looking at test-set predictions, the test score becomes optimistic, for the same reason as any other tuning on test data. You need predictions on data the model did not train on, and that data must not be the final test set.
The standard approach is to use out-of-fold predictions. cross_val_predict trains a model on each set of training folds and predicts the held-out fold. After all folds are done, every training row has a score from a model that never saw it. You choose the threshold from those scores, then apply it once to the test set.
Worked example
This example continues from the first example in the chapter on the accuracy pitfall. It uses the same synthetic dataset with about 5% positives and a stratified split. The code below is complete and runs as shown.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import precision_recall_curve, f1_score, precision_score, recall_score
from sklearn.model_selection import StratifiedKFold, cross_val_predict, train_test_split
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)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
oof = cross_val_predict(model, X_train, y_train, cv=cv, method="predict_proba")[:, 1]
precision, recall, thresholds = precision_recall_curve(y_train, oof)
f1 = 2 * precision * recall / (precision + recall + 1e-12)
best_threshold = thresholds[np.argmax(f1[:-1])]
model.fit(X_train, y_train)
test_scores = model.predict_proba(X_test)[:, 1]
default_pred = (test_scores >= 0.5).astype(int)
tuned_pred = (test_scores >= best_threshold).astype(int)
print("chosen threshold:", round(float(best_threshold), 3))
print("default 0.5 -> F1:", round(f1_score(y_test, default_pred), 3),
"precision:", round(precision_score(y_test, default_pred), 3),
"recall:", round(recall_score(y_test, default_pred), 3))
print("tuned -> F1:", round(f1_score(y_test, tuned_pred), 3),
"precision:", round(precision_score(y_test, tuned_pred), 3),
"recall:", round(recall_score(y_test, tuned_pred), 3))Exact numbers depend on your library versions, so run it and read your own output. Because the model uses balanced class weights, its scores for positives are already shifted upward. The tuned threshold will often land above 0.5, trading some recall for better precision. Without class weights, it would typically land below 0.5. In both cases the tuning step corrects for the shift using data the test set never touched.
How the code works
precision_recall_curvereturnsprecisionandrecallarrays that are one element longer thanthresholds. The last point (precision 1, recall 0) has no threshold. That is why the code usesf1[:-1].- The
1e-12term avoids division by zero when precision and recall are both zero at some threshold. np.argmaxreturns the first maximum. If several thresholds tie, you get the lowest one.- The final model is fit on the full training set, and the threshold from the out-of-fold scores is applied to its test scores. A model fit on all of the training data is slightly stronger than each fold model, so the transfer is approximate.
Picking a threshold under a constraint
When the goal is "at least 90% recall," you can read the answer from the same curve. This sketch reuses oof, precision, recall and thresholds from the previous example.
target_recall = 0.90
# recall has one more element than thresholds, so drop the final point.
ok = recall[:-1] >= target_recall
if ok.any():
# Among thresholds that meet the recall target, take the highest one,
# which gives the best precision.
constrained_threshold = thresholds[ok][-1]
print("threshold for recall >= 0.90:", round(float(constrained_threshold), 3))
print("precision at that threshold:", round(float(precision[:-1][ok][-1]), 3))
else:
print("No threshold reaches the target recall on the out-of-fold scores.")thresholds is sorted in increasing order, and recall falls as the threshold rises. So the values that meet the recall target form a prefix of the array, and the last of them is the highest usable threshold.
Using scikit-learn's built-in tools
Recent scikit-learn versions (1.5 and later) provide TunedThresholdClassifierCV. It wraps an estimator, finds the best threshold by cross-validation on the training data, and exposes a predict that uses it.
from sklearn.model_selection import TunedThresholdClassifierCV
tuned = TunedThresholdClassifierCV(
LogisticRegression(class_weight="balanced", max_iter=1000),
scoring="f1",
cv=5,
)
tuned.fit(X_train, y_train)
print("best threshold:", round(float(tuned.best_threshold_), 3))
print("test F1:", round(f1_score(y_test, tuned.predict(X_test)), 3))This continues from the worked example. The wrapper does the same job as the manual code, and it keeps the threshold search inside the estimator. That helps when you nest it in a larger cross-validation or a pipeline. The manual version is still worth knowing, because it lets you inspect the whole curve and apply constraints or cost functions.
Common errors
- Choosing the threshold on the test set. This inflates the reported metric. Use out-of-fold predictions or a separate validation set.
- Choosing it from in-sample scores. Scores from a model predicting its own training rows are too confident. The threshold you pick will not transfer.
- Tuning on resampled data. If you oversample the validation fold, the class ratio no longer matches deployment, and the best threshold shifts. Evaluate on data with the real class ratio.
- Treating a tuned threshold as permanent. The best threshold depends on the class ratio and the costs. If the positive rate in production drifts, re-check it.
- Optimizing a metric you do not care about. F1 weights precision and recall equally. If a missed case is much worse than a false alarm, use a recall constraint or a cost function.
- Tuning a noisy threshold. With few positives, the best-F1 point on the curve can be an accident of a handful of cases. Look at the shape of the F1 curve. If it is flat across a range, pick a value in the middle of the plateau.
Threshold tuning versus other remedies
Threshold tuning is cheap. It needs no retraining, no resampling and no change to the data. It also composes with the other methods: you can combine class weights, resampling or an ensemble with a tuned threshold.
It does not improve the ranking quality of the model. Metrics that depend only on ranking, such as ROC AUC and average precision, do not change when you move the threshold. If the model cannot separate the classes, no threshold fixes that. Use threshold tuning to choose an operating point, and use the other methods to improve the underlying scores.
Exercise
A fraud model is trained without class weights on data with 2% positives. At threshold 0.5, recall is 0.35. A reviewer says the team should retrain with oversampling to raise recall. Describe a cheaper step to try first, and say which data you should use to choose its value.
Show answer
Lower the decision threshold below 0.5 and measure recall and precision at each candidate value. Choose the value using out-of-fold predictions on the training data, from crossvalpredict with stratified folds, or a separate validation set with the real class ratio. Do not use the test set. Pick the threshold with a criterion that matches the goal, such as a minimum recall with the best precision above it, or minimum expected cost. Retrain with oversampling only if the ranking quality (average precision) is too low even at the best operating point.
Exercise
In the worked example, why does the code index with f1[:-1] before calling np.argmax?
Show answer
precisionrecallcurve returns precision and recall arrays with one more element than the thresholds array. The last element is a point with precision 1 and recall 0 that has no threshold. Dropping it with f1[:-1] keeps the F1 array the same length as thresholds, so the argmax index maps to a valid threshold.