Skip to content
Classical machine learning Foundation 27 min read

Metrics, validation and leakage

A model is only as good as the experiment that measured it. Evaluation is a simulation of the future: hold back data the model never influenced, split it the way the future will differ from the past, score it with a metric that reflects what errors actually cost, and report the uncertainty. Leakage is any crack through which the future seeps into training, and it is the most common reason impressive results evaporate.

10,000 ft

Every claim in machine learning, from "our credit model cuts defaults by 12%" to "this LLM scores 90% on a benchmark", is an evaluation claim. Training makes a model fit; evaluation tells you whether it generalises, which is the only property that matters. The machinery on this page (held-out sets, cross-validation, proper metrics, confidence intervals, leakage audits) is classical, but its failure modes are the same ones that plague modern AI: benchmark contamination in LLMs is test-set leakage; overfitting a public leaderboard is test-set reuse; an LLM judge without a calibration check is an uncalibrated metric (evals in practice). Kapoor and Narayanan's survey of machine-learning-based science found leakage errors in 17 fields, affecting 329 papers. Master this page and you will catch more bad results than any new architecture will ever fix.

2,000 ft

  1. Decide what "the future" is: new patients, next month, a new country, new users. That determines the split.
  2. Split before you look: training data for fitting, validation data (or cross-validation folds) for choosing models and hyperparameters, and a test set touched once at the end.
  3. Split along the axis of generalisation: by time for forecasting, by group (patient, user, document) when examples cluster, at random only when examples are truly independent.
  4. Choose a metric that mirrors cost: threshold metrics (precision, recall) for decisions, ranking metrics (ROC-AUC, PR-AUC) for ordering, proper scoring rules (log loss, Brier) for probabilities.
  5. Fit every preprocessing step inside the training fold, scalers, imputers, feature selection, target encoders, or you leak.
  6. Report the test score with an interval, and compare models on the same examples with paired tests.

An honest evaluation pipeline
An honest evaluation pipeline. All data, Split by time / group (before any fitting), Training folds, Fit preprocessing + model (inside each fold), Validation / CV score, Test set (touched once), Score ± interval, tune, choose, final modelAn honest evaluation pipeline. All data, Split by time / group (before any fitting), Training folds, Fit preprocessing + model (inside each fold), Validation / CV score, Test set (touched once), Score ± interval, tune, choose, final model

Ground level

The golden rule: the test set simulates the future

Training error is useless as an estimate of performance: the model was fitted to those very points, and a flexible enough model drives it to zero (bias and variance). What you want is the expected error on new data from the deployment distribution. A held-out set gives an unbiased estimate of it, for one reason only: nothing about the model depended on those examples. Every decision you make after looking at held-out results (which features, which model, which threshold, when to stop) makes the model depend on them a little, and the estimate becomes optimistic. The discipline of evaluation is the discipline of keeping that dependence at zero for at least one dataset.

Train, validation, test

  • Training set: fits the parameters.
  • Validation set (or development set): chooses among models, features, hyperparameters, thresholds, early-stopping points. It gets used many times, so its score is optimistic for the chosen model.
  • Test set: estimates the final model's performance, once. If you then go back and change the model, it has become a validation set, and you need a fresh test set to make an unbiased claim.

Typical proportions such as 60/20/20 are less important than absolute sizes: a test set needs enough examples (and enough positives) for the metric to be precise. A test accuracy from 200 examples has a 95% interval about ±6 percentage points wide (see uncertainty).

Cross-validation

When data are scarce, setting aside a fixed validation set wastes examples and gives a noisy estimate. k-fold cross-validation splits the data into \(k\) folds, trains \(k\) times, each time validating on the fold left out, and averages the \(k\) scores. Every example is used for validation exactly once and for training \(k-1\) times.

  • \(k = 5\) or \(10\) is the standard compromise. Larger \(k\) means each model trains on more data (less pessimistic bias) but the folds' training sets overlap more (more correlated estimates) and it costs more. Leave-one-out (\(k = n\)) is nearly unbiased but high-variance and expensive except for models with closed-form shortcuts (ordinary and ridge regression have one).
  • Stratified k-fold keeps the class proportions equal across folds; essential for rare classes.
  • Repeated k-fold with different shuffles reduces the variance that comes from one particular partition.
  • The standard deviation across folds is not a valid standard error of the CV estimate (the folds share training data), but it is a useful warning light.

