Deriving Model Evaluation (ML #14)
Fraud is 0.3% of transactions. A model that predicts “not fraud” for every single row scores 99.7% accuracy and catches zero frauds, and it is one line long. Meanwhile the model your team actually shipped scores 99.4% accuracy and is doing its job. Nothing is broken — accuracy is simply measuring the wrong thing, and this chapter derives which measure is right and when.
The deeper lesson is that every metric is a choice about what counts as an error, encoded as arithmetic. Precision and recall weight those two errors differently; F1 chooses a specific compromise; AUC ignores the threshold entirely. Choosing correctly means knowing which weighting your problem has.
The contingency table
Every binary evaluation reduces to counting four cells. True/False describe the label, Positive/Negative describe the prediction:
| predicted \(+\) | predicted \(-\) | |
|---|---|---|
| actually \(+\) | true positive (\(TP\)) | false negative (\(FN\)) |
| actually \(-\) | false positive (\(FP\)) | true negative (\(TN\)) |
\(FN\) is a miss (a real fraud waved through) and \(FP\) is a false alarm. These are not the same kind of error — one costs money lost to criminals, the other costs investigator hours — and every metric is a different way of trading them off.
\[ \text{precision} = \frac{TP}{TP + FP}, \qquad \text{recall} = \frac{TP}{TP + FN} \]
Precision is the fraction of alarms that were real: when it says fraud, how often is it fraud? Recall is the fraction of real frauds caught: of all fraud, how much did we find? Note that both have \(TP\) in the numerator, so raising the decision threshold raises precision and lowers recall — the trade-off is structural, baked into the definitions.
Accuracy, and why it collapses under imbalance
\[\text{accuracy} = \frac{TP + TN}{TP + TN + FP + FN} = \frac{\text{correct}}{\text{total}} \]
Accuracy counts both kinds of correct prediction equally, which is only sensible when the two error types cost the same and classes are balanced. Under imbalance it degenerates. With 0.3% positives, the constant negative predictor achieves \(TN/(TN+FP+FN) \approx 0.997\) — nearly perfect by accuracy, worth nothing operationally. Accuracy is a statement about the base rate, not about your model.
F1 is a harmonic mean, and the choice matters
Precision and recall are two views of one trade-off, so you often want one number. The obvious summary is the arithmetic mean — and it is the wrong one. Consider a model with precision \(= 1.0\) and recall \(= 0.0\): it flags exactly one transaction and it’s genuinely fraud, but it misses every other fraud. It has caught nothing.
\[ \text{arithmetic mean} = \frac{1.0 + 0.0}{2} = 0.5 \qquad \text{vs.} \qquad \frac{2(1.0)(0.0)}{1.0 + 0.0} = 0 \]
The arithmetic mean gives a model that found nothing a score of 0.5. The harmonic mean gives it 0. That is the entire justification for F1:
\[ F_1 = \frac{2PR}{P + R} = \left(\frac{1}{2}\left(\frac{1}{P} + \frac{1}{R}\right)\right)^{-1} \]
Algebraically F1 is the reciprocal of the average of reciprocals. The harmonic mean is dominated by the smaller of the two inputs: it sits at or below the smaller value always, and equals half the smaller only when they are equal. So F1 refuses to reward a lopsided model, and a model that is only good at one end is scored near its weak end.
The more general \(F_\beta\) weights recall \(\beta^2\) times more than precision when \(\beta > 1\) (favor recall; used in medical screening), or precision more when \(\beta < 1\). Choosing \(\beta\) is choosing which error costs more — an application decision, not a statistical one.
ROC and the area under it
ROC avoids thresholding entirely by sweeping it. Define
\[ \text{TPR} = \frac{TP}{TP+FN} = \text{recall}, \qquad \text{FPR} = \frac{FP}{FP+TN} = 1 - \text{specificity} \]
As the threshold sweeps from \(-\infty\) to \(+\infty\), every predicted probability maps to a (FPR, TPR) pair, tracing a curve. Note TPR and FPR share the numerator structure but different denominators: TPR normalizes by positives, FPR by negatives. That single fact explains when ROC misleads (next section).
AUC is the area under this curve, and it has a clean probabilistic meaning that makes it the most useful derived metric in this post:
\[ \boxed{\; \text{AUC} = \Pr(\text{score of a random positive} > \text{score of a random negative}) \;} \]
AUC is the probability that a randomly chosen positive outranks a randomly chosen negative. That’s it — a ranking property, independent of any threshold, which is exactly why it’s threshold-free and comparable across models.
The rank formula makes it computable in \(O(n \log n)\). Assign ranks \(r_i\) (average rank for ties), then
\[ \text{AUC} = \frac{\sum_{i \in \text{pos}} r_i - \frac{n_{\text{pos}}(n_{\text{pos}}+1)}{2}}{n_{\text{pos}} \, n_{\text{neg}}} \]
The subtracted term removes the ranks the positives would occupy by chance alone. Ties must use average ranks, or the metric is biased.
import numpy as np
def auc_rank(y_true, score):
"""AUC via average ranks -- tie-safe, no sklearn needed."""
y = np.asarray(y_true).astype(bool)
s = np.asarray(score, dtype=float)
order = np.argsort(s, kind="mergesort")
ranks = np.empty(len(s), dtype=float)
ranks[order] = np.arange(1, len(s) + 1) # average ranks within tied groups
_, inv, cnt = np.unique(s, return_inverse=True, return_counts=True)
for i in np.where(cnt > 1)[0]:
ranks[inv == i] = ranks[inv == i].mean()
npos, nneg = y.sum(), (~y).sum()
return (ranks[y].sum() - npos * (npos + 1) / 2) / (npos * nneg)
Ties are the subtle part. Two positives with identical scores are not ordered, and treating them as arbitrarily ordered inflates AUC. Averaging ranks within each tied group — the last loop — makes tied pairs contribute exactly 0.5, which is the correct probability of a coin flip between equal scores. Skip it and the metric is quietly wrong on any model with plateaus, which includes every tree-based model and every model with clipped scores.
\begin{tikzpicture}[font=\rmfamily, >=stealth]
\draw[->, thick] (0,0) -- (4.6,0) node[right, font=\rmfamily\scriptsize] {FPR (false positive rate)};
\draw[->, thick] (0,0) -- (0,3.6) node[above, font=\rmfamily\scriptsize] {TPR (recall)};
\draw[gray!60, dashed] (0,0) -- (4.2,3.2);
\draw[blue!70!black, very thick] (0,0) .. controls (3.2,3.1) and (0.6,0.3) .. (4.2,3.2);
\draw[orange!85!black, very thick] (0,0) .. controls (0.15,1.0) and (3.9,3.05) .. (4.2,3.2);
\fill[orange!85!black] (0.55,0.42) circle (1.8pt);
\node[font=\rmfamily\scriptsize, text=blue!70!black] at (2.6,1.0) {AUC 0.62};
\node[font=\rmfamily\scriptsize, text=orange!70!black] at (2.5,2.35) {AUC 0.93};
\node[font=\rmfamily\scriptsize, text=gray!75] at (3.3,1.55) {chance};
\node[font=\rmfamily\scriptsize, text=black!60, align=center] at (2.3,-0.6) {AUC = P(a random positive scores\\above a random negative)};
\end{tikzpicture}
PR curves win under imbalance
Because FPR normalizes by negatives, a huge negative class makes the denominator large and the FPR axis compressed. With 99.7% negatives, a model can push FPR to 0.002 — half a percent — while catching almost nothing, and the ROC curve still looks fine.
The precision–recall curve fixes the normalization problem: precision normalizes by predictions, which are few, so it is sensitive to false alarms. Under severe imbalance PR-AUC is markedly lower and far more discriminating than ROC-AUC for the same model. The rule that follows: ROC-AUC when classes are roughly balanced, PR-AUC (average precision) when they are not. A model whose ROC-AUC is 0.92 may have a PR-AUC of 0.11 — that gap is the tell.
Log loss rewards calibrated probability
Ranking metrics ignore how wrong a confident mistake is. Log loss (the cross-entropy from Chapter 3) does not:
\[ \text{log loss} = -\frac{1}{n}\sum_i \left[ y_i \log \hat{p}_i + (1-y_i)\log(1-\hat{p}_i) \right] \]
The log makes mistakes disproportionately expensive: predicting a positive with probability 0.99 when it is actually negative costs \(\approx 4.6\) nats, while predicting 0.51 costs \(\approx 0.69\). A model that is slightly wrong and appropriately hedged is heavily preferred over one confidently wrong — which is the behavior you want when someone acts on the output. log loss is also the only proper scoring rule for probability, so it is the right metric when probabilities themselves are the deliverable (Chapter 15’s standards work depends on it).
Calibration: good rankings can be bad probabilities
A model can rank well (AUC 0.9) while its probabilities are systematically off — and calibration is a property orthogonal to discrimination. Let \(\hat p = 0.8\) for a group; if those cases actually occur 60% of the time, the model is overconfident. Expected calibration error measures the gap:
\[ \text{ECE} = \sum_{b} \frac{n_b}{n}\left| \text{accuracy}_b - \text{mean confidence}_b \right| \]
bucketing predictions by confidence and averaging the within-bucket gap. Diagnose it with a reliability diagram — predicted probability on the x-axis, observed frequency on the y-axis — where a perfectly calibrated model falls on the diagonal.
Naive Bayes (Chapter 10) is the canonical offender: it multiplies likelihoods as if features were independent, so its posteriors are overconfident by construction. The standard fix is temperature scaling, which rescales logits before the sigmoid:
\[ \hat p = \sigma\!\left(\frac{z}{T}\right), \qquad T > 1 \text{ softens}, \quad T < 1 \text{ sharpens} \]
It has exactly one parameter, fit by minimizing log loss on a held-out set, and it preserves ranking — dividing all logits by a positive constant is monotone, so AUC is unchanged. Only the probabilities move. That is why it’s the right first fix: it can’t hurt your ranking, only your confidence.
def temperature_scale(logits, T):
return 1.0 / (1.0 + np.exp(-np.asarray(logits) / T))
# Fit T by grid search on validation log loss; report AUC before/after.
Choosing the threshold
Metrics that depend on a threshold (precision, recall, F1, accuracy at 0.5) are only meaningful at that threshold, and 0.5 is almost never the right one. Instead: compute the metric across all thresholds, plot the PR or ROC curve, then choose the operating point from the cost ratio.
If a false negative costs \(C_{FN}\) and a false positive costs \(C_{FP}\), the threshold should be set where those balance — a Bayes-optimal decision rule puts the threshold at probability \(p^* = \frac{C_{FP}}{C_{FP} + C_{FN}}\). With a missed fraud costing 100× an investigator’s wasted minute, that threshold sits very low, which is why fraud systems tolerate enormous false-alarm rates: they must, given the cost ratio.
from sklearn.metrics import precision_recall_curve, average_precision_score
precision, recall, thresholds = precision_recall_curve(y_true, scores)
ap = average_precision_score(y_true, scores)
target_recall = 0.90
i = (recall >= target_recall).argmax()
print(f"threshold {thresholds[i]:.3f} -> precision {precision[i]:.3f}, recall {recall[i]:.3f}")
Pick the threshold on validation data to hit a target recall or precision, then freeze it. Re-deriving it on the test set is tuning on your final answer.
The protocol
- Split before anything else. Fit preprocessing (scaling, imputation, feature selection) inside the training fold only. Fitting a scaler on the full dataset before splitting leaks test-set statistics into training and inflates every metric.
- Cross-validate for model selection. \(k\)-fold: split into \(k\) parts, train on \(k-1\), evaluate on the held-out one, repeat, average. It reduces the variance of your estimate — the dominant concern when the test set is a few hundred rows.
- Note the optimism. In \(k\)-fold, the validation folds appear in training for other splits, so CV error is slightly optimistic as an estimate of true generalization. Small \(k\) (2 or 3) makes this worse while also making the estimate noisier. \(k = 5\) or 10 is the usual compromise.
- Bootstrap confidence intervals. A single point estimate on a small test set is not evidence. Resample test cases with replacement, recompute the metric, and report a percentile interval.
- Touch the test set once. Every comparison against it converts it into a validation set, and the reported number drifts optimistic.
def bootstrap_ci(y_true, score, metric_fn, n_boot=2000, alpha=0.05):
rng = np.random.default_rng(0)
n = len(y_true)
stats = []
for _ in range(n_boot):
idx = rng.integers(0, n, n)
if len(np.unique(y_true[idx])) < 2: # a resample with one class
continue
stats.append(metric_fn(y_true[idx], score[idx]))
lo, hi = np.quantile(stats, [alpha / 2, 1 - alpha / 2])
return lo, hi
On a test set of 200 cases, an AUC of 0.90 comes with a confidence interval roughly ±0.04 wide — enough to overlap 0.86. Any claim that 0.90 beats 0.88 without an interval is unsupported.
Pitfalls
- Accuracy on imbalanced data. It measures the base rate. Use PR-AUC or recall at a fixed precision.
- F1 without deciding about \(\beta\). F1 assumes symmetric error costs. On medical screening, use \(F_2\) (\(\beta = 2\)) to weight recall.
- AUC as a threshold rule. AUC is threshold-free by construction; it tells you nothing about where to operate. Set the threshold separately, from costs.
- Trusting probabilities without calibration. A model can rank well and still be overconfident. Check a reliability diagram and fit temperature scaling.
- Leaking preprocessing across the split. Fitting a scaler or imputer on the full dataset before splitting contaminates every metric. Use a
Pipeline. - Comparing models on a single point estimate. Bootstrap intervals first. Many “improvements” are inside the noise.
- Selecting on the test set. Each comparison makes the test set a validation set; the reported figure inflates with every look.
Show that F1 is a harmonic mean, and give the numerical reason it beats the arithmetic mean for a model with precision 1.0 and recall 0.0. Why does a model with ROC-AUC 0.92 perform badly in production on a 0.3%-positive problem, given the definitions of TPR and FPR? Your fraud model’s probabilities are overconfident and its AUC is fine. Which single-parameter fix helps, and why can it not hurt your ranking? Why must preprocessing be fit inside the training fold?
ASolution
\(F_1 = 2PR/(P+R)\), and since \(\frac{2PR}{P+R} = \left(\frac12(\frac1P + \frac1R)\right)^{-1}\) it is literally the reciprocal of the mean of reciprocals. The harmonic mean is always at or below \(\min(P,R)\), so with \(P = 1.0, R = 0.0\) it gives \(0\) while the arithmetic mean gives \(0.5\) — a model that caught literally nothing scores 0.5 under the arithmetic mean and 0 under F1, which is the intended behavior because the harmonic mean is dominated by the weaker component. On the production failure: TPR normalizes by positives while FPR normalizes by negatives, so with 99.7% negatives the FPR denominator is enormous, letting a model that catches almost no real fraud still achieve a very low FPR and therefore a flattering ROC curve. Restrict attention to the rare positives — i.e. look at precision — and the same model collapses, which is why PR-AUC rather than ROC-AUC is the metric to trust under severe imbalance. The one-parameter fix is temperature scaling: divide the logits by a single \(T > 0\) before the sigmoid, fit by minimizing log loss on held-out data. It cannot hurt ranking because dividing by a positive constant is a strictly monotone transform of the score, so every ordering and therefore AUC is unchanged; only the probability magnitudes move, which is exactly the overconfidence you want to correct. And preprocessing must be fit inside the training fold because a scaler’s means and standard deviations — or an imputer’s fill values, or a feature selector’s chosen columns — are estimated from data. Fitting them on the full dataset lets test-set information flow into training, so the reported metrics are optimistic by an amount you cannot see, and it is especially damaging with small test sets where a single outlier can shift a mean substantially.
Where next
You have now derived the classical algorithm family end to end: the normal equation and its closed forms, the likelihood-based losses, the optimizers, the geometric learners, the ensembles, the unsupervised decompositions, and the evaluation arithmetic that tells you whether any of it worked. The natural continuations are the sibling roadmaps: the Backend Roadmap for the storage, caching, and scaling machinery beneath these models in production, and DevOps for deploying and observing them. For the neural-network algorithms that Chapters 8 and 12 gesture at, /deep-learning-guide/ covers backpropagation, CNNs, and attention in the same derivation-first style.
End of the ML algorithms course — fourteen chapters, from the normal equation to a metric that survives contact with a 0.3% base rate.