Worked Example: Picking a Threshold from Error Costs
Turn the costs of a missed failure and an unneeded inspection into a decision threshold, check that the model is calibrated enough to use it, confirm the threshold with a cost sweep on validation data, see how class reweighting breaks it, and report the cost on the test set once.
Contentsand lesson path
On this page
- The problem
- Step 1: Derive the threshold from the costs
- Step 2: Check that the probabilities can be trusted
- Step 3: Confirm the threshold with a cost sweep
- Step 4: What class reweighting does to the threshold
- Step 5: Fix the threshold, then test once
- Check your understanding
- Apply it
- Review prompt
Lessons of Model Evaluation & Validation
- Metrics That Match the Decision Concept · 25 min
- Worked Example: Picking a Threshold from Error Costs Worked example · 20 min
- Validation Schemes That Mirror Production Concept · 25 min
- Lab: Hunt the Leak Lab · 30 min
- Lab: Honest Tuning and Slice-Based Error Analysis Lab · 30 min
- Check: Would You Trust This Score? Knowledge check · 8 questions
What you will learn
- Select and compute metrics that fit the task and its error costs (precision, recall, F1, ROC-AUC vs PR-AUC, calibration, MAE/RMSE) and choose a decision threshold from those costs.
Prerequisites: Machine Learning Fundamentals
01. The problem
A water company checks its pumps once a week. For each pump, a model predicts the probability that it breaks down before the next check. An engineer can inspect a pump and replace worn parts for £100. A breakdown that nobody saw coming costs £2,000 in emergency repairs and lost supply. Which pumps should get an inspection this week?
The default answer, "inspect when the probability is above 0.5", ignores these numbers. A pump with a 20% risk has an expected breakdown cost of 0.2 × £2,000 = £400, four times the price of an inspection, yet a 0.5 threshold leaves it alone. In this worked example you derive the threshold from the costs, check the conditions under which it is valid, and measure what it saves. The data is simulated with a fixed seed, so your numbers will match.
You need Python 3.12 with scikit-learn 1.9 and pandas. Put every file in one folder and run the scripts from there.
import numpy as np
import pandas as pd
def load(n=40_000, seed=0):
"""Weekly sensor readings for pumps; failed = breaks down before the next check."""
rng = np.random.default_rng(seed)
vibration = rng.gamma(4.0, 1.0, n) # mm/s
temp = rng.normal(60, 8, n) # bearing temperature, °C
hours = rng.uniform(0, 4000, n) # hours since last service
logit = -6.3 + 0.45 * vibration + 0.06 * (temp - 60) + 0.0006 * hours
failed = rng.random(n) < 1 / (1 + np.exp(-logit))
X = pd.DataFrame({"vibration": vibration, "temp": temp, "hours": hours})
return X, failed.astype(int)from sklearn.model_selection import train_test_split
from machines import load
X, y = load()
X_tr, X_rest, y_tr, y_rest = train_test_split(X, y, test_size=0.5, stratify=y,
random_state=0)
X_val, X_te, y_val, y_te = train_test_split(X_rest, y_rest, test_size=0.5,
stratify=y_rest, random_state=0)
if __name__ == "__main__":
print(f"rows: train {len(y_tr)}, validation {len(y_val)}, test {len(y_te)}")
print(f"failure rate: {y.mean():.3f}")python split.pyrows: train 20000, validation 10000, test 10000
failure rate: 0.065The split follows the usual three roles: the model learns from the training rows, you make every choice (including the threshold) on the validation rows, and the test rows are scored once at the end. About 6.5% of pump-weeks end in a breakdown. Because stratify=y is set, each part has the same failure rate, which keeps the comparisons fair.
02. Step 1: Derive the threshold from the costs
Write a cost for each cell of the confusion matrix. Inspecting a pump that would have failed (TP) costs the £100 inspection. Inspecting a healthy pump (FP) also costs £100. Missing a failure (FN) costs £2,000, and leaving a healthy pump alone (TN) costs nothing.
For one pump with a calibrated failure probability p, compare the expected cost of each action. Inspecting costs p × C_TP + (1 − p) × C_FP. Not inspecting costs p × C_FN + (1 − p) × C_TN. Inspect when the first is smaller. Solving for p gives the threshold:
p* = (C_FP − C_TN) / ((C_FP − C_TN) + (C_FN − C_TP))
When correct decisions cost nothing (C_TP = C_TN = 0), this reduces to the common form p* = C_FP / (C_FP + C_FN). Here the inspection is paid even when it catches a failure, which is why the code keeps the general form.
import numpy as np
# Cost in pounds of each outcome for one pump over the next 7 days
COST = {"TP": 100, "FP": 100, "FN": 2000, "TN": 0}
def threshold_from_costs(c=COST):
"""Flag when p*C_TP + (1-p)*C_FP < p*C_FN + (1-p)*C_TN; solve for p."""
return (c["FP"] - c["TN"]) / ((c["FP"] - c["TN"]) + (c["FN"] - c["TP"]))
def cost_per_pump(y, p, t, c=COST):
flag = p >= t
total = (c["TP"] * np.sum(flag & (y == 1)) + c["FP"] * np.sum(flag & (y == 0))
+ c["FN"] * np.sum(~flag & (y == 1)) + c["TN"] * np.sum(~flag & (y == 0)))
return total / len(y)
if __name__ == "__main__":
print(f"threshold from costs: {threshold_from_costs():.4f}")
free_catch = threshold_from_costs(dict(COST, TP=0))
print(f"same, if a caught failure cost nothing: {free_catch:.4f}")python costs.pythreshold from costs: 0.0500
same, if a caught failure cost nothing: 0.0476Inspect when the failure probability is at least 5%. The threshold depends only on the costs. It does not depend on how common failures are, because the probability p already carries that information. If the model is calibrated, a pump scored 0.05 really does fail about 5% of the time, whatever the overall rate. Note also how little the cost of a true positive moves the threshold here (0.0500 against 0.0476): the ratio between a breakdown and an inspection dominates.
03. Step 2: Check that the probabilities can be trusted
The derivation assumed that p is a real probability. Before you use it, fit the model and check its calibration on validation rows. With strategy="quantile", calibration_curve puts the same number of rows in each bin, which keeps every bin populated even though most pumps have a small risk.
from sklearn.calibration import calibration_curve
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from split import X_tr, X_val, y_tr, y_val
model = make_pipeline(StandardScaler(), LogisticRegression())
model.fit(X_tr, y_tr)
p_val = model.predict_proba(X_val)[:, 1]
print(f"validation ROC-AUC: {roc_auc_score(y_val, p_val):.3f}")
frac, mean = calibration_curve(y_val, p_val, n_bins=6, strategy="quantile")
for m, f in zip(mean, frac):
print(f" predicted {m:.3f} observed {f:.3f}")python fit.pyvalidation ROC-AUC: 0.799
predicted 0.006 observed 0.005
predicted 0.014 observed 0.022
predicted 0.024 observed 0.029
predicted 0.041 observed 0.041
predicted 0.073 observed 0.074
predicted 0.221 observed 0.220Predicted and observed rates agree closely in every bin, so a predicted 0.05 can be read as a 5% risk. That is partly luck of the set-up: the simulated failures follow a logistic curve, so logistic regression fits them well. With a real dataset, or a model such as naive Bayes or a boosted tree, check this step carefully and calibrate first if the curve bends away from the diagonal.
04. Step 3: Confirm the threshold with a cost sweep
Theory gives 0.05, but the validation data can confirm it directly: compute the cost per pump at many thresholds and see where it is lowest. This empirical sweep is also your fallback when the probabilities are not calibrated.
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from costs import cost_per_pump, threshold_from_costs
from split import X_tr, X_val, y_tr, y_val
model = make_pipeline(StandardScaler(), LogisticRegression()).fit(X_tr, y_tr)
p_val = model.predict_proba(X_val)[:, 1]
print(f"{'threshold':>9} {'flagged':>8} {'cost/pump':>10}")
for t in [0.01, 0.03, 0.05, 0.08, 0.15, 0.5]:
print(f"{t:9.2f} {np.mean(p_val >= t):8.1%} {cost_per_pump(y_val, p_val, t):10.2f}")
grid = np.round(np.arange(0.005, 0.30, 0.005), 3)
costs = [cost_per_pump(y_val, p_val, t) for t in grid]
best = grid[int(np.argmin(costs))]
print(f"lowest validation cost at threshold {best:.3f}: {min(costs):.2f}")
print(f"theory says {threshold_from_costs():.3f}: "
f"{cost_per_pump(y_val, p_val, threshold_from_costs()):.2f}")python sweep.pythreshold flagged cost/pump
0.01 83.8% 85.64
0.03 51.3% 69.52
0.05 34.8% 66.16
0.08 22.0% 71.64
0.15 9.8% 85.62
0.50 0.9% 118.94
lowest validation cost at threshold 0.055: 65.28
theory says 0.050: 66.16The cost curve is shallow near its minimum: anything between 0.03 and 0.08 costs £65 to £72 per pump, while the default 0.5 costs £118.94 because it flags under 1% of pumps and misses most failures. The lowest validation cost sits at 0.055, close to the theoretical 0.05. Prefer the theoretical value when the model is calibrated: the sweep minimum moves a little with the particular validation rows, and the curve is so flat here that the two thresholds cost almost the same.
05. Step 4: What class reweighting does to the threshold
A common reflex with imbalanced data is class_weight="balanced", which makes each failure count as much in training as about 14 healthy pump-weeks. It can help a model pay attention to the rare class, but it also changes what the model's output means.
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from costs import cost_per_pump, threshold_from_costs
from split import X_tr, X_val, y_tr, y_val
t = threshold_from_costs()
for weight in [None, "balanced"]:
model = make_pipeline(StandardScaler(), LogisticRegression(class_weight=weight))
p_val = model.fit(X_tr, y_tr).predict_proba(X_val)[:, 1]
print(f"class_weight={str(weight):<8} ROC-AUC {roc_auc_score(y_val, p_val):.3f} "
f"mean p {p_val.mean():.3f} cost at {t:.2f}: "
f"{cost_per_pump(y_val, p_val, t):.2f}")
print(f"observed failure rate in validation: {y_val.mean():.3f}")python balanced.pyclass_weight=None ROC-AUC 0.799 mean p 0.063 cost at 0.05: 66.16
class_weight=balanced ROC-AUC 0.798 mean p 0.362 cost at 0.05: 97.54
observed failure rate in validation: 0.065The ranking is as good as before (ROC-AUC 0.798 against 0.799), but the average predicted probability jumps from 0.063, close to the true 6.5%, to 0.362. The model now speaks as if failures were common, so the 0.05 threshold flags far too many pumps and the cost rises by about £31 per pump. If you reweight, the cost-derived threshold no longer applies. Either calibrate the outputs again on validation data, or search the threshold empirically. scikit-learn (1.5 and later) does the second with TunedThresholdClassifierCV, which picks the threshold that maximises a score by cross-validation. Your scorer returns minus the cost, because scikit-learn maximises scores.
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import make_scorer
from sklearn.model_selection import StratifiedKFold, TunedThresholdClassifierCV
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from costs import cost_per_pump
from split import X_tr, X_val, y_tr, y_val
def neg_cost(y, y_pred): # scikit-learn maximises a score, so return minus the cost
return -cost_per_pump(np.asarray(y), np.asarray(y_pred), 0.5)
X_dev, y_dev = pd.concat([X_tr, X_val]), np.concatenate([y_tr, y_val])
base = make_pipeline(StandardScaler(), LogisticRegression(class_weight="balanced"))
tuned = TunedThresholdClassifierCV(
base, scoring=make_scorer(neg_cost),
cv=StratifiedKFold(5, shuffle=True, random_state=0),
).fit(X_dev, y_dev)
print(f"threshold chosen by CV for the balanced model: {tuned.best_threshold_:.3f}")python tuned.pythreshold chosen by CV for the balanced model: 0.469For the reweighted model the cost-minimising cut-off is 0.469, nowhere near 0.05. The scorer receives the 0/1 predictions made at each candidate threshold, so cost_per_pump is called with a cut-off of 0.5 on values that are already 0 or 1. The lesson is not that 0.469 is a better number, only that a threshold belongs to one model and its probability scale.
06. Step 5: Fix the threshold, then test once
All choices are now made: plain logistic regression, threshold 0.05. Refit on training plus validation rows, then score the test set once and compare with the two policies that need no model at all.
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from costs import cost_per_pump, threshold_from_costs
from split import X_te, X_tr, X_val, y_te, y_tr, y_val
# Refit on train + validation, keep the threshold fixed, then score the test set once
X_dev, y_dev = pd.concat([X_tr, X_val]), np.concatenate([y_tr, y_val])
model = make_pipeline(StandardScaler(), LogisticRegression()).fit(X_dev, y_dev)
p_te = model.predict_proba(X_te)[:, 1]
t = threshold_from_costs()
rows = {
"inspect nothing": cost_per_pump(y_te, np.zeros_like(p_te), 0.5),
"inspect every pump": cost_per_pump(y_te, np.ones_like(p_te), 0.5),
"model, threshold 0.5": cost_per_pump(y_te, p_te, 0.5),
f"model, threshold {t:.2f}": cost_per_pump(y_te, p_te, t),
}
for name, cost in rows.items():
print(f"{name:<22} £{cost:6.2f} per pump-week")python final.pyinspect nothing £130.60 per pump-week
inspect every pump £100.00 per pump-week
model, threshold 0.5 £119.66 per pump-week
model, threshold 0.05 £ 59.32 per pump-weekInspecting every pump costs £100 per pump-week and inspecting none costs £130.60. The model with the default threshold saves little (£119.66). With the cost-based threshold it costs £59.32, about 40% less than inspecting everything. The test cost is lower than the validation cost of £66.16, partly because the final model saw more rows and partly because a different set of 10,000 pumps gives a slightly different number. That spread is a reminder to report a cost with an interval, for example from a bootstrap over test rows, rather than as a single exact figure.
07. Check your understanding
08. Apply it
In the practice project, the notebook reports a score but never says what the model is used for. Add a decision layer.
- Agree a cost for each cell of the confusion matrix with the owner of the decision, and write them in the report.
- Check calibration on validation data, derive the threshold from the costs, and confirm it with a cost sweep on the same data.
- Report the test cost at that threshold next to "act on nothing" and "act on everything", with a bootstrap interval.
09. Review prompt
Without looking back, derive the cost-based threshold from the expected cost of acting and of not acting; say which assumption about the probabilities it needs and how you would check it; explain what class_weight="balanced" does to that assumption and two ways to recover; and explain why the threshold is chosen on validation data and scored on the test set only once.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.