Slides · Evaluation, statistics and data
Evaluation, leakage and imbalance: validation design, metrics, thresholds and rare classes
1 / 24
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:
- Choose a validation scheme from how the rows relate.
- Name each kind of leakage and its repair.
- Pick metrics and a threshold from error costs.
- Handle a rare class in the right order and analyse errors by slice.
Compare
Choosing the splitter
| Rows are | Use | Guarantee |
|---|---|---|
| Independent | k-fold | Simple |
| One class rare | Stratified | Same class mix per fold |
| Several rows per entity | Group | No group on both sides |
| Time-ordered | Forward-chaining | Train on the past only |
- Stratified, 45 against 5, three folds: test counts (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.
Sources[1] Cross-validation: evaluating estimator performance[2] TimeSeriesSplit[3] Cross-validation failure: small sample sizes lead to large error bars[4] Assessing and tuning brain decoders: cross-validation, caveats, and guidelines
Diagram
The decision, in order
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
| Kind | Repair |
|---|---|
| Target: a feature known only after the outcome | Prediction timestamp, point-in-time features |
| Preprocessing fitted before the split | Pipeline fitted per fold |
| Shared entities or duplicates | Group k-fold, de-duplicate |
| Temporal: random split of time data | Forward-chaining |
| Resampling before the split | Resample the training fold only |
- Red flags: too good a score, one feature dominating, a gap between cross-validation and a later holdout.
Sources[5] Common pitfalls and recommended practices (data leakage)[6] Common pitfalls and recommended practices (imbalanced-learn)
Worked example
Leaks, measured
| Experiment | Leaky | Honest |
|---|---|---|
| Select 10 of 2,000 noise features first (accuracy) | 0.817 | 0.492 |
| Patient rows on both sides, random labels (accuracy) | 0.944 | 0.490 |
| Random walk, random split against forward (error) | 0.84 | 2.61 |
| Duplicate first, then cross-validate (balanced accuracy) | 0.972 | 0.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.
| Flagged | Caught | Accuracy | Precision | Recall | F1 | Cost | |
|---|---|---|---|---|---|---|---|
| Model A | 40 | 15 | 0.9970 | 0.375 | 0.75 | 0.500 | 26,250 |
| Model B | 60 | 18 | 0.9956 | 0.300 | 0.90 | 0.450 | 12,100 |
| Never flags | 0 | 0 | 0.998 | n/a | 0 | n/a | 100,000 |
- Cost: 5,000 per miss and 50 per false alarm.
- Accuracy and F1 prefer A; the cost prefers B.
Math
ROC-AUC against average precision
AP=n∑(Rn−Rn−1)Pn| Negatives per 100 positives | ROC-AUC | AP |
|---|---|---|
| 100 | 0.903 | 0.910 |
| 49,900 | 0.911 | 0.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.
Sources[7] Metrics and scoring: quantifying the quality of predictions[8] 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>CFP+CFNCFP- 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.
Source[9] 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.
Sources[10] Probability calibration[11] On Calibration of Modern Neural Networks
Diagram
The imbalance order
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/(knc), give 0.5051 and 50.0 for 99 negatives and 1 positive.
Sources[12] SMOTE: Synthetic Minority Over-sampling Technique[13] 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); MAPE blows up near zero.
Source[16] 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)
Cross-validation: evaluating estimator performance (opens in a new tab)
scikit-learn2026Documentation
https://scikit-learn.org/stable/modules/cross_validation.html
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.
TimeSeriesSplit (opens in a new tab)
scikit-learn2026Documentation
https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.TimeSeriesSplit.html
Used for The test_size default and the gap parameter, with the 12-sample examples used in the lesson.
Cross-validation failure: small sample sizes lead to large error bars (opens in a new tab)
Gaël Varoquaux2017arXiv:1706.07581Preprint
https://arxiv.org/abs/1706.07581
Used for Cross-validation error bars of roughly 10 points at 100 samples in neuroimaging; the standard error across folds strongly underestimates them (abstract).
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
https://arxiv.org/abs/1606.05201
Used for Nested cross-validation avoids circularity bias when tuning, though sane defaults may sometimes be better (abstract).
Common pitfalls and recommended practices (data leakage) (opens in a new tab)
scikit-learn2026Documentation
https://scikit-learn.org/stable/common_pitfalls.html
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)
Common pitfalls and recommended practices (imbalanced-learn) (opens in a new tab)
imbalanced-learn2026Documentation
https://imbalanced-learn.org/stable/common_pitfalls.html
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.
Metrics and scoring: quantifying the quality of predictions (opens in a new tab)
scikit-learn2026Documentation
https://scikit-learn.org/stable/modules/model_evaluation.html
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.
Takaya Saito, Marc Rehmsmeier2015PLOS ONE 10(3): e0118432Paper
https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0118432
Used for Precision-recall plots are more informative than ROC plots on imbalanced datasets (abstract and conclusion).
Tuning the decision threshold for class prediction (opens in a new tab)
scikit-learn2026Documentation
https://scikit-learn.org/stable/modules/classification_threshold.html
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.
Probability calibration (opens in a new tab)
scikit-learn2026Documentation
https://scikit-learn.org/stable/modules/calibration.html
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)
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
https://arxiv.org/abs/1706.04599
Used for Modern neural networks are poorly calibrated; temperature scaling is a simple and effective post-processing fix (abstract).
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
https://arxiv.org/abs/1106.1813
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).
Over-sampling (imbalanced-learn user guide) (opens in a new tab)
imbalanced-learn2026Documentation
https://imbalanced-learn.org/stable/over_sampling.html
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.
LogisticRegression (class_weight parameter) (opens in a new tab)
scikit-learn2026Documentation
https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html
Used for The balanced class_weight formula n_samples / (n_classes * np.bincount(y)).
Datasets: Imbalanced datasets (Machine Learning Crash Course) (opens in a new tab)
Google for Developers2026Documentation
https://developers.google.com/machine-learning/crash-course/overfitting/imbalanced-datasets
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)
DummyClassifier (opens in a new tab)
scikit-learn2026Documentation
https://scikit-learn.org/stable/modules/generated/sklearn.dummy.DummyClassifier.html
Used for DummyClassifier as a baseline and its strategies (most_frequent, prior, stratified, uniform, constant).
Keys: ← → move, Home End first and last, F full screen.