Metrics That Match the Decision
Build precision, recall and F1 from a confusion matrix, see why ROC-AUC stays flat while PR-AUC collapses as positives get rarer, check whether predicted probabilities can be trusted with a calibration curve, and read MAE and RMSE together to spot rare large errors.
Contentsand lesson path
On this page
- Why it matters
- From a confusion matrix to precision, recall and F1
- ROC-AUC and PR-AUC when positives are rare
- Can you trust the probability? Calibration
- Regression: MAE and RMSE together
- 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. Why it matters
A model is only useful because someone acts on its output: an analyst opens a case, a lender declines a loan, a courier gets a delivery estimate. A metric is the number you use to decide whether the model is good enough for that action. If the metric does not reflect what the action costs, a model can win on paper and lose in production.
A fraud model scores 99% accuracy, and the team celebrates. But only 1% of payments are fraud, so a model that says "not fraud" every time also scores 99%. The fraud team cares about two other questions: of the payments we flag, how many are really fraud? And of all the fraud, how much do we catch?
This lesson builds the metrics that answer such questions. You will compute them on small examples, watch how class imbalance changes them, and learn when a predicted probability can be read as a real probability. The next lesson uses these ideas to pick a decision threshold from the costs of each kind of error.
You need: Python 3.12 with scikit-learn 1.9 (python -m pip install scikit-learn).
02. From a confusion matrix to precision, recall and F1
For a yes/no decision, every prediction falls into one of four cells. A true positive (TP) is a case the model flagged that really was positive. A false positive (FP) is a false alarm. A false negative (FN) is a positive case the model missed. A true negative (TN) is a negative case correctly left alone. The table of these four counts is the confusion matrix, and almost every classification metric is a ratio of its cells.
Precision is TP / (TP + FP): of the cases we flagged, the share that were right. It is what the person who handles the flags experiences. Recall (also called sensitivity or true positive rate) is TP / (TP + FN): of all the real positives, the share we caught. F1 is the harmonic mean of the two, 2 × precision × recall / (precision + recall). The harmonic mean is pulled towards the smaller value, so F1 is only high when both are high. Notice that none of the three uses TN.
from sklearn.metrics import confusion_matrix, f1_score, precision_score, recall_score
# 12 loan applications: 1 = the applicant later defaulted
y_true = [1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0]
y_pred = [1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0]
tn, fp, fn, tp = confusion_matrix(y_true, y_pred).ravel()
print(f"TP={tp} FP={fp} FN={fn} TN={tn}")
print(f"precision = {tp}/({tp}+{fp}) = {precision_score(y_true, y_pred):.3f}")
print(f"recall = {tp}/({tp}+{fn}) = {recall_score(y_true, y_pred):.3f}")
print(f"F1 = {f1_score(y_true, y_pred):.3f}")
print(f"accuracy = {(tp + tn) / len(y_true):.3f}")python confusion.pyTP=3 FP=2 FN=1 TN=6
precision = 3/(3+2) = 0.600
recall = 3/(3+1) = 0.750
F1 = 0.667
accuracy = 0.750scikit-learn orders the flattened matrix as TN, FP, FN, TP, which is why the code unpacks it in that order. Of the five applicants the model flagged, three defaulted (precision 0.6); of the four who defaulted, it caught three (recall 0.75). If a flag means a human reviews the loan, low precision wastes reviewer time. If a missed default costs the lender far more than a review, recall matters more. F1 weighs the two equally and rarely matches real costs, so treat it as a summary, not the goal.
03. ROC-AUC and PR-AUC when positives are rare
Most classifiers output a score, and you turn it into a decision by choosing a threshold. Ranking metrics summarise the model over every possible threshold at once.
- The ROC curve plots recall (true positive rate) against the false positive rate, FP / (FP + TN), as the threshold moves. ROC-AUC is the area under it: the probability that a randomly chosen positive gets a higher score than a randomly chosen negative. A random model scores 0.5.
- The precision-recall (PR) curve plots precision against recall. Its area is usually estimated with average precision (
average_precision_scorein scikit-learn), often called PR-AUC. A random model scores about the share of positives, so 0.01 when 1% of cases are positive.
The script below keeps one model fixed: 200 frauds whose scores are centred at 2.0 and a pool of normal payments centred at 0.0. It then adds more and more normal payments, as happens when fraud gets rarer, and measures both areas plus the precision among the 200 highest-scored payments, which is what a team that reviews 200 cases a day would see.
import numpy as np
from sklearn.metrics import average_precision_score, roc_auc_score
rng = np.random.default_rng(0)
# Scores of one fixed model: frauds score higher on average than normal payments
fraud = rng.normal(2.0, 1.0, size=200)
normal_pool = rng.normal(0.0, 1.0, size=200_000)
print(f"{'normal per fraud':>16} {'ROC-AUC':>8} {'PR-AUC':>7} {'precision@200':>14}")
for ratio in [1, 10, 100, 1000]:
normal = normal_pool[: 200 * ratio]
s = np.concatenate([fraud, normal])
y = np.concatenate([np.ones(200), np.zeros(normal.size)])
top = np.argsort(-s)[:200] # the 200 payments the analysts can review
roc, pr = roc_auc_score(y, s), average_precision_score(y, s)
print(f"{ratio:>16} {roc:8.3f} {pr:7.3f} {y[top].mean():14.3f}")python rare.pynormal per fraud ROC-AUC PR-AUC precision@200
1 0.929 0.924 0.850
10 0.927 0.679 0.615
100 0.925 0.290 0.320
1000 0.925 0.051 0.135ROC-AUC barely moves, from 0.929 to 0.925, while PR-AUC falls from 0.924 to 0.051 and the review queue goes from 85% fraud to 13.5% fraud. The reason is in the definitions. Recall is computed only among frauds, and the false positive rate only among normal payments, so adding normal payments that look like the old ones leaves both rates, and the ROC curve, unchanged. Precision mixes the two classes: with 1,000 normal payments per fraud, even a small false positive rate produces many false alarms per real fraud.
So when positives are rare and people act on the top of the ranking, PR-AUC, or precision at the number of cases you can actually handle, describes their experience far better than ROC-AUC. ROC-AUC is still useful when both classes matter equally, or for comparing models on data with the same class balance. Two practical notes: report the share of positives next to a PR-AUC, because its baseline depends on it, and compare PR-AUC values only on data with the same class balance.
04. Can you trust the probability? Calibration
A model is calibrated when its probabilities match reality: among all cases it scores 0.3, about 30% turn out positive. Ranking metrics ignore this. A model can rank perfectly and still say 0.9 for cases that are positive only half the time. Calibration matters whenever you use the number itself, for example to compute an expected cost, to set a price, or to compare a score with a fixed policy threshold.
A calibration curve (or reliability diagram) groups the predictions into bins, then compares the average predicted probability in each bin with the observed share of positives. The Brier score is the mean squared difference between the predicted probability and the 0/1 outcome; lower is better. It mixes calibration with how well the model separates the classes, so read it together with the curve. Naive Bayes is known for over-confident probabilities, because it treats correlated features as independent evidence, so it makes a good test case.
from sklearn.calibration import CalibratedClassifierCV, calibration_curve
from sklearn.datasets import make_classification
from sklearn.metrics import brier_score_loss, roc_auc_score
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
X, y = make_classification(n_samples=20_000, n_features=20, n_informative=5,
n_redundant=10, random_state=1)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.5, random_state=1)
models = {
"naive Bayes": GaussianNB(),
"naive Bayes + isotonic": CalibratedClassifierCV(
GaussianNB(), method="isotonic", cv=5
),
}
for name, model in models.items():
p = model.fit(X_tr, y_tr).predict_proba(X_te)[:, 1]
frac_pos, mean_pred = calibration_curve(y_te, p, n_bins=5)
auc, brier = roc_auc_score(y_te, p), brier_score_loss(y_te, p)
print(f"{name:<23} ROC-AUC {auc:.3f} Brier {brier:.3f}")
pairs = " ".join(f"{m:.2f}->{f:.2f}" for m, f in zip(mean_pred, frac_pos))
print(f" predicted -> observed: {pairs}")python calibration.pynaive Bayes ROC-AUC 0.879 Brier 0.153
predicted -> observed: 0.04->0.10 0.30->0.27 0.50->0.38 0.71->0.52 0.94->0.83
naive Bayes + isotonic ROC-AUC 0.879 Brier 0.140
predicted -> observed: 0.08->0.09 0.31->0.29 0.49->0.49 0.72->0.73 0.90->0.90Raw naive Bayes is over-confident at the top: cases it scores 0.94 are positive 83% of the time, and its 0.71 bin is closer to a coin flip. CalibratedClassifierCV with method="isotonic" fits a monotonic mapping from raw scores to observed rates using internal cross-validation, so the calibrated bins line up (0.72 becomes 0.73, 0.90 stays 0.90). With the default ensemble="auto", which means True here, it averages five such calibrated copies, one per fold, so the order is kept almost exactly; isotonic steps can also create ties that move ROC-AUC in the fourth decimal. The ROC-AUC therefore still reads 0.879: calibration fixes the meaning of the numbers, not the ranking.
Isotonic calibration needs plenty of data; with a few hundred rows, method="sigmoid" (a fitted logistic curve) is safer. Check it on unseen data after each retraining.
05. Regression: MAE and RMSE together
For a numeric target, the error of one prediction is prediction minus truth. MAE (mean absolute error) averages the absolute errors, so it is in the same unit as the target and treats every unit of error the same. RMSE (root mean squared error) squares the errors, averages them and takes the square root. It is also in the target unit, but squaring makes large errors count far more than small ones. RMSE is never smaller than MAE, and the gap tells you about the shape of the errors.
import numpy as np
from sklearn.metrics import mean_absolute_error, root_mean_squared_error
# Delivery-time errors in minutes for two route planners on the same 10 orders
y_true = np.array([30, 42, 25, 38, 50, 33, 29, 45, 40, 36])
steady = y_true + np.array([4, -5, 3, -4, 5, -3, 4, -5, 3, -4])
spiky = y_true + np.array([0, 1, -1, 0, 1, 0, -1, 0, 1, 38])
for name, y_pred in [("steady", steady), ("spiky", spiky)]:
mae = mean_absolute_error(y_true, y_pred)
rmse = root_mean_squared_error(y_true, y_pred)
print(f"{name:<6} MAE {mae:5.1f} min RMSE {rmse:5.1f} min ratio {rmse / mae:.2f}")python regression_errors.pysteady MAE 4.0 min RMSE 4.1 min ratio 1.02
spiky MAE 4.3 min RMSE 12.0 min ratio 2.80Both planners have a similar MAE, but the spiky one is nearly perfect on nine orders and 38 minutes late on the tenth. Its RMSE is almost three times its MAE, while the steady planner, with errors of 3 to 5 minutes everywhere, has RMSE close to MAE. Choose by the decision: if one very late delivery loses a customer, RMSE (or the share of errors above a limit) reflects that risk; if every minute of waiting costs about the same, MAE is the honest summary. Report both, plus a high percentile of the absolute error, and read the largest errors.
06. Check your understanding
07. Apply it
The practice project for this skill starts from a notebook that reports a single headline score. Before you hunt for leaks, decide which metric the decision needs.
- Write down the action taken on a positive prediction, how many cases can be handled per day, and the share of positives in the data.
- Report ROC-AUC, PR-AUC and precision and recall at that daily capacity, with the share of positives next to them.
- Plot a calibration curve on held-out data with
CalibratedClassifierCVorcalibration_curve, and write one sentence on whether the probabilities can be used as numbers.
08. Review prompt
Without looking back, write the formulas for precision, recall and F1 from the four cells of a confusion matrix; explain in two sentences why ROC-AUC can look healthy when positives are very rare while PR-AUC does not; describe what a calibration curve compares and why calibration does not change ROC-AUC; and say what a large gap between RMSE and MAE tells you about the errors.
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.