Sub topic 14
Choosing a threshold for your costs
This chapter assumes you can fit a scikit-learn logistic regression, read a confusion matrix, and compute precision and recall. The previous chapters covered the sigmoid, the 0.5 default, and the metrics. Here you will see why 0.5 is rarely the right cutoff and how to pick a better one.
The threshold is a decision, not a model parameter
Logistic regression outputs a probability p. Turning p into a label needs a rule: predict positive when p >= t. The fitted weights never learn t. scikit-learn's predict hardcodes t = 0.5, which is optimal only when the two kinds of mistake cost the same and the probabilities are accurate.
Changing t does not change the model. It moves the operating point along the precision-recall trade-off. A lower t produces more positive predictions, so recall rises and precision usually falls. A higher t does the opposite.
Start from the costs
Every classifier makes two kinds of error. Write down what each costs before you look at any curve.
| Row | Actual negative | Actual positive |
|---|---|---|
| Predicted negative | 0 | C_FN (missed case) |
| Predicted positive | C_FP (false alarm) | 0 |
Suppose the model says the probability of a positive is p. Predicting positive has expected cost (1 - p) * C_FP. Predicting negative has expected cost p * C_FN. Predict positive when the first is smaller:
p * C_FN > (1 - p) * C_FP, which rearranges to p > C_FP / (C_FP + C_FN).
So the cost-optimal threshold is t* = C_FP / (C_FP + C_FN). If a missed case costs 10 times a false alarm, then t* = 1 / 11, about 0.09. Equal costs give t* = 0.5.
Choose the threshold on data the model has not memorized
Searching for a threshold is a form of fitting. If you search on the test set, your reported results are optimistic. Instead, produce out-of-fold probabilities on the training set with cross-validation, choose t there, and touch the test set once at the end.
The example below uses the breast cancer dataset. In scikit-learn's copy, label 0 means malignant, so we flip the labels to make malignant the positive class. We assume a missed malignancy costs 10 times a false alarm.
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, cross_val_predict
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix
COST_FN = 10.0
COST_FP = 1.0
X, y = load_breast_cancer(return_X_y=True)
y = 1 - y # 1 = malignant, the class we must not miss
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=0
)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
# Out-of-fold probabilities: each row is scored by a model that never saw it.
oof = cross_val_predict(model, X_train, y_train, cv=5, method="predict_proba")[:, 1]
def total_cost(y_true, proba, t):
pred = proba >= t
fn = np.sum(~pred & (y_true == 1))
fp = np.sum(pred & (y_true == 0))
return COST_FN * fn + COST_FP * fp
thresholds = np.linspace(0.01, 0.99, 99)
costs = [total_cost(y_train, oof, t) for t in thresholds]
best_t = thresholds[int(np.argmin(costs))]
print("theory:", COST_FP / (COST_FP + COST_FN), "empirical:", best_t)
model.fit(X_train, y_train)
test_proba = model.predict_proba(X_test)[:, 1]
for t in (0.5, best_t):
print("threshold", round(float(t), 2))
print(confusion_matrix(y_test, test_proba >= t))
print("cost:", total_cost(y_test, test_proba, t))Expect the empirical threshold to land near the theoretical value but not exactly on it. The cost curve is flat and noisy near its minimum because only a few examples change sides as t moves a little. Compare the two confusion matrices. Lowering t should convert false negatives into true positives and add some false positives. Whether the trade pays off depends on your costs, which is the point.
When costs are unknown: use curves
Sometimes nobody can state C_FN and C_FP. Then you choose from a constraint instead, such as "recall must be at least 95%". precision_recall_curve gives precision and recall at every candidate threshold:
from sklearn.metrics import precision_recall_curve
precision, recall, thr = precision_recall_curve(y_train, oof)
# precision and recall have one more entry than thr, so drop the last one.
ok = recall[:-1] >= 0.95
t_for_recall = thr[ok].max() # highest threshold that still reaches 95% recall
print(t_for_recall, precision[:-1][ok].max())Taking the highest threshold that satisfies the recall floor gives the best precision under that constraint. In a precision-recall plot, each threshold is one point on the curve. In a ROC plot, each threshold is one point as well, but ROC hides the effect of class prevalence. Under heavy imbalance, a small false positive rate can still mean many false alarms per true positive, so precision-recall is the more honest view.
Common errors
- Tuning on the test set. The reported cost looks better than it will be in production. Use out-of-fold or validation probabilities.
- Mixing up the class direction.
predict_proba(X)[:, 1]is the probability ofclasses_[1]. Check that column corresponds to your positive class, as the label flip above shows. - Reusing a threshold after changing the model. A new regularization strength, new features, or
class_weight="balanced"changes the probability scale. Re-derive the threshold after any such change. - Reusing a threshold after the base rate shifts. If the positive rate in production differs from training, the probabilities are no longer calibrated for it, and the old
tis wrong. - Optimizing F1 when costs are asymmetric. F1 weights precision and recall equally, which matches the cost ratio only by accident. Use the cost function, or an F-beta score with
betachosen to reflect the ratio. - Trusting a threshold from a few positives. With very few positive examples, the cost curve is jagged. Prefer a simple threshold from theory, and report uncertainty by repeating the cross-validation with different seeds.
Exercises
Exercise
A fraud team estimates that a missed fraud costs 50 and a false alarm (a manual review) costs 2. If the model's probabilities are calibrated, what threshold minimizes expected cost, and is it above or below 0.5?
Show answer
t* = CFP / (CFP + C_FN) = 2 / (2 + 50) = 2/52, about 0.038. It is far below 0.5, because missing fraud is much more expensive than reviewing a legitimate transaction.
Exercise
You choose a threshold by scanning the test set for the lowest cost, then report that cost as your expected production cost. What is wrong, and what should you do instead?
Show answer
The threshold was fit to the test set, so the reported cost is optimistically biased. Choose the threshold on out-of-fold training probabilities or a separate validation set, then evaluate on the test set once with that fixed threshold.