Cross-validation estimates the performance of the procedure (fit this model family with these settings on about \(\frac{k-1}{k}n\) examples). After choosing settings, refit on all the data for deployment.

Nested cross-validation: when CV chooses the model

If you try 50 hyperparameter settings and report the best CV score, that score is optimistically biased: you picked the setting that got luckiest on these folds. Cawley and Talbot (2010) showed this selection bias can be as large as the differences between learning algorithms that papers report. The fix is nested CV: an outer loop of folds estimates performance, and inside each outer training set an inner CV loop does the tuning. The outer test fold never influences any choice. Use it when you must report an unbiased estimate and cannot afford a separate test set; otherwise, tune with CV and keep a held-out test set.

Split along the axis of generalisation

Random splitting assumes every example is an independent draw from the deployment distribution. That is rarely true.

Groups. Multiple images per patient, many sessions per user, several sentences per document, repeated measurements per machine. If one patient's scans are in both training and test, the model can recognise the patient rather than the disease, and test accuracy measures memorisation. Use group k-fold: all examples of a group go to the same fold. Generalising to new patients requires testing on new patients.

Time. For anything deployed forward in time (forecasting, credit, fraud, churn, prices), train on the past and test on the future, never the reverse. Use a single cut-off date or a rolling-origin (expanding-window) scheme, and leave a gap between training and test when features or labels take time to materialise (a 90-day default label is not known until 90 days later).

fold 1fold 2fold 3fold 4 time → traintestgap = white
Rolling-origin evaluation: every fold trains only on the past and tests on the block after a gap. The scores across folds also show whether performance decays as the world drifts.

Space and other shifts. Neighbouring locations are correlated (use spatial blocks); a model meant for a new hospital, country or product line should be tested on one it never saw. When the deployment distribution differs from anything you can sample, say so: no split can measure a shift you have no data for (data in production).

Classification metrics: one confusion matrix, many numbers

Every threshold metric is a summary of the confusion matrix. A worked example: a screening test for a condition with 1% prevalence, applied to 10,000 people, with sensitivity 90% and specificity 95%.

actually positive (100) actually negative (9,900)
predicted positive TP = 90 FP = 495
predicted negative FN = 10 TN = 9,405
  • Accuracy \(= (90 + 9{,}405)/10{,}000 = 94.95\%\). The trivial model "everyone is negative" scores 99%. Accuracy is dominated by the majority class: the accuracy paradox.
  • Recall (sensitivity, true positive rate) \(= \text{TP}/(\text{TP}+\text{FN}) = 90/100 = 90\%\): of the sick, how many we catch.
  • Specificity \(= \text{TN}/(\text{TN}+\text{FP}) = 95\%\); false positive rate $= 1 - $ specificity \(= 5\%\).
  • Precision (positive predictive value) \(= \text{TP}/(\text{TP}+\text{FP}) = 90/585 = 15.4\%\): of those flagged, how many are sick. Fewer than one in six, despite "90% sensitive, 95% specific". This is Bayes' rule, and the base-rate fallacy: when positives are rare, even a small false positive rate produces many false positives in count.
  • F1 \(= 2PR/(P+R) = 2(0.154)(0.9)/(1.054) = 0.263\), the harmonic mean, which is dragged down by the worse of the two.

Which number matters depends on the decision. Missing a cancer (FN) is far worse than a follow-up scan (FP), so screening optimises recall and accepts low precision; a spam filter that hides real mail (FP) is worse than letting some spam through, so it guards precision. The threshold sets the trade, and a calibrated probability plus a cost ratio fixes it: predict positive when \(p > c_{\text{FP}}/(c_{\text{FP}}+c_{\text{FN}})\) (logistic regression).

Ranking metrics: ROC and precision–recall curves

