Sub topic 10
Choosing an operating threshold
A ROC curve shows every trade-off a scoring model can offer. Deployment needs exactly one of them. The threshold you ship is the operating threshold, and the point on the curve it produces is the operating point. This chapter covers three ways to pick one: Youden's J, minimum expected cost, and a constraint on the false positive rate.
This chapter assumes you can build a ROC curve with roc_curve, that you know TPR and FPR from the confusion matrix, and that you are comfortable with NumPy indexing.
Why AUC does not pick a threshold
AUC summarizes ranking quality over all thresholds. It says nothing about which threshold to use. Two models with the same AUC can have very different operating points. A model with a high AUC can also perform badly at a poorly chosen threshold.
Choosing a threshold is a decision problem, not a measurement problem. It needs information the curve does not contain:
- What a false positive costs.
- What a false negative costs.
- How common positives are in production.
- Any hard limits, such as "reviewers can handle 50 alerts a day".
State the criterion first, then find the point on the curve that satisfies it.
Criterion 1: Youden's J
Youden's J statistic is J = TPR - FPR. Geometrically, it is the vertical distance from a ROC point up to the diagonal. Maximizing J picks the point farthest above the "random guessing" line.
import numpy as np
from sklearn.metrics import roc_curve
y_true = np.array([0, 0, 1, 1])
y_score = np.array([0.1, 0.4, 0.35, 0.8])
fpr, tpr, thresholds = roc_curve(y_true, y_score)
j = tpr - fpr
best = np.argmax(j)
print(thresholds[best], tpr[best], fpr[best])On this data, J is [0, 0.5, 0, 0.5, 0] across the five curve points. Two points tie at 0.5. np.argmax returns the first one, which is threshold 0.8 with TPR 0.5 and FPR 0. The other tied point is threshold 0.35 with TPR 1.0 and FPR 0.5.
Ties like this are common on small samples. J cannot tell these two points apart, so you need another reason to choose between them.
J implicitly assumes three things:
- A false negative and a false positive cost the same.
- Positives and negatives are weighted equally, regardless of how many of each you have.
- Specificity and sensitivity matter equally.
If any of these is false in your application, use a different criterion.
Criterion 2: minimum expected cost
When you can put numbers on the two error types, minimize the total cost directly. At each threshold on the curve:
cost = c_fn * FN + c_fp * FP
You can get FN and FP back from the rates and the class counts:
FN = (1 - TPR) * n_posFP = FPR * n_neg
import numpy as np
from sklearn.metrics import roc_curve
y_true = np.array([0, 0, 1, 1])
y_score = np.array([0.1, 0.4, 0.35, 0.8])
fpr, tpr, thresholds = roc_curve(y_true, y_score)
n_pos = (y_true == 1).sum()
n_neg = (y_true == 0).sum()
def best_threshold(c_fn, c_fp):
cost = c_fn * (1 - tpr) * n_pos + c_fp * fpr * n_neg
i = np.argmin(cost)
return thresholds[i], cost[i]
t, c = best_threshold(c_fn=5, c_fp=1)
print(f"{t:.2f} {c:.1f}") # 0.35 1.0When a missed positive costs five times a false alarm, the best threshold drops to 0.35. The model then catches both positives and accepts one false alarm, for a total cost of 1. Reverse the costs (c_fn=1, c_fp=5) and the best threshold rises to 0.8, also with a total cost of 1.
The geometry of cost
Lines of equal cost on the ROC plane are straight lines with slope:
slope = (c_fp * n_neg) / (c_fn * n_pos)
The best operating point is where the highest line of that slope still touches the curve. Two consequences follow:
- When false negatives are expensive, the slope is small, so the line is flat and touches the curve far up and to the right.
- When positives are rare,
n_neg / n_posis large, so the slope is steep. This pushes the best point toward the lower left, which means a strict threshold.
Only the points on the upper convex hull of the curve can ever be optimal for some cost ratio. A point in a dent of the curve is never the best choice.
A shortcut for calibrated probabilities
If your scores are well-calibrated probabilities, you do not need the curve to find the cost-optimal threshold. Predict positive when:
p >= c_fp / (c_fp + c_fn)
With c_fn=5 and c_fp=1, this gives 1/6, about 0.167. With c_fn=9 and c_fp=1, it gives 0.1. The rule depends on calibration. Raw scores from many models, such as SVM margins or unscaled boosting outputs, are not probabilities. In that case, search over thresholds using the curve as shown above.
Criterion 3: a cap on false positives
Often the constraint comes from operations, not from a cost table. For example: "no more than 1% of legitimate transactions may be flagged." Here you choose the highest TPR that keeps FPR within the cap.
import numpy as np
from sklearn.metrics import roc_curve
y_true = np.array([0, 0, 1, 1])
y_score = np.array([0.1, 0.4, 0.35, 0.8])
fpr, tpr, thresholds = roc_curve(y_true, y_score)
def threshold_at_max_fpr(max_fpr):
eligible = np.where(fpr <= max_fpr)[0]
i = eligible[-1] # tpr never decreases as fpr grows
return thresholds[i], tpr[i], fpr[i]
t, tp, fp = threshold_at_max_fpr(0.2)
print(f"{t:.2f} {tp:.2f} {fp:.2f}") # 0.80 0.50 0.00Because the ROC curve is monotone, the last eligible index has the highest TPR. With a cap of 0.2, the only eligible points have FPR 0, so the threshold is 0.8.
The mirror-image constraint is also common: "catch at least 90% of positives". There you pick the smallest FPR with tpr >= 0.9.
Constraints with small FPR values need a lot of negative examples. With 200 negatives, an FPR of 0.01 means two false positives, so the estimate is very noisy.
Comparing the three criteria
| Criterion | Needs | Strength | Weakness |
|---|---|---|---|
| Youden's J | Nothing extra | Simple, no cost estimates | Assumes equal costs; ties on small data |
| Minimum expected cost | Costs for FN and FP | Matches the real objective | Cost estimates are often guesses |
| FPR cap | An operational limit | Easy to explain and audit | Ignores the cost of missed positives |
Pitfalls
- Tuning on the test set. Pick the threshold on validation data, or with cross-validation. Then report metrics on data that played no part in the choice. A threshold chosen on the same data you report on gives optimistic numbers. Recent scikit-learn versions provide
TunedThresholdClassifierCVto automate this with cross-validation. - The leading
infthreshold.roc_curvebegins with a threshold above every score so that the curve starts at (0, 0). Newer versions returninfthere and older ones returnmax(score) + 1. A criterion that selects this point means "never predict positive". If you see it, your criterion is telling you the model is not useful under those costs. - Thresholds are not portable. A threshold is a number on one model's score scale. If you retrain, recalibrate, or switch models, the old threshold no longer means the same thing. Re-derive it every time.
- Prevalence shifts. TPR and FPR do not change when class balance changes, but the number of false alarms per day does. If production prevalence differs from your validation set, recompute
n_posandn_negin the cost formula with production proportions, not validation counts. - Flat regions. Many thresholds can give nearly the same cost. Prefer a threshold in the middle of a stable region over the single sharpest minimum, since small data changes can move the sharp minimum.
- Conversion to predictions.
roc_curvetreats a thresholdtas "predict positive when score>= t". Use the same rule when you deploy:y_pred = (y_score >= t).astype(int).
Putting it together
A sound routine looks like this:
- Split the data into training, validation, and test sets.
- Fit the model on the training set and score the validation set.
- Write down the criterion before looking at the curve.
- Apply the criterion to
roc_curveoutput to get one threshold. - Score the test set once and report TPR, FPR, and cost at that threshold.
- Document the threshold, the criterion, and the cost assumptions so that someone can revisit them later.
Exercise
Using the four-example data set (y_true = [0, 0, 1, 1], y_score = [0.1, 0.4, 0.35, 0.8]), a missed positive costs 1 and a false alarm costs 5. Which threshold minimizes the total cost, and what is that cost? Then, for a calibrated model with c_fn=9 and c_fp=1, what probability cutoff minimizes expected cost?
Show answer
At threshold 0.8, the model flags only the top-scored example, which is a true positive. This gives FN = 1 (cost 1) and FP = 0 (cost 0), so the total cost is 1. The alternatives are worse: threshold 0.4 gives 1 + 5 = 6, threshold 0.35 gives 0 + 5 = 5, and threshold 0.1 gives 10. For the calibrated model, the cutoff is cfp / (cfp + c_fn) = 1 / 10 = 0.1.