Slides · Evaluation, statistics and data

Evaluation, leakage and imbalance: validation design, metrics, thresholds and rare classes

Evaluation, leakage and imbalance

Validation design, the ways a score lies, metrics, thresholds from costs, and rare classes.

Concept

Why this is worth 90 minutes

  • A model can look excellent offline and fail in production, and the usual cause is how it was measured, not how it was built.
  • Interviewers use this to separate mid-level from senior candidates (common industry pattern): it cannot be memorised, you have to reason.
  • Think of evaluation as a rehearsal of deployment: same information, same independence, same cost, same decision rule.

Four things you will be able to do:

  1. Choose a validation scheme from how the rows relate.
  2. Name each kind of leakage and its repair.
  3. Pick metrics and a threshold from error costs.
  4. Handle a rare class in the right order and analyse errors by slice.

Compare

Choosing the splitter

Rows areUseGuarantee
Independentk-foldSimple
One class rareStratifiedSame class mix per fold
Several rows per entityGroupNo group on both sides
Time-orderedForward-chainingTrain on the past only
  • Stratified, 45 against 5, three folds: test counts (15,2),(15,2),(15,1)(15,2),(15,2),(15,1).
  • Time series, 12 rows, test blocks of 2, gap 2: train rows 0 to 3 with test rows 6, 7; then 0 to 5 with 8, 9; then 0 to 7 with 10, 11.
  • Picking the best of many configurations on the same folds is optimistic: use a test set once, or nested cross-validation.
  • Small data, wide error bars: about 10 points at 100 samples in Varoquaux’s neuroimaging experiments.

Sources1 Cross-validation: evaluating estimator performance2 TimeSeriesSplit3 Cross-validation failure: small sample sizes lead to large error bars4 Assessing and tuning brain decoders: cross-validation, caveats, and guidelines

Diagram

The decision, in order

Diagram: Check for time order first, then for repeated entities, then for a rare class.

yes

no

yes

no

yes

no

How are the rows related?

Time order or
predicting the future?

Forward-chaining
with a gap

Several rows
per entity?

Group k-fold

Rare class?

Stratified k-fold

k-fold

Diagram summary: Check for time order first, then for repeated entities, then for a rare class. The first structure you find decides the splitter, and the test set is looked at once at the end.

Check yourself

Check: next-month churn

You predict next-month churn from monthly snapshots of 20,000 customers over two years. Which splitter, and when would you also group by customer?

Answer

Forward-chaining: train on earlier months, test on later ones. Reusing the same customers across the boundary is the realistic rehearsal, because next month you score customers you already know. Group the customers only if the model must generalise to customers it has never seen. A random row-level split would train on the future.

Compare

Five ways a score lies

KindRepair
Target: a feature known only after the outcomePrediction timestamp, point-in-time features
Preprocessing fitted before the splitPipeline fitted per fold
Shared entities or duplicatesGroup k-fold, de-duplicate
Temporal: random split of time dataForward-chaining
Resampling before the splitResample the training fold only
  • Red flags: too good a score, one feature dominating, a gap between cross-validation and a later holdout.

Sources5 Common pitfalls and recommended practices (data leakage)6 Common pitfalls and recommended practices (imbalanced-learn)

Worked example

Leaks, measured

ExperimentLeakyHonest
Select 10 of 2,000 noise features first (accuracy)0.8170.492
Patient rows on both sides, random labels (accuracy)0.9440.490
Random walk, random split against forward (error)0.842.61
Duplicate first, then cross-validate (balanced accuracy)0.9720.495
  • Honest means chance for noise, and a larger error when forecasting is really forecasting.
  • In each case the leaky number comes from the same model on the same data: only the order of steps or the split changed.

Check yourself

Check: an unsupervised scaler

A teammate fits a StandardScaler on all rows before splitting “because it never looks at the label”. Is that a problem?

Answer

Yes, a small one that can grow. The means and standard deviations include the test rows, so information about them reaches training even without labels. The rule is the same for every fitted step: learn it from the training part and apply it to held-out rows, which a pipeline does inside each fold.

Worked example

Accuracy under imbalance

10,000 transactions, 20 fraud.

FlaggedCaughtAccuracyPrecisionRecallF1F_1Cost
Model A40150.99700.3750.750.50026,250
Model B60180.99560.3000.900.45012,100
Never flags000.998n/a0n/a100,000
  • Cost: 5,000 per miss and 50 per false alarm.
  • Accuracy and F1F_1 prefer A; the cost prefers B.

Math

ROC-AUC against average precision

AP=∑n(Rn−Rn−1) Pn\mathrm{AP}=\sum_n (R_n-R_{n-1})\,P_n
Negatives per 100 positivesROC-AUCAP
1000.9030.910
49,9000.9110.091
  • The same ranker: ROC-AUC compares positives with negatives, so extra negatives of the same kind barely move it (no change in expectation).
  • Average precision falls because the same false-positive rate now means thousands of false alarms.
  • A constant score has an AP equal to the positive rate, 0.0020 here.

Sources7 Metrics and scoring: quantifying the quality of predictions8 The Precision-Recall Plot Is More Informative than the ROC Plot When Evaluating Binary Classifiers on Imbalanced Datasets