Sweep the threshold from high to low and every metric traces a curve.

The ROC curve plots true positive rate against false positive rate. Its area, ROC-AUC, has a clean meaning: the probability that a randomly chosen positive gets a higher score than a randomly chosen negative. By hand: positives scored \(\{0.9, 0.8, 0.4\}\), negatives \(\{0.7, 0.3, 0.2, 0.1\}\). Of the \(3\times4 = 12\) positive–negative pairs, the positive wins in \(4 + 4 + 3 = 11\), so AUC \(= 11/12 = 0.917\). A random scorer gets 0.5; a perfect ranker 1.0. ROC-AUC is independent of the threshold and of class prevalence, which is both its strength and its weakness.

The precision–recall (PR) curve plots precision against recall; its area is estimated by average precision (AP). A random scorer's AP equals the prevalence. Because precision involves false positives in count, the PR curve is sensitive to class imbalance in exactly the way the deployment is.

false positive raterecallROC · AUC 0.92precision–recall · AP 0.38 random: 0.5random: 0.02 1010
The same model on the same data (2% positives; the Build-it run). The ROC curve hugs the top-left corner and its AUC of 0.92 looks excellent; the four marked thresholds are all squeezed into the first 7% of false positive rate. The PR curve shows the operational truth: to catch two-thirds of positives, precision drops to 16%.

Rule of thumb: when positives are rare and false positives cost effort (fraud review, search results, medical follow-ups), report the PR curve and AP alongside ROC-AUC. Saito and Rehmsmeier (2015) make the case in detail; Davis and Goadrich (2006) prove the two curves are linked one-to-one, so a curve dominating in ROC space also dominates in PR space, but their areas can rank models differently.

Probabilistic metrics: scoring the probabilities themselves

If the model's probabilities will be used (to set prices, to combine with costs, to show a user "73% likely"), score them directly with a proper scoring rule, one whose expected value is optimised only by reporting the true probability:

  • Log loss (cross-entropy): \(-\frac1n\sum_i[y_i\log p_i + (1-y_i)\log(1-p_i)]\). Punishes confident errors without bound; the training loss of logistic regression and neural classifiers.
  • Brier score: \(\frac1n\sum_i (p_i - y_i)^2\), mean squared error on probabilities; bounded, gentler on confident errors.

Accuracy and F1 are not proper: a model can improve them while its probabilities get worse. Check calibration separately with a reliability diagram (bin predictions, plot mean predicted against observed frequency) or the expected calibration error (ECE), the weighted average gap across bins; logistic regression shows one.

Regression metrics

  • MSE / RMSE targets the conditional mean and punishes large errors quadratically; RMSE is in the target's units.
  • MAE targets the conditional median, robust to outliers.
  • MAPE (mean absolute percentage error) is popular with business users and treacherous: it is undefined at zero, explodes near zero, and penalises over-forecasts more than under-forecasts of the same size (forecast 150 for 100 is 50% error; forecast 50 for 100 is also 50%, but forecast 100 for 50 is 100%), which biases models towards forecasting low.
  • \(R^2\) compares with predicting the mean; on test data it can be negative. Report it alongside an absolute error.
  • Quantile (pinball) loss for prediction intervals; check that a stated 90% interval contains about 90% of test outcomes.

Train and select with the metric you will be judged on, or one whose optimum coincides with it.

How sure are you? Uncertainty and comparisons

A test score is an estimate from a finite sample. For accuracy on \(n\) independent test examples, the standard error is \(\sqrt{\hat a(1-\hat a)/n}\). With \(n = 1{,}000\) and \(\hat a = 0.85\): \(\sqrt{0.85 \times 0.15/1000} = 0.0113\), so a 95% interval is about \(85\% \pm 2.2\) points. Model B at 86% on the same test set is not demonstrably better from those two numbers.

