Sub topic 10
Tuning the Decision Threshold
This chapter assumes you know scikit-learn estimators, predict_proba, and the precision-recall trade-off from earlier chapters. It also assumes you have a stratified train/test split.
Why the threshold matters
A classifier such as logistic regression outputs a probability-like score. The predict method turns that score into a label with a fixed cutoff, usually 0.5. That cutoff is a default, not a rule. On imbalanced data, the best cutoff is often far from 0.5.
Moving the threshold trades precision against recall:
- A lower threshold flags more cases as positive. Recall rises and precision usually falls.
- A higher threshold flags fewer cases. Precision usually rises and recall falls.
Class weights and resampling change the model. Threshold tuning changes only how you read its scores. It is cheap, and it works with any model that produces scores.
Choose the threshold from out-of-fold predictions
You need data to pick the threshold. There are two ways to get this wrong:
- Picking it on the test set. The test score is then optimistic, because the test data helped choose a setting.
- Picking it on predictions the model made for its own training rows. Those scores are too confident, so the chosen threshold will not transfer.
The fix is out-of-fold predictions. cross_val_predict gives every training row a score from a model that never saw that row. You tune on those scores, fit the final model, and apply the chosen threshold to the test set once.
Worked example
This code continues from the first example in this tutorial, which created X_train, X_test, y_train and y_test.
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import precision_recall_curve, f1_score
from sklearn.model_selection import StratifiedKFold, cross_val_predict
# Continues from the first example (X_train, X_test, y_train, y_test).
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_pred = (model.predict_proba(X_test)[:, 1] >= best_threshold).astype(int)
print("threshold:", best_threshold)
print("test F1:", f1_score(y_test, test_pred))Step by step:
cross_val_predictwithmethod="predict_proba"returns one out-of-fold score per training row. Taking column[:, 1]keeps the positive class.precision_recall_curvereturns precision and recall at each candidate threshold. Itsprecisionandrecallarrays have one more entry thanthresholds, so the code drops the last entry withf1[:-1].- The small
1e-12avoids dividing by zero when precision and recall are both zero. np.argmaxpicks the threshold with the highest F1.- The final model is fitted on all training data. The test set is scored once with the chosen threshold.
Common errors
| Error | Effect | Fix |
|---|---|---|
| Tuning the threshold on the test set | Inflated test metrics | Tune on out-of-fold training scores |
| Using in-sample training scores | Threshold too high or poorly placed | Use `cross_val_predict` |
| Forgetting the length mismatch in `precision_recall_curve` | Wrong threshold index | Slice with `[:-1]` |
| Maximizing F1 when costs are unequal | Threshold does not match real cost | Optimize expected cost instead |
Beyond F1
F1 treats precision and recall as equally important. Often they are not. Missing a fraud case may cost far more than reviewing a false alarm. You can then pick the threshold in one of these ways:
- Maximize F-beta with
beta > 1to favor recall. - Fix a minimum recall, such as 0.90, and take the highest precision that meets it.
- Assign a cost to each false positive and false negative, then pick the threshold with the lowest total cost on out-of-fold scores.
Exercise
A teammate picks the threshold that maximizes F1 using model.predict_proba(X_train) from a model fitted on X_train, then reports F1 on the test set. Name the flaw and the fix.
Show answer
The training scores are in-sample, so the model is overconfident on them and the chosen threshold may not transfer to new data. Use cross_val_predict on the training set to get out-of-fold scores, choose the threshold from those, then apply it once to the test set.
Exercise
Your application requires at least 90% recall on the rare class. How would you choose the threshold from precision , recall and thresholds?
Show answer
Keep only the thresholds where recall is at least 0.90, then take the one with the highest precision. Compute this from out-of-fold scores, not from the test set.