Check yourself

Check: AUC of 0.95

A model has ROC-AUC 0.95 on data with 0.1% positives. What do you ask for before calling it good?

Answer

Precision and recall at the threshold you would actually use, the average precision against the 0.001 baseline, and the cost of the false alarms. A high ROC-AUC says the ranking is good in general and says nothing about how many alerts are false.

Math

The threshold from costs

p>CFPCFP+CFNp>\frac{C_{FP}}{C_{FP}+C_{FN}}
  • Valid for calibrated probabilities only. A miss of 5,000 and a false alarm of 50 give 0.0099.
  • Cost per row at threshold 0.5, 0.1 and 0.0099: 191.23, 37.18 and 14.54, with precision 0.623, 0.350 and 0.201.
  • The cheapest policy has 20% precision, because misses are 100 times dearer.
  • With limited capacity, pick the threshold that matches the alert volume.

Source9 Tuning the decision threshold for class prediction

Check yourself

Check: another cost pair

A missed case costs 200 and a false alarm costs 8, with calibrated probabilities. Where do you cut?

Answer

At 8 divided by 208, about 0.038. Below that probability, the expected cost of staying silent is smaller than the cost of raising the alert.

Concept

Calibration

  • Among cases scored near 0.8, about 80% should be positive. Check with reliability bins, ECE, log loss.
  • Ranking and probability are separate: doubling logits left ROC-AUC at 0.8346 and moved ECE from 0.011 to 0.093 and log loss from 0.500 to 0.572.
  • Sigmoid for small samples, isotonic above about 1,000, temperature scaling for networks; fit on held-out data.
  • Class weights and resampling distort probabilities and keep the ranking: weight 99 turns a true 0.01 into 0.500.

Sources10 Probability calibration11 On Calibration of Modern Neural Networks

Diagram

The imbalance order

Diagram: Cheap and reversible steps come first.

Baseline and metric

Stratify, natural-rate test

Class weights

Tune threshold

Resample training fold only

Recalibrate

Anomaly framing, more labels

Diagram summary: Cheap and reversible steps come first. Resampling comes late and only inside training folds, and probabilities are recalibrated before use.

Concept

Resampling and SMOTE

  • Undersampling throws away majority rows. Random oversampling repeats minority rows. SMOTE interpolates between a minority sample and its nearest minority neighbours.
  • Caveats: synthetic points are not observations, plain SMOTE cannot handle categorical features, and it may connect inliers and outliers.
  • Do it inside each training fold. On noise with 15 positives in 300 rows: duplicate first 0.972, inside folds 0.495.
  • Downsampling negatives 25 times turns a 99 to 1 split into about 20% positives; upweight to correct the bias.
  • Balanced class weights, n/(k nc)n/(k\,n_c), give 0.5051 and 50.0 for 99 negatives and 1 positive.

Sources12 SMOTE: Synthetic Minority Over-sampling Technique13 Over-sampling (imbalanced-learn user guide)6 Common pitfalls and recommended practices (imbalanced-learn)14 LogisticRegression (class_weight parameter)15 Datasets: Imbalanced datasets (Machine Learning Crash Course)

Check yourself

Check: the validation fold

A colleague resamples the validation fold to 50/50 “so the metric is fair”. What goes wrong?

Answer

Live traffic arrives at the natural rate, so a 50/50 validation fold misstates precision and the expected cost. Resample inside the training fold only, and score on folds that keep the real class mix.

Worked example

Baselines and error analysis

  • Baselines: DummyClassifier (most frequent: accuracy 0.998 here), a constant score (AP 0.0020), the base-rate log loss (0.0144), a simple model, the current rule.
  • Slices: 9,000 rows at 95% and 1,000 rows at 70% make 92.5% overall.
  • Read the worst errors, group them by cause, fix the biggest group first.
  • Regression: MAE 4.8 against RMSE 8.99 for errors (1,1,1,1,20)(1,1,1,1,20); MAPE blows up near zero.

Source16 DummyClassifier

Code

Homework: the evaluation toolkit

Python

def stratified_kfold(labels, k):
    """k (train, test) index pairs that keep the class mix."""

def average_precision(y_true, scores):
    """Sum of (recall step) x (precision), no interpolation."""

def balance_by_duplication(indices, labels):
    """Balance a TRAINING fold only."""
  • The homework also has group and forward-chaining splitters, ROC-AUC, a cost threshold, ECE and two leak detectors.

Summary

Recap

  • The splitter follows the rows’ structure; touch the test set once.
  • Leakage hides in the order of steps: fit, select and resample inside the training fold, keep entities together, split time forward.
  • Accuracy lies under imbalance; ROC-AUC ignores prevalence, average precision does not; the cost threshold needs calibrated probabilities.
  • Weights and resampling shift probabilities, so recalibrate. Report against a baseline and slice the errors.

References