But the two models were scored on the same examples, so compare them paired: count \(b\) = examples A got right and B got wrong, and \(c\) = the reverse. The examples both got right or both got wrong carry no information about the difference. McNemar's test uses \(\chi^2 = (b - c)^2/(b + c)\) with one degree of freedom. If B's 1-point edge came from \(b = 40\), \(c = 50\), then \(\chi^2 = 100/90 = 1.11\), \(p \approx 0.29\): not significant. If it came from \(b = 2\), \(c = 12\): \(\chi^2 = 100/14 = 7.1\), \(p \approx 0.008\). Same accuracies, different evidence. Dietterich (1998) compares such tests for classifiers.

For metrics without a simple formula (AUC, F1, AP), use the bootstrap: resample the test set with replacement many times, recompute the metric, and take the 2.5th and 97.5th percentiles. Resample groups if examples are clustered. Statistics for experiments and evals goes further (multiple comparisons, power, sequential testing).

Leakage: how the future gets into training

Leakage is any path by which information that would not be available at prediction time influences the model or its evaluation. It inflates offline scores and collapses in production. The main kinds:

Kind What happens Example Guard
Target leakage a feature is a consequence or proxy of the label "account closed date" when predicting churn; "received antibiotics" when predicting infection for each feature ask: would I know this at the moment of prediction?
Preprocessing leakage statistics computed on all data before splitting scaling, imputation, PCA, feature selection, target encoding fitted on the full dataset fit every transform inside the training fold (a Pipeline)
Group / duplicate leakage the same entity or near-duplicates in train and test several photos of one patient; the same news story syndicated twice group splits; deduplicate before splitting
Temporal leakage the model sees the future random split of time-series data; features computed with windows that extend past the prediction time time-based splits with gaps; point-in-time feature computation
Test-set reuse repeated peeking at test results tuning against the test set; leaderboard climbing one-shot test set; fresh holdouts; nested CV
Sampling artefacts how data were assembled encodes the label IDs, file paths, scanner type, or collection site correlated with the outcome check whether ID-like or metadata features predict the label; they should not

Real cases are instructive. In the KDD Cup 2008 breast-cancer competition, the winning team found that patient identifiers carried information about malignancy, an artefact of how the dataset had been assembled; Kaufman, Rosset, Perlich and Stitelman (2012) built a formal treatment of leakage from such cases. Kapoor and Narayanan (2023) re-examined claims that complex models vastly outperform logistic regression at predicting civil wars and found the advantage vanished once leakage was corrected. In LLMs, benchmark questions appearing in pre-training data is the same failure at internet scale (contamination).

The wrong way to do cross-validation

Select the 100 features most correlated with the label using all the data, then cross-validate a classifier on those features. On pure noise, with labels independent of every feature, this reports 100% accuracy in the Build-it run below; selecting inside each fold gives the true 51%. Hastie, Tibshirani and Friedman call this "the wrong and right way to do cross-validation" (ESL section 7.10.2), and it remains one of the most common errors in published work with many features and few samples.

History

From radar operators to Kaggle

The ROC curve comes from signal detection theory, developed for radar during and after the Second World War to describe how an operator trades hits against false alarms as the detection threshold moves; Green and Swets' 1966 book carried it into psychology, and from there it reached medicine and machine learning. Cross-validation as a principled method for choosing and assessing predictors is usually dated to Mervyn Stone's 1974 paper and Seymour Geisser's work in 1975. The Brier score was proposed by the meteorologist Glenn Brier in 1950 to verify probabilistic weather forecasts. Competitions sharpened the modern awareness of leakage and test-set reuse: public leaderboards made overfitting to a held-out set something you could watch happen, and Recht et al. (2019) rebuilt fresh ImageNet and CIFAR-10 test sets and found accuracy drops of 11–14% and 3–15% respectively, though they attributed the drop mainly to the new images being slightly harder rather than to adaptive overfitting.

First principles

