Shelves / AI and ML Foundations
AI·149
ML Evaluation
How to know whether a model is any good, and good for what: the confusion matrix and the four outcomes, accuracy and why it lies on imbalanced data, precision, recall, F1 and Fβ, threshold selection from business costs, ROC curves and AUC, precision-recall curves and average precision, multi-class averaging (macro, micro, weighted), log loss, Brier score and calibration with reliability diagrams and Platt/isotonic/temperature scaling, regression metrics (MAE, MSE, RMSE, MAPE, R², quantile loss), ranking metrics (precision@k, recall@k, MRR, MAP, NDCG), baselines, slice-based error analysis, offline vs online evaluation, and metric implementations from scratch checked against scikit-learn.
Start here: is the model any good, and good for what?
A single number like "98.9% accurate" can hide a useless model. Evaluation means choosing metrics that match what the model is for, setting decision thresholds deliberately, checking that probabilities mean what they say, and making sure the test itself isn't cheating.
Accuracy lies on imbalanced data
10,000 test orders, 113 of them fraud:
a "model" that always says "not fraud": accuracy 98.87%, catches 0 frauds
That's why imbalanced problems use the confusion matrix (true positives, false positives, false negatives, true negatives) and metrics built from it: precision (of the orders we flagged, how many were fraud?) and recall (of the frauds, how many did we flag?).
The threshold is a business decision
A random forest outputs a fraud probability for each order; flagging happens above a chosen threshold:
threshold 0.50: accuracy 98.89% precision 100.0% recall 1.8% flags 2, misses 111
threshold 0.30: accuracy 98.88% precision 55.6% recall 4.4% flags 9
threshold 0.10: accuracy 97.38% precision 18.3% recall 38.1% flags 235 (43 real)
threshold 0.05: accuracy 93.97% precision 10.2% recall 55.8% flags 616 (63 real)
Lowering the threshold caught more fraud and flagged many more honest orders; accuracy fell even as the model became more useful for catching fraud. The right threshold depends on costs: if reviewing a flag costs ₹20 and a missed fraud costs ₹2,000, catching 43 frauds for 235 reviews is a good deal. Threshold-free summaries help compare models: ROC-AUC 0.863 sounds strong, while PR-AUC 0.183 shows how hard the rare class really is; for rare positives, PR-AUC is the more honest one.
Do the probabilities mean anything?
Among the orders each model scored highest (top fifth by predicted probability):
logistic regression: predicted 4.6% fraud on average, observed 4.2% (Brier score 0.0103)
random forest: predicted 5.2%, observed 4.7% (Brier score 0.0101)
A model is calibrated when "5% risk" really means about 5 in 100. Both were close here; when they aren't (boosted trees and neural networks often aren't), calibration methods (Platt scaling, isotonic regression) fix the probabilities without changing the ranking. Calibration matters whenever probabilities feed decisions, prices or other models.
When the test cheats: leakage
clean features, 5-fold CV: 68.7%
plus a feature only known after the outcome (refund issued): 96.4%
near-duplicate rows on both sides of the split: 94.8% (82.0% without duplicates)
Leakage is information in training or testing that won't exist at prediction time. A post-outcome feature made a mediocre model look brilliant; near-duplicate records let the model "recognise" test rows it had already seen. Both would collapse in production. Leakage is the most common reason a model that looked great fails on real data.
How deep to go in ML evaluation
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Read a confusion matrix and explain accuracy, precision, recall and F1 |
| L2 | Choose metrics and thresholds for a problem and report them with error bars |
| L3 | Explain ROC/PR curves, calibration, ranking metrics and regression metrics and when each misleads |
| L4 | Find leakage, contamination, slice failures and evaluation bugs in someone else's results |
| L5 | Design an evaluation protocol: splits by time/group, offline metrics tied to business outcomes, online tests |
| L6 | Own evaluation standards, fairness audits and model governance across an organisation |
Why evaluation is the hard part
A model's training loss says little about whether it solves the problem. Evaluation answers: how good is it, on what data, by which measure, compared to what, and with what uncertainty? The metric must match the decision the model supports: a fraud model that catches 99% of fraud but blocks 10% of good customers may be unusable; a search ranker with great accuracy on "is this relevant?" may still put the best result on page two.
Principles:
- Choose metrics before training, from the product goal and the cost of each error type.
- Compare against baselines: predict the majority class, the mean, yesterday's value, a simple rule, the current production system.
- Report uncertainty (chapter 147's confidence intervals and paired tests).
- Evaluate on data that looks like production, sliced by the segments that matter.
Classification: the confusion matrix
For a binary classifier with a positive class (fraud, disease, spam):
Threshold metrics
| Metric | Formula | Question it answers |
|---|---|---|
| Accuracy | (TP + TN) / all | Fraction correct |
| Precision (positive predictive value) | TP / (TP + FP) | When it says positive, how often is it right? |
| Recall (sensitivity, true positive rate) | TP / (TP + FN) | Of actual positives, how many did it catch? |
| Specificity (true negative rate) | TN / (TN + FP) | Of actual negatives, how many did it leave alone? |
| False positive rate | FP / (FP + TN) = 1 − specificity | How often are negatives flagged? |
| F1 | 2PR / (P + R) | Harmonic mean of precision and recall |
| Fβ | (1 + β²)PR / (β²P + R) | β > 1 weighs recall more (screening); β < 1 weighs precision |
| Matthews correlation (MCC) | (TP·TN − FP·FN) / √(…) | Balanced single number even with imbalance, −1 to 1 |
| Balanced accuracy | (recall + specificity) / 2 | Accuracy that isn't fooled by imbalance |
From the matrix above: accuracy 0.94, precision 0.667, recall 0.80, F1 0.727, specificity 0.956.
Why accuracy lies
With 1% fraud, a model that always predicts "not fraud" scores 99% accuracy and catches nothing. On imbalanced problems, report precision, recall, F1, PR-AUC or MCC, and always compare with the majority-class baseline.
Precision vs recall trade-off and thresholds
Most classifiers output a score or probability; the threshold converts it to a decision. Raising the threshold → fewer positives → higher precision, lower recall; lowering it does the opposite.
- Spam filter: false positives (losing a real email) are costly → favour precision.
- Cancer screening: false negatives are dangerous → favour recall; follow-up tests handle false positives.
- Fraud: balance investigation cost (FP) against loss (FN).
Choose the threshold on validation data by minimising expected cost: cost = c_FP·FP + c_FN·FN, or by meeting a constraint ("recall ≥ 95%, maximise precision").
import numpy as np
from sklearn.metrics import (precision_score, recall_score, f1_score, roc_auc_score,
average_precision_score, log_loss, brier_score_loss)
def confusion(y, yhat):
tp = np.sum((y == 1) & (yhat == 1)); fp = np.sum((y == 0) & (yhat == 1))
fn = np.sum((y == 1) & (yhat == 0)); tn = np.sum((y == 0) & (yhat == 0))
return tp, fp, fn, tn
def prf(y, yhat):
tp, fp, fn, tn = confusion(y, yhat)
p = tp / (tp + fp) if tp + fp else 0.0
r = tp / (tp + fn) if tp + fn else 0.0
f = 2 * p * r / (p + r) if p + r else 0.0
return p, r, f
rng = np.random.default_rng(0)
y = (rng.random(5000) < 0.05).astype(int) # 5% positives
score = np.clip(0.25 * y + rng.normal(0.3, 0.15, 5000), 0, 1) # imperfect scores
yhat = (score >= 0.5).astype(int)
prf(y, yhat) # matches sklearn:
precision_score(y, yhat), recall_score(y, yhat), f1_score(y, yhat)
# Choose the threshold that minimises expected cost on validation data
c_fp, c_fn = 1.0, 20.0 # a miss costs 20× a false alarm
ths = np.linspace(0, 1, 101)
costs = [c_fp * confusion(y, (score >= t).astype(int))[1] + c_fn * confusion(y, (score >= t).astype(int))[2]
for t in ths]
ths[int(np.argmin(costs))] # ≈ 0.46 here: misses are expensive, so the threshold moves down
Ranking-quality metrics: ROC and PR curves
Threshold-free metrics evaluate the score ordering across all thresholds.
ROC curve and AUC
The ROC curve plots true positive rate (recall) against false positive rate as the threshold sweeps from high to low. ROC-AUC (area under it) equals the probability that a random positive scores higher than a random negative. 0.5 = random, 1.0 = perfect ranking.
Precision-recall curve and average precision
The PR curve plots precision against recall. Its area (PR-AUC, usually computed as average precision) is more informative when positives are rare: ROC's FPR denominator is dominated by the huge number of negatives, so ROC-AUC can look excellent while precision at useful recall is poor. The PR baseline is the positive rate (e.g. 0.05), not 0.5.
def roc_auc_rank(y, s):
"""AUC = P(score of random positive > score of random negative), via ranks (Mann–Whitney U)."""
order = np.argsort(s); ranks = np.empty(len(s)); ranks[order] = np.arange(1, len(s) + 1)
n_pos, n_neg = y.sum(), len(y) - y.sum()
return (ranks[y == 1].sum() - n_pos * (n_pos + 1) / 2) / (n_pos * n_neg)
def average_precision(y, s):
idx = np.argsort(-s); y_sorted = y[idx]
tp_cum = np.cumsum(y_sorted)
precision_at_k = tp_cum / np.arange(1, len(y) + 1)
return np.sum(precision_at_k * y_sorted) / y.sum() # mean precision at each positive
roc_auc_rank(y, score), roc_auc_score(y, score) # equal (no ties in continuous scores)
average_precision(y, score), average_precision_score(y, score)
Multi-class and multi-label
Compute per-class precision/recall/F1 (one-vs-rest), then average:
- Macro: unweighted mean over classes: every class matters equally (rare classes count).
- Micro: pool all TP/FP/FN first: dominated by frequent classes (equals accuracy for single-label multi-class).
- Weighted: mean weighted by class support.
Also: top-k accuracy (correct label among the top k predictions), the multi-class confusion matrix (which classes get confused with which: often the most useful diagnostic), and for multi-label problems, per-label metrics and subset accuracy.
Probabilistic quality and calibration
A model can rank well but output poorly calibrated probabilities. Calibration means that among predictions with confidence 0.8, about 80% are correct. It matters whenever probabilities drive decisions: expected-cost thresholds, risk scores, combining models, deciding when an AI system should abstain or escalate to a human.
- Log loss (cross-entropy): punishes confident wrong answers heavily; proper scoring rule.
- Brier score: mean squared error between predicted probability and outcome (0/1); also proper.
- Reliability diagram: bin predictions by confidence, plot mean confidence vs observed accuracy; perfect calibration is the diagonal.
- Expected calibration error (ECE): weighted average gap between confidence and accuracy across bins.
Calibration methods, fitted on a held-out calibration set:
- Platt scaling: fit a logistic regression on the model's score.
- Isotonic regression: fit a monotone step function (needs more data, more flexible).
- Temperature scaling: divide logits by a single learned T > 0 (chapter 147); preserves ranking and accuracy, fixes neural network over-confidence.
from sklearn.calibration import calibration_curve
def ece(y, p, bins=10):
edges = np.linspace(0, 1, bins + 1); total = 0.0
for lo, hi in zip(edges[:-1], edges[1:]):
m = (p > lo) & (p <= hi)
if m.any(): total += m.mean() * abs(p[m].mean() - y[m].mean())
return total
p_true = rng.random(20000); y_cal = (rng.random(20000) < p_true).astype(int)
p_over = 1 / (1 + np.exp(-3 * np.log(p_true / (1 - p_true)))) # over-confident version (logits × 3)
ece(y_cal, p_true), ece(y_cal, p_over) # ≈ 0.01 vs ≈ 0.14
log_loss(y_cal, p_true), log_loss(y_cal, p_over) # over-confidence costs log loss
brier_score_loss(y_cal, p_true), brier_score_loss(y_cal, p_over)
Regression metrics
| Metric | Formula | Properties |
|---|---|---|
| MAE | mean |y − ŷ| | Same units as y; robust to outliers; optimal prediction is the median |
| MSE | mean (y − ŷ)² | Penalises large errors heavily; optimal prediction is the mean; differentiable |
| RMSE | √MSE | Same units as y; still outlier-sensitive |
| MAPE | mean |y − ŷ|/|y| | Scale-free percentages; undefined at y = 0; asymmetric |
| sMAPE / WAPE | variants | Common in forecasting |
| R² | 1 − SS_res/SS_tot | Fraction of variance explained relative to predicting the mean; 1 perfect, 0 = mean baseline, negative = worse than the mean |
| Quantile (pinball) loss | asymmetric | For prediction intervals and asymmetric costs (under-stocking vs over-stocking) |
| Huber loss | quadratic near 0, linear far | Robust training loss |
y_true = np.array([100, 150, 200, 250, 1000.0]) # one large value
y_pred = np.array([110, 140, 210, 240, 700.0])
err = y_true - y_pred
mae = np.abs(err).mean() # 68.0
rmse = np.sqrt((err ** 2).mean()) # ≈ 134.5: dominated by the 300 miss
mape = np.mean(np.abs(err) / np.abs(y_true)) * 100 # ≈ 11.1%
r2 = 1 - (err ** 2).sum() / ((y_true - y_true.mean()) ** 2).sum() # ≈ 0.84
Also inspect residual plots (residual vs prediction or vs feature): patterns reveal missing nonlinearity, heteroscedasticity (error growing with magnitude) or segment-specific bias.
Ranking and recommendation metrics
Search, recommendation and retrieval (including RAG retrieval, chapter 162) care about the order of results, and mostly about the top.
| Metric | Definition | Use |
|---|---|---|
| Precision@k | Relevant items in top k / k | "How much of the first page is useful?" |
| Recall@k | Relevant items in top k / all relevant | Retrieval coverage (did we fetch the needed documents?) |
| Hit rate@k | 1 if any relevant item in top k | Single-answer retrieval |
| MRR (mean reciprocal rank) | Mean of 1/rank of the first relevant item | Question answering, navigation queries |
| MAP | Mean over queries of average precision | Multiple relevant items, binary relevance |
| NDCG@k | DCG / ideal DCG, DCG = Σ (2^rel − 1)/log₂(i + 1) | Graded relevance (0–3), position discount |
def precision_at_k(rels, k): return np.mean(rels[:k])
def recall_at_k(rels, k, total_relevant): return np.sum(rels[:k]) / total_relevant
def mrr(list_of_rels):
return np.mean([1 / (np.argmax(r) + 1) if np.any(r) else 0 for r in list_of_rels])
def ndcg_at_k(gains, k):
gains = np.asarray(gains, float)
disc = 1 / np.log2(np.arange(2, k + 2))
dcg = np.sum((2 ** gains[:k] - 1) * disc[:len(gains[:k])])
ideal = np.sort(gains)[::-1]
idcg = np.sum((2 ** ideal[:k] - 1) * disc[:len(ideal[:k])])
return dcg / idcg if idcg else 0.0
ranked_binary = np.array([0, 1, 1, 0, 1]) # relevance of returned items in order
precision_at_k(ranked_binary, 3), recall_at_k(ranked_binary, 3, total_relevant=4) # 0.667, 0.5
mrr([np.array([0, 1, 0]), np.array([1, 0, 0]), np.array([0, 0, 0])]) # (0.5 + 1 + 0)/3 = 0.5
ndcg_at_k([3, 2, 0, 1], k=4) # ≈ 0.99: nearly ideal order
Online, ranking quality shows up as click-through rate, dwell time, conversion and long-term retention: offline metrics are proxies to be validated with A/B tests.
Error analysis
Aggregate metrics hide where a model fails. Error analysis is the highest-leverage activity in applied ML:
- Look at the errors. Sample 50–100 false positives and false negatives; read them; tag causes (label noise, ambiguous input, missing feature, rare subgroup, distribution shift).
- Slice metrics by meaningful segments: country, device, customer tier, input length, language, time period, demographic groups (fairness). A 92% average can hide a 60% segment.
- Confusion analysis: which classes are confused; are some labels ill-defined?
- Check the labels: a surprising share of "errors" are label mistakes; confident-learning tools (cleanlab) find likely mislabels.
- Prioritise by frequency × fixability × impact; fix data before tuning hyperparameters.
- Keep a regression test set of hard and previously fixed cases, re-run on every model version (chapter 175 does the same for LLM systems).
import pandas as pd
df = pd.DataFrame({"y": y, "pred": yhat,
"segment": rng.choice(["web", "ios", "android"], len(y), p=[0.5, 0.3, 0.2])})
by_seg = df.groupby("segment").apply(
lambda g: pd.Series({"n": len(g), "recall": recall_score(g.y, g.pred, zero_division=0),
"precision": precision_score(g.y, g.pred, zero_division=0)}),
include_groups=False)
by_seg
Offline vs online evaluation
| Offline | Online |
|---|---|
| Held-out data, fast, cheap, repeatable | Real users, real behaviour, the actual goal |
| Proxy metrics (AUC, NDCG) | Business metrics (conversion, retention, revenue, complaints) |
| Can't capture feedback loops | Captures interaction effects and feedback loops |
| Risk: offline gains that don't transfer | Risk: exposing users to worse models; needs guardrails |
The path to production: offline evaluation → shadow mode (new model scores live traffic without acting) → canary / A/B test with guardrail metrics → full rollout with monitoring (chapter 177–178). Counterfactual / off-policy evaluation estimates online effects of a new policy from logged data of the old one (importance weighting) when experiments are expensive.
Lab: metrics, thresholds, calibration and leakage
scikit-learn 1.9.1 on the lab machine. Imbalanced data from make_classification(20000, n_features=20, n_informative=6, weights=[0.99], flip_y=0.002, class_sep=0.8), split 50/50 stratified; a 300-tree random forest and a logistic regression. Leakage experiments use a separate 3,000-row dataset with 10% label noise.
Experiment 1: threshold sweep
| Threshold | Accuracy | Precision | Recall | F1 | TP | FP | FN |
|---|---|---|---|---|---|---|---|
| never flag | 98.87% | — | 0% | 0 | 0 | 0 | 113 |
| 0.50 | 98.89% | 100.0% | 1.8% | 0.03 | 2 | 0 | 111 |
| 0.30 | 98.88% | 55.6% | 4.4% | 0.08 | 5 | 4 | 108 |
| 0.10 | 97.38% | 18.3% | 38.1% | 0.25 | 43 | 192 | 70 |
| 0.05 | 93.97% | 10.2% | 55.8% | 0.17 | 63 | 553 | 50 |
ROC-AUC 0.863, PR-AUC 0.183 (a random model's PR-AUC equals the positive rate, 0.011, so 0.183 is a 16× lift). With costs ₹20 per review and ₹2,000 per missed fraud, the expected cost per 10,000 orders is: never flag ₹226,000; 0.10 → 235 × 20 + 70 × 2,000 = ₹144,700; 0.05 → 616 × 20 + 50 × 2,000 = ₹112,320. Under these costs the lowest threshold tried is best, although its F1 is lower than at 0.10: F1 encodes an implicit cost ratio that may not be yours. Sweep the full curve and choose by expected cost (or by review capacity, if that's the binding constraint).
Experiment 2: calibration
| Model | Brier score | Top-quintile predicted vs observed |
|---|---|---|
| logistic regression | 0.0103 | 4.6% vs 4.2% |
| random forest | 0.0101 | 5.2% vs 4.7% |
calibration_curve(y, p, n_bins=5, strategy="quantile") groups predictions into equal-count bins; plotting predicted against observed per bin is the reliability diagram. With only 113 positives, each bin's observed rate is itself uncertain (±2 points or so), so small miscalibrations here aren't distinguishable from noise. For fixing real miscalibration, use CalibratedClassifierCV with a held-out fold, never the test set.
Experiment 3: two leaks
| Setup | Score |
|---|---|
| clean features, 5-fold CV logistic regression | 68.7% |
+ leak = y + noise (a "refund issued" style post-outcome feature) |
96.4% |
| random forest, near-duplicates of every row on both sides of the split | 94.8% |
| random forest, same data without duplicates | 82.0% |
The duplicate case is common in practice: the same customer placing similar orders, the same image at two resolutions, the same document in two crawls. Group-aware splitting (GroupKFold by customer, TimeSeriesSplit by time) and deduplication (exact hashes plus near-duplicate detection such as MinHash for text, chapter 150) are the fixes. A practical leakage alarm: if one feature's importance dwarfs all others, or a simple model is suspiciously good, ask when that feature becomes known.
Try it yourself
- Plot precision–recall and cost against threshold for the random forest and find the cost-minimising threshold.
- Retrain with
class_weight="balanced"and compare PR-AUC and calibration. What did reweighting do to the probabilities? - Calibrate an XGBoost model with isotonic regression on a validation fold and compare Brier scores.
- Simulate customer-level duplication (each customer has 5 similar orders) and compare random
KFoldwithGroupKFold.
Revision sheet: ML evaluation
Key ideas
- Confusion matrix: TP, FP, FN, TN; accuracy, precision, recall, specificity, F1/Fβ.
- Thresholds from costs and capacity; curves (ROC, precision–recall) and their areas for threshold-free comparison; PR-AUC for rare positives.
- Calibration: reliability diagrams, Brier score, log loss; Platt scaling and isotonic regression.
- Regression metrics: MAE, RMSE, MAPE (and its traps), R²; quantile loss for forecasts.
- Ranking metrics: precision@k, recall@k, MAP, NDCG, MRR.
- Protocol: train/validation/test; CV; splits by time and group; one-shot test set; error bars; slice analysis (by segment, region, device).
- Leakage: target leakage, train–test contamination, preprocessing leakage, temporal leakage.
- Offline vs online: offline metrics must predict business outcomes; confirm with A/B tests.
Numbers to remember
- Lab: always-negative model 98.87% accurate, 0% recall.
- Lab: ROC-AUC 0.863 vs PR-AUC 0.183 on 1.1% positives.
- Lab: a post-outcome feature lifted 68.7% to 96.4%; duplicates lifted 82.0% to 94.8%.
Pitfalls
- Accuracy on imbalanced data; ROC-AUC alone for rare events.
- Default 0.5 thresholds; thresholds tuned on the test set.
- Random splits for time series or grouped data.
- Features unavailable at prediction time.
- Ignoring slices where the model fails badly.
- Treating calibration as optional when probabilities drive decisions.
Glossary
- Fβ: weighted harmonic mean of precision and recall (β > 1 favours recall).
- Brier score: mean squared error of probabilities.
- Reliability diagram: predicted vs observed frequency per bin.
- NDCG: ranking quality weighting top positions more.
- Slice analysis: evaluating metrics separately for subgroups.