References & Sources (1 of 4)

  1. Cross-validation: evaluating estimator performance (opens in a new tab)

    scikit-learn2026Documentation

    Used for Stratified, group and time-series splitters with example outputs (45 against 5 stratified counts, group example, TimeSeriesSplit), no shuffling by default, preprocessing learnt from the training set, k-fold on time series gives unreasonable correlation, the warning that stratification can shrink the spread across folds. The empty folds in the docs example come from class-sorted rows with no shuffling by default; shuffle=True with a fixed random_state is advised for independent rows, never for time-ordered data. The homework stratified splitter is unshuffled.

  2. TimeSeriesSplit (opens in a new tab)

    scikit-learn2026Documentation

    Used for The test_size default and the gap parameter, with the 12-sample examples used in the lesson.

  3. Cross-validation failure: small sample sizes lead to large error bars (opens in a new tab)

    Gaël Varoquaux2017arXiv:1706.07581Preprint

    Used for Cross-validation error bars of roughly 10 points at 100 samples in neuroimaging; the standard error across folds strongly underestimates them (abstract).

  4. Assessing and tuning brain decoders: cross-validation, caveats, and guidelines (opens in a new tab)

    Gaël Varoquaux, Pradeep Reddy Raamana, Denis Engemann, Andrés Hoyos-Idrobo, et al.2016arXiv:1606.05201Preprint

    Used for Nested cross-validation avoids circularity bias when tuning, though sane defaults may sometimes be better (abstract).

  5. Common pitfalls and recommended practices (data leakage) (opens in a new tab)

    scikit-learn2026Documentation

    Used for Definition of data leakage, the rule to split first and fit transformations on training data only, and the feature-selection example (200 samples, 10,000 random features, 0.76 against 0.5).

References

References & Sources (2 of 4)

  1. Common pitfalls and recommended practices (imbalanced-learn) (opens in a new tab)

    imbalanced-learn2026Documentation

    Used for Resampling the entire dataset before splitting causes leakage; the example numbers (0.724 and 0.698 leaky; 0.732 and 0.727 with a pipeline); a pipeline resamples inside each training fold.

  2. Metrics and scoring: quantifying the quality of predictions (opens in a new tab)

    scikit-learn2026Documentation

    Used for Precision, recall and F-beta definitions, balanced accuracy, average precision (no linear interpolation, random baseline is the positive rate), roc_auc_score, log loss, Brier score, MAE and squared error as the consistent losses for the median and mean. Read up to the first 100,000 characters.

  3. The Precision-Recall Plot Is More Informative than the ROC Plot When Evaluating Binary Classifiers on Imbalanced Datasets (opens in a new tab)

    Takaya Saito, Marc Rehmsmeier2015PLOS ONE 10(3): e0118432Paper

    Used for Precision-recall plots are more informative than ROC plots on imbalanced datasets (abstract and conclusion).

  4. Tuning the decision threshold for class prediction (opens in a new tab)

    scikit-learn2026Documentation

    Used for The default 0.5 threshold is hard-coded, TunedThresholdClassifierCV, never tune the threshold on the data used to train the classifier, a cost-sensitive example with a tuned threshold near 0.02.

  5. Probability calibration (opens in a new tab)

    scikit-learn2026Documentation

    Used for Definition of a well-calibrated classifier, reliability curves, Platt sigmoid and isotonic regression with the sample-size guidance, ties and AUC, fitting the calibrator on independent data, which models tend to be miscalibrated, temperature scaling.

References

References & Sources (3 of 4)

  1. On Calibration of Modern Neural Networks (opens in a new tab)

    Chuan Guo, Geoff Pleiss, Yu Sun, Kilian Q. Weinberger2017ICML 2017 (arXiv:1706.04599)Paper

    Used for Modern neural networks are poorly calibrated; temperature scaling is a simple and effective post-processing fix (abstract).

  2. SMOTE: Synthetic Minority Over-sampling Technique (opens in a new tab)

    N. V. Chawla, K. W. Bowyer, L. O. Hall, W. P. Kegelmeyer2002Journal of Artificial Intelligence Research 16, 321-357 (arXiv:1106.1813)Paper

    Used for Definition of imbalance and the SMOTE method; over-sampling with synthetic examples combined with under-sampling beat under-sampling alone in the authors' experiments (abstract).

  3. Over-sampling (imbalanced-learn user guide) (opens in a new tab)

    imbalanced-learn2026Documentation

    Used for SMOTE interpolates between a sample and its nearest neighbours; it may connect inliers and outliers; plain SMOTE cannot handle categorical features and SMOTENC exists for mixed data; random oversampling repeats samples.

  4. LogisticRegression (class_weight parameter) (opens in a new tab)

    scikit-learn2026Documentation

    Used for The balanced class_weight formula n_samples / (n_classes * np.bincount(y)).

  5. Datasets: Imbalanced datasets (Machine Learning Crash Course) (opens in a new tab)

    Google for Developers2026Documentation

    Used for Examples of extreme imbalance (below 0.1%), downsampling and upweighting by the same factor, the 99/1 split becoming about 80/20 when downsampling by 25, and the prediction bias it introduces.

References

References & Sources (4 of 4)

  1. DummyClassifier (opens in a new tab)

    scikit-learn2026Documentation

    Used for DummyClassifier as a baseline and its strategies (most_frequent, prior, stratified, uniform, constant).