Sub topic 16
Using calibrated probabilities for thresholds and decisions
This chapter assumes you can already calibrate a model with CalibratedClassifierCV and read a reliability diagram. It covers what calibration lets you do once the probabilities are trustworthy: choose thresholds from costs, estimate counts, adjust for a changed base rate, and let the model abstain.
Why calibration matters for decisions
A classifier's default predict uses a 0.5 cutoff. That cutoff is only sensible when a false positive and a false negative cost the same and the class balance is similar in training and in production. Most real problems break one or both assumptions.
If probabilities are calibrated, a score of 0.2 means about a 20% chance of the positive class. You can then turn the score into an action with arithmetic, without trial and error. If the probabilities are not calibrated, the same arithmetic gives wrong answers, because the inputs are wrong.
Ranking tasks are different. If you only need the top 100 items by risk, any monotonic transform of the score gives the same top 100. Calibration is needed when the numeric value of the probability enters a decision.
The cost-based threshold
Suppose a false positive costs c_fp, a false negative costs c_fn, and correct predictions cost nothing. For an example with true positive probability p:
- Predicting positive has expected cost
(1 - p) * c_fp. - Predicting negative has expected cost
p * c_fn.
Predicting positive is better when (1 - p) * c_fp < p * c_fn. Solving for p gives the threshold:
t* = c_fp / (c_fp + c_fn)
If missing a fraud case costs 9 times as much as a false alarm, t* = 1 / (1 + 9) = 0.1. The model should flag every transaction whose fraud probability is above 10%, even though most of those flags will be false alarms. With equal costs the formula gives 0.5.
Checking the rule on data
The script below trains a naive Bayes model on imbalanced data, once raw and once calibrated. It evaluates total cost on a test set at two thresholds: 0.5 and the cost-derived 0.1.
import numpy as np
from sklearn.calibration import CalibratedClassifierCV
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
C_FP, C_FN = 1.0, 9.0
X, y = make_classification(
n_samples=30000, n_features=20, n_informative=5, n_redundant=10,
weights=[0.8, 0.2], random_state=0,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.5, random_state=0, stratify=y
)
def total_cost(y_true, p, threshold):
pred = (p >= threshold).astype(int)
fp = np.sum((pred == 1) & (y_true == 0))
fn = np.sum((pred == 0) & (y_true == 1))
return C_FP * fp + C_FN * fn
raw = GaussianNB().fit(X_train, y_train)
cal = CalibratedClassifierCV(GaussianNB(), method="isotonic", cv=5)
cal.fit(X_train, y_train)
t_star = C_FP / (C_FP + C_FN)
for name, model in (("raw", raw), ("calibrated", cal)):
p = model.predict_proba(X_test)[:, 1]
print(
f"{name:<10} cost at 0.50: {total_cost(y_test, p, 0.5):7.0f} "
f"cost at {t_star:.2f}: {total_cost(y_test, p, t_star):7.0f}"
)Run it and compare the columns. The calibrated model's cost at the theoretical threshold should be at or near the lowest cost you can find by sweeping thresholds. For the raw model, the theoretical threshold is less reliable, because its scores are not probabilities and often sit too close to 0 or 1.
Choosing a threshold empirically
The formula assumes the costs are known and the probabilities are exact. In practice, you can also sweep thresholds on a validation set and pick the one with the lowest cost. Keep three roles apart:
- Training data fits the base model.
- Calibration data fits the calibrator.
CalibratedClassifierCVhandles this internally through its cross-validation folds. - Validation data picks the threshold. Test data reports the final cost.
Choosing the threshold on the test set makes the reported cost optimistic. The same leakage rule that applies to calibrators applies to thresholds.
For a calibrated model, the swept threshold should land near t*. A large gap is a diagnostic. It suggests residual miscalibration, wrong cost estimates, or a validation set too small to give a stable optimum.
Other thresholds that follow from calibration
F1 score
Maximizing F1 does not use the 0.5 cutoff either. For calibrated probabilities, the F1-optimal threshold equals half of the best achievable F1. If the best F1 is 0.6, the best threshold is about 0.3. Treat this as a useful guide, since it holds exactly only for the true conditional probabilities.
Capacity limits
If a review team can handle 50 cases a day, you do not need a probability threshold. Take the 50 highest scores. Calibration still helps here because it lets you report the expected precision of that queue: the mean predicted probability of the selected cases.
Expected counts
For calibrated probabilities, the sum of p over a group estimates the number of positives in it. This is useful for forecasting workload or revenue. It is also a quick sanity check. If the sum of predicted probabilities on a labelled batch is far from the actual positive count, the model is miscalibrated on average, even if a reliability diagram looks acceptable.
p_test = cal.predict_proba(X_test)[:, 1]
print("expected positives:", p_test.sum().round(1))
print("actual positives :", y_test.sum())Adjusting for a different base rate
Calibration is relative to the class balance of the data the calibrator saw. If you train on a dataset with 20% positives and deploy where only 2% of cases are positive, the probabilities will be too high. If you know the new prior, you can correct for the shift without retraining. Convert the probability to odds, multiply by the ratio of the new prior odds to the old prior odds, and convert back.
import numpy as np
def adjust_for_prior(p, train_prior, new_prior):
p = np.clip(np.asarray(p, dtype=float), 1e-12, 1 - 1e-12)
odds = p / (1 - p)
ratio = (new_prior / (1 - new_prior)) / (train_prior / (1 - train_prior))
new_odds = odds * ratio
return new_odds / (1 + new_odds)
print(adjust_for_prior([0.5, 0.2], train_prior=0.2, new_prior=0.02))A probability of 0.5 under a 20% prior becomes about 0.06 under a 2% prior. This correction assumes only the class balance changed and that the feature distribution within each class stayed the same (label shift). If the features themselves drifted, this fix does not apply, and you need to recalibrate on recent labelled data. Chapter 15 covers monitoring for this.
Abstaining with two thresholds
You can use two thresholds instead of one. Act automatically above t_high, do nothing below t_low, and send the middle band to a human or a slower model. The band's width is a trade-off between automation rate and error rate. Because the probabilities are calibrated, you can state the expected error of each region directly. In the "act" region, the expected error rate is 1 - mean(p). In the "do nothing" region, it is mean(p).
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Using 0.5 with unequal costs | Systematically too many false negatives or false positives | Derive the threshold from costs |
| Tuning the threshold on test data | Optimistic cost estimate | Use a separate validation set |
| Applying `t*` to uncalibrated scores | Threshold does not match the actual risk | Calibrate first, then check the reliability diagram |
| Ignoring a base-rate change | Probabilities too high or too low in production | Adjust the prior or recalibrate on recent data |
| Treating zero-cost correct outcomes as given | Wrong `t*` if true positives carry value or cost | Include all four outcome costs in the derivation |
The last row deserves a note. With a full cost matrix, the threshold is (c_fp - c_tn) / ((c_fp - c_tn) + (c_fn - c_tp)). The simple formula is the special case where correct outcomes cost zero.
Exercise
A loan model is calibrated. Approving a loan that defaults (a false positive for "good borrower") costs 400. Rejecting a loan that would have repaid costs 40 in lost profit. Correct decisions cost nothing. Treating "will repay" as the positive class, what is the cost-optimal threshold on the predicted repayment probability, and what does it mean for a borrower with p = 0.85?
Show answer
Here cfp = 400 (approve a defaulter) and cfn = 40 (reject a good borrower). The threshold is t = 400 / (400 + 40) ≈ 0.91. Approve only when the repayment probability is at least about 0.91. A borrower with p = 0.85 is rejected, because the expected cost of approving is 0.15 400 = 60, which exceeds the expected cost of rejecting, 0.85 * 40 = 34.