Why a held-out estimate is unbiased, and why reuse breaks it. Let \(\hat f\) be fixed and let \((\mathbf{x}_i, y_i)\) be test examples drawn independently of everything that produced \(\hat f\). Then each loss \(\ell(\hat f(\mathbf{x}_i), y_i)\) is an independent draw with mean equal to the true risk \(R(\hat f)\), so their average is unbiased, with variance shrinking as \(1/n\). The argument needs independence between the test examples and \(\hat f\). The moment you select \(\hat f\) because it scored well on those examples, the selected score is the maximum of several noisy estimates, and the maximum of noisy estimates is biased upwards (the winner's curse). If 100 configurations all truly score 85% and each test estimate has standard error 1.1 points, the best observed score is expected to be about \(2.5\) standard errors high: roughly 87.8%, an illusory gain of nearly 3 points, from selection alone.

Why the split must mirror deployment. The estimate is unbiased for the distribution the test set was drawn from. If test examples share patients, time periods or near-duplicates with training while deployment will not, you are estimating performance on a different, easier problem. Choosing the split is choosing which generalisation question you are answering.

Why proper scoring rules. Suppose the true probability is \(q\) and you report \(p\). Expected log loss is \(-[q\log p + (1-q)\log(1-p)]\); its derivative in \(p\) is zero exactly at \(p = q\). Expected Brier score \(q(1-p)^2 + (1-q)p^2\) is minimised at \(p = q\) too. Accuracy at threshold 0.5 is equally happy with \(p = 0.51\) or \(0.99\) whenever \(q > 0.5\): it cannot reward honesty.

The maths

Confusion-matrix quantities. With \(P = \text{TP}+\text{FN}\) positives and \(N = \text{FP}+\text{TN}\) negatives: \(\text{TPR} = \text{TP}/P\), \(\text{FPR} = \text{FP}/N\), \(\text{precision} = \text{TP}/(\text{TP}+\text{FP})\), \(F_\beta = (1+\beta^2)\frac{PR}{\beta^2P + R}\) (with \(P, R\) here precision and recall; \(\beta > 1\) weights recall more). In terms of prevalence \(\pi\):

\[ \text{precision} = \frac{\pi\,\text{TPR}}{\pi\,\text{TPR} + (1-\pi)\,\text{FPR}} , \]

which is Bayes' rule and makes the base-rate effect explicit: for the screening example, \(\frac{0.01\times0.9}{0.01\times0.9 + 0.99\times0.05} = 0.154\).

Derivation: ROC-AUC equals the probability of correct ranking

Let \(S_1\) and \(S_0\) be the scores of a random positive and a random negative, with survival functions \(\text{TPR}(t) = P(S_1 > t)\), \(\text{FPR}(t) = P(S_0 > t)\). The ROC curve is the parametric curve \((\text{FPR}(t), \text{TPR}(t))\) as \(t\) runs from \(+\infty\) to \(-\infty\). Its area is

\[ \text{AUC} = \int_0^1 \text{TPR}\;d\,\text{FPR} = \int_{-\infty}^{\infty} P(S_1 > t)\, f_0(t)\,dt = P(S_1 > S_0), \]

where \(f_0\) is the density of \(S_0\) and we substituted \(d\,\text{FPR} = f_0(t)\,dt\) (the sign flips with the limits). Empirically, \(\widehat{\text{AUC}} = \frac{1}{n_1n_0}\sum_{i:y_i=1}\sum_{j:y_j=0}\mathbb{1}[s_i > s_j]\) (ties count ½), which equals the Mann–Whitney \(U\) statistic divided by \(n_1n_0\). Computing it via ranks: if \(R_1\) is the sum of the positives' ranks among all \(n\) scores, \(U = R_1 - n_1(n_1+1)/2\). That is the formula in the Build-it code. For two Gaussian score distributions with equal variance and means \(d'\) standard deviations apart, \(\text{AUC} = \Phi(d'/\sqrt{2})\): \(d' = 2\) gives \(\Phi(1.414) = 0.921\), matching the simulation's 0.919.

Average precision. With examples sorted by decreasing score, \(\text{AP} = \frac{1}{n_1}\sum_{k:\,y_{(k)}=1}\text{precision@}k\): the mean of the precision values at the rank of each positive.

Standard error of a proportion. For accuracy \(\hat a\) from \(n\) independent examples, \(\operatorname{Var}(\hat a) = a(1-a)/n\); a normal-approximation 95% interval is \(\hat a \pm 1.96\sqrt{\hat a(1-\hat a)/n}\) (use the Wilson interval when \(\hat a\) is near 0 or 1 or \(n\) is small).

McNemar. Under the null hypothesis that both models have the same error rate, each discordant example is equally likely to favour A or B, so \(b \sim \text{Binomial}(b+c, \tfrac12)\); the statistic \((b-c)^2/(b+c)\) is approximately \(\chi^2_1\) (use the exact binomial test when \(b + c\) is small).

Expected maximum of noisy estimates. For \(K\) independent \(\mathcal{N}(\mu, s^2)\) estimates, \(\mathbb{E}[\max] \approx \mu + s\sqrt{2\ln K}\) for large \(K\) (the more precise value at \(K = 100\) is about \(\mu + 2.51s\)). Selection bias grows only like \(\sqrt{\ln K}\), slowly but without limit.

In practice

  • Write down the deployment scenario first: who or what is new at prediction time, and what information exists at that moment. Derive the split and the feature cut-offs from it.
  • Use pipelines. In scikit-learn, put every transform in a Pipeline and pass the pipeline to cross_val_score or GridSearchCV; use GroupKFold, StratifiedKFold and TimeSeriesSplit as the problem dictates.
  • Build a baseline first: predict the majority class, the mean, last value (time series), or a simple logistic regression. A complex model's score means little without it.
  • Look at the errors. Read 50 misclassified examples. Metrics summarise; errors explain, and they are where you find label noise and leakage.
  • Suspiciously good results are bugs until proven otherwise. If one feature carries most of the importance, or a simple model is near-perfect on a hard problem, hunt for leakage before celebrating.
  • Monitor after deployment: the offline estimate is valid only while the world matches the test distribution (data in production).

Common misconceptions

High ROC-AUC means the model is useful

ROC-AUC measures ranking across all thresholds and ignores prevalence. At 2% positives, an AUC of 0.92 can still mean precision below 20% at useful recall. Report the operating point you will actually use.

Cross-validation prevents overfitting

CV measures generalisation; it does not prevent overfitting, and if you tune many choices against it, you overfit the CV estimate itself. Hold out a test set or use nested CV.

Standardising features on the whole dataset is harmless

For a scaler on a large dataset the leak is usually tiny, which is why people get away with it; for feature selection, target encoding, oversampling or imputation with model-based methods it can be enormous. Make "fit only on the training fold" a habit for every transform.

Build it

1. Leakage by feature selection. Labels are coin flips, independent of all 5,000 features. Any accuracy above 50% is an artefact.

import numpy as np

rng = np.random.default_rng(0)
n, p, k, folds = 50, 5000, 100, 5
X = rng.normal(size=(n, p))                     # pure noise features
y = rng.integers(0, 2, n)                       # labels independent of X: true accuracy is 50%

def top_k(X, y, k):                             # filter: features most correlated with y
    Xc, yc = X - X.mean(0), y - y.mean()
    corr = np.abs(Xc.T @ yc) / (np.linalg.norm(Xc, axis=0) * np.linalg.norm(yc))
    return np.argsort(corr)[-k:]

def nearest_centroid(Xtr, ytr, Xte):
    c0, c1 = Xtr[ytr == 0].mean(0), Xtr[ytr == 1].mean(0)
    return (((Xte - c1) ** 2).sum(1) < ((Xte - c0) ** 2).sum(1)).astype(int)

def cv_accuracy(select_inside):
    idx = rng.permutation(n); accs = []
    cols_all = top_k(X, y, k)                   # WRONG: chosen using every label, test folds included
    for f in range(folds):
        te = idx[f::folds]; tr = np.setdiff1d(idx, te)
        cols = top_k(X[tr], y[tr], k) if select_inside else cols_all
        pred = nearest_centroid(X[tr][:, cols], y[tr], X[te][:, cols])
        accs.append(np.mean(pred == y[te]))
    return np.mean(accs)

wrong = [cv_accuracy(False) for _ in range(20)]
right = [cv_accuracy(True) for _ in range(20)]
print(f"select features, then CV : accuracy {np.mean(wrong):.2f}  (on pure noise!)")
print(f"select inside each fold  : accuracy {np.mean(right):.2f}")

Output:

select features, then CV : accuracy 1.00  (on pure noise!)
select inside each fold  : accuracy 0.51

2. Metrics from scratch on an imbalanced problem. 2% positives; the probabilities are the exact posterior, so they are calibrated.

import numpy as np

rng = np.random.default_rng(42)
n, prevalence = 20_000, 0.02
y = (rng.random(n) < prevalence).astype(int)
z = rng.normal(size=n) + 2.0 * y                  # a decent, imperfect score
logit = 2 * z - 2 + np.log(prevalence / (1 - prevalence))
p = 1 / (1 + np.exp(-logit))                     # the exact posterior: calibrated

def auc_roc(y, s):                                # P(score of random pos > random neg)
    r = np.argsort(np.argsort(s)) + 1             # ranks 1..n (no ties with continuous s)
    n1, n0 = y.sum(), len(y) - y.sum()
    return (r[y == 1].sum() - n1 * (n1 + 1) / 2) / (n1 * n0)

def average_precision(y, s):                      # area under the PR curve (step-wise)
    order = np.argsort(-s); hits = y[order]
    prec_at_k = np.cumsum(hits) / np.arange(1, len(y) + 1)
    return prec_at_k[hits == 1].mean()

def report(t):
    yhat = (p >= t).astype(int)
    tp, fp = np.sum((yhat == 1) & (y == 1)), np.sum((yhat == 1) & (y == 0))
    fn, tn = np.sum((yhat == 0) & (y == 1)), np.sum((yhat == 0) & (y == 0))
    prec, rec = tp / max(tp + fp, 1), tp / (tp + fn)
    print(f"t={t:<5} TP={tp:4} FP={fp:5} FN={fn:4} TN={tn:5}  acc={(tp+tn)/n:.3f}"
          f"  precision={prec:.3f} recall={rec:.3f} F1={2*prec*rec/max(prec+rec,1e-12):.3f}")

print(f"positives: {y.sum()} of {n};  'always negative' accuracy = {1 - y.mean():.3f}")
for t in (0.5, 0.2, 0.1, 0.05):
    report(t)
print(f"ROC-AUC = {auc_roc(y, p):.3f}   average precision (PR-AUC) = {average_precision(y, p):.3f}"
      f"   (random classifier: 0.5 and {y.mean():.3f})")
print(f"log loss = {-np.mean(y*np.log(p) + (1-y)*np.log(1-p)):.4f}   Brier = {np.mean((p - y)**2):.4f}")
boot = [auc_roc(y[i], p[i]) for i in (rng.integers(0, n, n) for _ in range(300))]
print("bootstrap 95%% CI for ROC-AUC: [%.3f, %.3f]" % tuple(np.percentile(boot, [2.5, 97.5])))

Output:

positives: 401 of 20000;  'always negative' accuracy = 0.980
t=0.5   TP=  77 FP=   28 FN= 324 TN=19571  acc=0.982  precision=0.733 recall=0.192 F1=0.304
t=0.2   TP= 167 FP=  247 FN= 234 TN=19352  acc=0.976  precision=0.403 recall=0.416 F1=0.410
t=0.1   TP= 221 FP=  682 FN= 180 TN=18917  acc=0.957  precision=0.245 recall=0.551 F1=0.339
t=0.05  TP= 271 FP= 1422 FN= 130 TN=18177  acc=0.922  precision=0.160 recall=0.676 F1=0.259
ROC-AUC = 0.919   average precision (PR-AUC) = 0.380   (random classifier: 0.5 and 0.020)
log loss = 0.0631   Brier = 0.0153
bootstrap 95% CI for ROC-AUC: [0.906, 0.930]

Read the output against the page. The best accuracy (0.982, at the Bayes threshold 0.5 for calibrated probabilities) beats "always negative" by 0.2 points while catching only 19% of positives. Lowering the threshold trades precision for recall; F1 peaks near 0.2, a different threshold from accuracy's. ROC-AUC matches the theoretical \(\Phi(2/\sqrt2) = 0.921\); AP of 0.38 is 19 times the random baseline but tells a much soberer story.

Things to try

  • In snippet 1, raise n to 500 and see how much the leak shrinks; then set k = 10. When is feature-selection leakage worst?
  • In snippet 1, replace feature selection with standardising on all data and check that this leak is negligible here. Why is selection so much worse than scaling?
  • In snippet 2, change prevalence to 0.5 and to 0.001: ROC-AUC barely moves; watch AP and precision.
  • Miscalibrate the scores (p = p ** 0.5) and check which numbers change: AUC and AP do not (ranking is preserved), log loss and Brier do.
  • Implement McNemar's test for two thresholds' predictions and a paired bootstrap for the difference in AUC between two noisy scores.

Check yourself

Why is the validation score of your best hyperparameter setting an optimistic estimate of its performance?

You selected that setting because it scored highest, and the score includes noise; selecting the maximum of noisy estimates picks favourable noise (the winner's curse). The more settings you tried, the larger the bias, growing like \(\sqrt{2\ln K}\) standard errors. A test set, or the outer loop of nested CV, gives an unbiased estimate.

You have 10,000 chest X-rays from 2,000 patients. How do you split, and what goes wrong if you split at random?

Split by patient (group k-fold): all images of a patient in one fold. A random split puts images of the same patient in train and test; the model can match patient-specific features (anatomy, implants, scanner settings) and test accuracy overstates performance on new patients.

A fraud model has ROC-AUC 0.95 and fraud is 0.1% of transactions. Can it be useless in practice?

Yes. At FPR 1% and TPR 80%, precision is \(\frac{0.001\times0.8}{0.001\times0.8 + 0.999\times0.01} \approx 7.4\%\): about twelve false alarms per fraud caught, at a 1% alert rate on all transactions. Whether that is useful depends on review cost; ROC-AUC alone cannot say. Look at precision at the review capacity you have.

Compute ROC-AUC by hand: positives scored \(\{0.6, 0.35\}\), negatives \(\{0.7, 0.4, 0.3\}\).

Pairs: 0.6 beats 0.4 and 0.3 (2 of 3); 0.35 beats 0.3 (1 of 3). AUC \(= 3/6 = 0.5\), no better than random at ranking, even though 0.6 is the second-highest score.

Which of these leak in 5-fold CV if done once on the full dataset beforehand: (a) dropping rows with missing labels, (b) standardising features, © target encoding a category, (d) SMOTE oversampling, (e) deduplicating exact copies?

(a) No: it uses no information about held-out labels beyond defining the dataset. (b) Mildly (fold statistics leak into training); usually small but avoidable. © Yes, severely: each row's encoding contains its own label. (d) Yes: synthetic points interpolated from a test-fold positive land in training, near the test point. (e) Deduplicating before splitting is the correct thing to do; failing to deduplicate is what leaks.

Model A: 85.0%, model B: 86.0% on the same 1,000 test examples. The discordant counts are b = 2 (A right, B wrong) and c = 12. Is B better?

McNemar: \((2-12)^2/(2+12) = 100/14 \approx 7.14\), \(p\approx0.008\): strong evidence that B is better on this distribution, even though the unpaired intervals (\(\pm2.2\) points each) overlap. Pairing removes the variance shared by examples both models get right or wrong.

Hard: why can you not simply report the standard deviation of the k fold scores divided by \(\sqrt{k}\) as the standard error of a CV estimate?

The fold estimates are not independent: any two training sets share \(\frac{k-2}{k-1}\) of their examples, so the fold scores are positively correlated and the naive formula underestimates the variance. Bengio and Grandvalet (2004) showed there is no unbiased estimator of the variance of k-fold CV that works for every distribution. Use repeated CV with corrected tests, a separate test set with a binomial or bootstrap interval, or accept the fold spread as a rough indicator only.

Go deeper

Papers

Videos and lectures

Articles and blog posts

Courses and books

Code

Where this leads