Sub topic 14
Choosing a threshold for your costs
This chapter assumes you can fit a scikit-learn logistic regression and read a confusion matrix. You should know precision (the share of predicted positives that are correct) and recall (the share of actual positives that are found).
The threshold is a separate decision
Logistic regression outputs a probability. Turning it into a label needs a rule: predict positive when the probability is at least a threshold t. The default t = 0.5 is only a convention. It is the best choice when both kinds of mistake cost the same and the probabilities are well calibrated. Often they don't cost the same.
- A false negative is a positive case you missed, such as an undetected tumor.
- A false positive is a negative case you flagged, such as an unnecessary follow-up test.
Lowering t flags more cases. Recall goes up and precision usually goes down. Raising t does the opposite.
A cost-based rule
Assign a cost to each error. If a false negative costs c_fn and a false positive costs c_fp, the expected cost is lowest at t = c_fp / (c_fp + c_fn). This holds only if the probabilities are calibrated. With c_fn = 10 and c_fp = 1, that gives t ≈ 0.09.
In practice, sweep thresholds and pick the one with the lowest total cost. Do the sweep on out-of-fold predictions from the training data, not on the test set. The test set then gives an honest estimate of the final choice.
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 classification_report
X, y = load_breast_cancer(return_X_y=True)
y = 1 - y # in this dataset 0 is malignant, so make malignant the positive class
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))
oof = cross_val_predict(model, X_train, y_train, cv=5, method="predict_proba")[:, 1]
cost_fn, cost_fp = 10, 1
thresholds = np.linspace(0.05, 0.95, 19)
costs = []
for t in thresholds:
pred = oof >= t
fn = np.sum(~pred & (y_train == 1))
fp = np.sum(pred & (y_train == 0))
costs.append(cost_fn * fn + cost_fp * fp)
best = thresholds[int(np.argmin(costs))]
print("chosen threshold:", best)
model.fit(X_train, y_train)
proba = model.predict_proba(X_test)[:, 1]
print(classification_report(y_test, (proba >= best).astype(int)))The code flips the labels because load_breast_cancer encodes malignant as 0. With the flip, a lower threshold catches more malignant cases.
Other ways to pick
- ROC curve: choose the point where the true positive rate is high enough and the false positive rate is acceptable.
- Precision-recall curve: better when positives are rare.
- Constraint: fix a minimum recall, such as 0.95, and take the highest threshold that meets it.
Re-check the threshold when class frequencies or costs change.
Exercise
A false negative costs 5 and a false positive costs 1. If the probabilities are calibrated, what threshold minimizes expected cost, and is it above or below 0.5?
Show answer
t = cfp / (cfp + c_fn) = 1 / (1 + 5) ≈ 0.17. It is below 0.5, because missing a positive is more expensive, so the model should flag more cases.