Evaluation, leakage and imbalance: validation design, metrics, thresholds and rare classes
- Advanced
- 1 h 30 min
- Lesson 1 of 3 in Evaluation, statistics and data
- Last verified
Select text in the lesson first to keep it with your note. With the keyboard, move focus here and press the button: the note goes with the section you are reading.
In this module
On this page
Before you start
- Completed:The learning problem: generalization, bias-variance and regularizationML foundations
- Completed:Linear models, loss functions and gradient descentML foundations
You will be able to
- Choose a validation scheme (stratified, group, time-series or plain k-fold) from how the rows of a dataset relate to each other, and explain why the test set is used once.
- Name the main kinds of leakage (target, preprocessing before the split, shared entities or duplicates, temporal, resampling before the split), say how each shows up, and say how to prevent it.
- Pick metrics for a classifier (accuracy, precision, recall, F1, ROC-AUC against PR-AUC, log loss, calibration) and for a regressor, compute them from a confusion matrix, and choose a decision threshold from error costs.
- Handle a rare class in the right order (baseline, metric, class weights, threshold, resampling inside the folds, recalibration), state the caveats of SMOTE, and run error analysis by slice.
Concept
The first lesson gave the three-way split and warned about leaks. The second introduced the loss functions that models are trained on. This lesson is about the other half of the job: measuring a model honestly. It covers how to split data so the score means what you think it means, the ways a score quietly lies (leakage), which metric answers which question, how to turn a probability into a decision using costs, and what to do when one class is rare.
| Question | Tool in this lesson |
|---|---|
| How should I split the rows? | Stratified, group or forward-chaining cross-validation |
| Why is my score too good? | The leakage catalogue and its detectors |
| Is 99.8% accuracy good? | Confusion matrix, PR-AUC, a baseline |
| Do the probabilities mean anything? | Log loss, reliability bins, calibration |
| Where do I cut the score? | A threshold from error costs |
| One class is rare | Class weights, inside-fold resampling, recalibration |
| Where does it fail? | Error analysis by slice |
Why It Matters
Evaluation mistakes are the most common reason a model that looked excellent offline disappoints in production. Interviewers treat this as a differentiator for mid-level and senior roles (common industry pattern), because it cannot be memorised: you have to reason about what information the model had, what the metric rewards and what a mistake costs. A candidate who answers “99% accuracy” with “compared with what, and at which threshold?” has shown the habit that matters.
Mental Model
Evaluation is a rehearsal of deployment. A good rehearsal matches the real performance in four ways: the model sees only what it will know at prediction time, the unit that is independent in the real world (a patient, a user, a week) is independent in the split, the metric rewards what the business rewards, and the decision rule is the one that will be used. Every rule in this lesson repairs one of those four. When a score looks too good, ask which of the four the rehearsal broke.
Splits and cross-validation
The three-way split from the first lesson (train fits, validation chooses, test judges once) is the frame. Cross-validation spends the data more efficiently by rotating the validation fold. What matters is how the rows are assigned to folds, because the folds must imitate the gap between training data and future data.
| Rows are | Use | Why |
|---|---|---|
| Independent, classes balanced enough | k-fold | The simplest honest option |
| Independent, one class rare | Stratified k-fold | Every fold keeps about the same class mix |
| Several rows per person, device or patient | Group k-fold | A group never sits on both sides of a split |
| Ordered in time | Forward-chaining (time-series split) | Train on the past, test on the future |
Stratified. Each fold keeps roughly the class proportions of the whole set (scikit-learn, Cross-validation). The documentation’s example has 50 samples, 45 of one class and 5 of the other, in 3 folds. Stratified folds test on samples of the two classes, and the script reproduces this with the helper written for the homework. Plain k-fold on the same data, in the documentation’s output, produced test folds with no positives at all in two of the three, so those folds cannot score recall. That happens because the rows are sorted by class and neither KFold nor StratifiedKFold shuffles by default. For independent rows, pass shuffle=True with a fixed random_state; never shuffle time-ordered data. The homework’s stratified splitter is unshuffled on purpose, so its output is exactly reproducible. The same page warns that stratification was introduced to work around engineering problems and can artificially shrink the spread of the metric across folds.
Group. Group k-fold guarantees that no group appears in both train and test. For ten rows in groups and three folds, the test sets are , and : each group is tested exactly once. The fold sizes differ because the groups differ, and the library documentation points to a stratified-group variant when class proportions must also be balanced (scikit-learn, Cross-validation).
Time series. Ordinary k-fold assumes the samples are independent and identically distributed, and on time series it gives “unreasonable correlation between training and testing instances” (scikit-learn, Cross-validation). The forward-chaining splitter trains on an initial stretch and tests on the next block, repeatedly, and successive training sets are supersets of earlier ones. A gap option skips rows between the end of training and the start of the test block (scikit-learn, TimeSeriesSplit). With 12 rows, 3 splits, test blocks of 2 and a gap of 2, the script prints training rows to against test rows , then to against , then to against . A gap is useful when a label or feature is computed over a window that reaches ahead of the row’s timestamp (common practice).
The test set is touched once. Every time you look at a score and change something, the validation set leaks a little into your choices. The test set exists to be looked at after all choices are made. Reporting the best cross-validation score as the final estimate is optimistic for the same reason, since you picked it for being best. When you tune hyperparameters and also want an honest estimate, nested cross-validation is the usual way to avoid that circularity: Varoquaux et al. report that it avoids the circularity bias of tuning and scoring on the same folds, while noting that sensible defaults can sometimes do better than tuning (Varoquaux et al. 2016).
Small data gives wide error bars. In neuroimaging experiments Varoquaux found that cross-validated accuracy with around 100 samples has error bars of about ±10 points, and that the standard error across folds strongly underestimates it (Varoquaux 2017). That result is from one field, but the lesson transfers: do not rank two models by a one-point gap on a few hundred rows, and report a spread, not a single number.
Leakage and its main forms
Leakage is information that would not be available at prediction time getting into the model-building process, which gives an overly optimistic estimate and poorer performance on genuinely new data (scikit-learn, Common pitfalls). The score does not fail loudly. It looks wonderful, and the damage shows up in production.
| Kind | Example | Tell-tale sign | Prevention |
|---|---|---|---|
| Target leakage | A feature recorded after the outcome, such as a discharge disposition when predicting readmission, or “account closed” when predicting churn | One feature dominates; the model is suspiciously good | Fix a prediction time and audit every feature against it |
| Preprocessing before the split | Scaler, imputer, encoder or feature selection fitted on all rows | Cross-validation beats the true holdout | Fit inside each training fold with a pipeline |
| Shared entities and duplicates | The same patient in train and test; copies of a row on both sides | Row-level CV far above group CV | Group k-fold; remove or group duplicates |
| Temporal leakage | A random split of time-ordered data; a feature aggregated over future rows | Performance collapses on the next period | Forward-chaining split; point-in-time features |
| Resampling before the split | Oversampling or SMOTE applied to all the data, then split | Minority-class recall unrealistically high | Resample the training fold only |
The examples in the first row are illustrative; the rest of this section measures the other four on data you can run.
Preprocessing before the split
The rule from the scikit-learn documentation is to split first and fit every transformation on the training part only (scikit-learn, Common pitfalls). It applies to scalers, imputers and PCA, and to feature selection too. The documentation’s example has 200 samples and 10,000 random features with a target that is pure noise. Selecting 25 features on all the data before the split gives a test accuracy of 0.76 against about 0.5 when selection sees only the training rows.
The script repeats this with its own sizes: 100 rows, 2,000 noise features, 10 kept, a nearest-centroid classifier, 20 repeats. Selecting on all rows gives a test accuracy of 0.817. Selecting on the training rows only gives 0.492, which is chance, the honest answer for noise. The leak is large because with 2,000 candidates, some features correlate with the labels of the test rows by luck, and choosing them using those labels hands the model the answer.
Shared entities and duplicates
If one patient contributes five visits, a random row-level split puts some visits in training and others in test. A flexible model recognises the patient. The script builds 100 patients with five rows each, makes each patient’s label a coin flip, so no feature can truly predict it, and scores a 1-nearest-neighbour classifier over 5 repeats. Row-level 5-fold gives accuracy 0.944, with about 65 of the 100 patients on both sides of fold 0. Group 5-fold gives 0.490 with no patient on both sides: chance, which is the truth. The same mechanism works for duplicated rows, and the same fix applies: split by the unit that is independent in the real world.
Temporal leakage
On a random walk of 300 steps, predict each value from the nearest training time step. A random 5-fold split has an average absolute error of 0.84, because every test point has a training neighbour one or two steps away. Forward-chaining with five splits (test blocks of 50) gives 2.61, which is what predicting the future from the past actually costs. The random split measured interpolation, not forecasting.
Resampling before the split
Oversampling creates copies of minority rows. If that happens before the split, copies land on both sides. The imbalanced-learn documentation shows a related effect with a random under-sampler and a gradient-boosting classifier on the adult census data. Resampling the whole dataset before cross-validation gave a cross-validated balanced accuracy of 0.724 against 0.698 on a left-out set; with the resampler inside a pipeline the two agreed (0.732 against 0.727). The page names two problems with resampling first: the held-out folds no longer have the natural class distribution, and the resampler may use information from samples that later serve as test data (imbalanced-learn, Common pitfalls). Under-sampling creates no copies, so the script’s own experiment illustrates the copy mechanism that over-sampling adds. The script’s own version uses pure noise with 15 positives in 300 rows: duplicating first and then cross-validating a 1-nearest-neighbour gives a balanced accuracy of 0.972 (5 seeds), with about half of the validation rows having an exact copy among the training rows of that fold. Resampling inside each training fold gives 0.495. The number that should be reported is the second.
Finding the leak
Treat these as red flags: a validation score that is too good for the problem, one feature carrying most of the importance, and a large gap between cross-validation and a later holdout. Then run the cheap checks. Look for test rows that exactly duplicate training rows, look for group ids on both sides of a split (both are homework functions), and ask for every feature when it becomes known.
Metrics for classification
Start from the confusion matrix, which counts predictions against truth.
| Predicted positive | Predicted negative | |
|---|---|---|
| Actual positive | TP (hit) | FN (miss) |
| Actual negative | FP (false alarm) | TN |
| Symbol | Meaning |
|---|---|
| Precision | Of the cases flagged, the share that are real: purity |
| Recall | Of the real cases, the share found: coverage |
| The harmonic mean of the two; it is low if either is low |
The scikit-learn documentation gives the more general , where a larger weights recall more (scikit-learn, Metrics).
Accuracy lies under imbalance
Take 10,000 transactions of which 20 are fraud. Model A flags 40 and catches 15: . Its accuracy is 0.9970, precision 0.375, recall 0.75 and . A model that never flags anything has accuracy 0.998 and recall 0, so the useless model beats the useful one on accuracy.
Model B flags 60 and catches 18: accuracy 0.9956, precision 0.300, recall 0.90, . Accuracy and both say B is worse. If a miss costs 5,000 units and a false alarm 50, the total cost is 26,250 for A and 12,100 for B, so B is better for the business. No metric is better than the others in general; the right one is the one that matches the cost of each error. Balanced accuracy, the average of recall over the classes, is one cheap guard against accuracy’s blind spot (scikit-learn, Metrics).
ROC-AUC against PR-AUC
Both metrics score a ranking, not a single threshold. ROC-AUC is the probability that a randomly chosen positive is scored above a randomly chosen negative (ties count half). It depends only on how the two classes’ scores compare, so it does not change when you add more negatives of the same kind. That is its strength and its trap. Average precision (the usual PR-AUC) is , with and the precision and recall at the th threshold; scikit-learn does not interpolate linearly, which it describes as overly optimistic, and a random ranking scores the positive rate (scikit-learn, Metrics).
The script uses the same 100 positives (scores from a normal with mean 2) against either 100 or 49,900 negatives (normal with mean 0):
| Negatives | Positive rate | ROC-AUC | AP | Precision at score | Recall at score |
|---|---|---|---|---|---|
| 100 | 50% | 0.903 | 0.910 | 0.830 | 0.83 |
| 49,900 | 0.2% | 0.911 | 0.091 | 0.010 | 0.83 |
The ranker is equally good in both rows, so ROC-AUC barely moves (0.903 against 0.911; in expectation it does not change). But with 49,900 negatives, a threshold that catches 83% of positives also flags thousands of negatives, so precision falls to 0.010 and AP falls to 0.091. A constant score gets an AP of 0.0020 here, the positive rate, so 0.091 is much better than chance and still far from useful. Saito and Rehmsmeier reach the same conclusion on imbalanced data and recommend precision-recall plots as the more informative view, because a precision-recall plot shows the share of true positives among the positive predictions, which is what you will experience in operation (Saito and Rehmsmeier 2015). Two cautions. AP is not comparable across datasets with different positive rates, since its baseline moves. And ROC-AUC is not wrong: it answers “how well does it rank?”, and that is the right question when the cost of false alarms is small.
Log loss and the Brier score
AUC and AP use only the order of the scores. When the probabilities themselves drive decisions, use a metric that scores them. Log loss is the cross-entropy from the second lesson, ; it is non-negative and punishes a confident wrong answer very heavily. The Brier score is the squared error between the probability and the 0 or 1 outcome (scikit-learn, Metrics). Both mix calibration with discrimination, so a lower value does not by itself prove better calibration (scikit-learn, Calibration).
Calibration
A classifier is calibrated when, among the cases it scores near 0.8, about 80% are positive (scikit-learn, Calibration). It matters whenever a score is used as a probability: pricing, expected loss, clinical risk, combining models and cost-based thresholds. For pure ranking, such as showing the top 10 items, it matters much less (common practice).
To check, bin the predictions and compare each bin’s mean prediction with its fraction of positives (a reliability diagram). The expected calibration error summarises this as
where is the number of rows in bin , the fraction of positives and the mean predicted probability. This is the equal-width binned version used in the homework (the number of bins is a choice that changes the value).
Ranking and probability quality are separate. In the script, true probabilities are used to draw labels for 20,000 rows. The calibrated scores have ECE 0.011 and log loss 0.500. Doubling every logit makes the model overconfident: ECE 0.093 and log loss 0.572, while ROC-AUC is 0.8346 for all three versions, because the order did not change. Halving the logits restores ECE 0.011 and log loss 0.500. A single-parameter rescaling of this kind, fitted on held-out data, is temperature scaling; Guo et al. found modern neural networks to be poorly calibrated and temperature scaling to be a simple and effective fix (Guo et al. 2017).
Two standard calibrators exist. Platt’s sigmoid is a two-parameter logistic map, most effective for small samples or an under-confident model, but it assumes symmetric errors, which can be a problem for highly imbalanced data. Isotonic regression fits any monotonic distortion but overfits small datasets; the documentation’s rule of thumb is that it does as well or better with more than about 1,000 samples, and it can introduce ties that change ROC-AUC (scikit-learn, Calibration). The calibrator must be fitted on data that the classifier was not trained on. Logistic regression is often reasonably calibrated by itself, naive Bayes tends to push probabilities to 0 or 1, and random forests and max-margin models give sigmoid-shaped curves (same page).
Weights and resampling distort probabilities. If you train with positives weighted by , the odds of a well-specified model are multiplied by (derived here): , so a true probability comes out as . With a true 0.01 becomes 0.500. Downsampling negatives by 25 turns a 99 to 1 split into 20.2% positives in the script’s arithmetic, which matches the roughly 80 to 20 split in Google’s course, whose advice is to upweight the downsampled class to correct the resulting prediction bias (Google, Imbalanced datasets). The ranking survives, so AUC and AP are unaffected; the probabilities do not, so recalibrate before using a cost-based threshold or quoting a risk.
Choosing the threshold from costs
A classifier outputs a score. A decision needs a cut. The default of 0.5 is hard-coded in libraries and, in the scikit-learn documentation’s words, is “most certainly not ideal for most use cases” (scikit-learn, Threshold tuning). With calibrated probabilities the cost-minimising cut follows from comparing two expected costs. Predicting negative costs in expectation, and predicting positive costs . Predict positive when the second is smaller:
| Symbol | Meaning |
|---|---|
| Calibrated probability of the positive class | |
| Cost of a missed positive | |
| Cost of a false alarm |
With a miss costing 5,000 and a false alarm 50, the threshold is . The script makes 20,000 rows with calibrated probabilities and a 6.2% positive rate, and totals the cost per row:
| Threshold | Cost per row | Precision | Recall |
|---|---|---|---|
| 0.5 | 191.23 | 0.623 | 0.388 |
| 0.1 | 37.18 | 0.350 | 0.897 |
| 0.0099 (formula) | 14.54 | 0.201 | 0.993 |
The best threshold on a 0.001 grid was 0.008 at 14.14, close to the formula; the small gap is sampling noise in a finite sample. The cheapest policy has 20% precision. That looks poor and is right, because a miss is 100 times worse than a false alarm. Two practical points. The formula assumes calibrated probabilities, which is why calibration comes first. And real systems often have a capacity limit, such as a review team that can read the top 1% of cases: then choose the threshold that gives that alert volume and report precision and recall at it (common practice). scikit-learn’s TunedThresholdClassifierCV automates the search with cross-validation, and warns never to train a classifier and tune its threshold on the same data (scikit-learn, Threshold tuning).
Regression metrics
For a numeric target, the choice is again about what an error costs.
MAE treats every unit of error alike and is the loss whose best constant is the median; RMSE squares errors so large ones dominate, and squared error is the loss for the mean (scikit-learn, Metrics). For errors the MAE is 4.8 and the RMSE is 8.99: one outlier nearly doubles RMSE relative to MAE. Use RMSE when big misses are disproportionately bad, MAE when you want the typical miss. compares the model with always predicting the mean (1 is perfect, 0 is no better than the mean) and ranks models the same way as squared error. MAPE, the average of , is unstable when actual values are near zero: an actual of 0.1 predicted as 1.1 is a 1000% error.
Class imbalance
A dataset is imbalanced when its classes are not approximately equally represented (Chawla et al. 2002). Fraud can be under 0.1% of transactions, and a severe imbalance may leave too few minority examples to train properly (Google, Imbalanced datasets). Reach for the cheap, reversible fixes first.
- Baseline and metric. Use PR-AUC, recall at a fixed precision, or an expected cost. Keep the test set at the natural class rate, so the number describes real traffic.
- Class weights. Scikit-learn’s
balancedmode sets weights inversely proportional to class frequencies as , with classes and rows in class (scikit-learn, LogisticRegression). For 99 negatives and 1 positive that is 0.5051 and 50.0. It needs no change to the data and changes only the loss. Probabilities need recalibrating afterwards (above). - Threshold. Tune it on validation data, from costs.
- Resampling. Undersampling the majority discards information. Random oversampling repeats minority rows. SMOTE instead interpolates between a minority sample and one of its nearest minority neighbours (imbalanced-learn, Over-sampling), and Chawla et al. report that over-sampling with synthetic examples combined with under-sampling beat under-sampling alone in their experiments. Its caveats: the synthetic points are not real observations, so they can be unrealistic (derived here from how interpolation works); the documentation notes SMOTE may connect inliers and outliers, that plain SMOTE cannot handle categorical features, and that a variant for mixed data exists (imbalanced-learn, Over-sampling). Whether resampling beats class weights on your data is an experiment, not a rule (common practice).
- Inside the folds. A resampler belongs inside the cross-validation loop and acts on the training fold only. The validation fold must stay untouched at its natural rate: it stands for future data, which will not be resampled. In the script’s noise experiment, the leaky order scores 0.972 and the correct one 0.495 (see the leakage section). In imbalanced-learn, a pipeline that contains the resampler resamples inside each training fold and leaves the held-out fold untouched (imbalanced-learn, Common pitfalls).
- Last resorts. When positives are extremely rare or keep changing, framing the problem as anomaly detection can fit better, and labelling more positives (for example by prioritising which cases to label) often beats any algorithmic trick (common practice).
Baselines and error analysis
Report every metric next to a baseline, or it has no meaning. scikit-learn’s DummyClassifier exists for this purpose and ignores the features: the most_frequent strategy always predicts the most common class, stratified samples from the class prior, and constant always predicts a label of your choice (scikit-learn, DummyClassifier). On the fraud data, the most-frequent baseline has accuracy 0.998 and a constant score has an AP of 0.0020, so a model must beat those, using a metric that can separate them. A log-loss baseline is the same idea: predicting the base rate of 0.002 for every row gives 0.0144. Compare also with the simplest sensible model (a regularised linear model) and, if one exists, the rule the business uses today (common practice).
Error analysis looks at where the model fails, not only how often. An average hides weak segments: 9,000 rows at 95% correct and 1,000 rows at 70% correct give 92.5% overall, which sounds fine while one segment is failing. The steps are: slice the metric by segment (age band, region, device, language, time period, data source), read a sample of the worst errors by hand, group them by cause, and fix the biggest group first, whether that is a data problem, a missing feature or a label error (common practice). Slicing by group is also the first step of a fairness check; the criteria for that are outside this lesson.
Code
This standard-library script produced every number in the lesson that is computed here. The first part is the helper functions from homework/solution.py (without docstrings); the rest is the experiments. It has fixed seeds and runs in about 2 seconds (Python 3.14). Another Python version may draw different random numbers, which moves the exact figures in sections 2, 3, 5, 6 and 7 but not their pattern.
import math
import random
import time
def stratified_kfold(labels, k):
n = len(labels)
if k < 2 or k > n:
raise ValueError("need 2 <= k <= number of rows")
fold_of = [0] * n
counter = 0
for cls in sorted(set(labels)):
for i in range(n):
if labels[i] == cls:
fold_of[i] = counter % k
counter += 1
return [([i for i in range(n) if fold_of[i] != f], [i for i in range(n) if fold_of[i] == f]) for f in range(k)]
def group_kfold(groups, k):
first_seen = []
members = {}
for i, g in enumerate(groups):
if g not in members:
members[g] = []
first_seen.append(g)
members[g].append(i)
if k < 2 or k > len(first_seen):
raise ValueError("need 2 <= k <= number of groups")
order = sorted(first_seen, key=lambda g: -len(members[g]))
sizes = [0] * k
test = [[] for _ in range(k)]
for g in order:
f = sizes.index(min(sizes))
test[f].extend(members[g])
sizes[f] += len(members[g])
n = len(groups)
out = []
for f in range(k):
t = sorted(test[f])
ts = set(t)
out.append(([i for i in range(n) if i not in ts], t))
return out
def time_series_split(n, n_splits, test_size=None, gap=0):
if n_splits < 2:
raise ValueError("n_splits must be at least 2")
if test_size is None:
test_size = n // (n_splits + 1)
out = []
for i in range(n_splits):
end = n - (n_splits - 1 - i) * test_size
start = end - test_size
if test_size < 1 or start - gap < 1:
raise ValueError("not enough rows for these settings")
out.append((list(range(0, start - gap)), list(range(start, end))))
return out
def roc_auc(y_true, scores):
pos = [s for y, s in zip(y_true, scores) if y == 1]
neg = [s for y, s in zip(y_true, scores) if y == 0]
if not pos or not neg:
raise ValueError("both classes are needed")
order = sorted(range(len(scores)), key=lambda i: scores[i])
ranks = [0.0] * len(scores)
i = 0
while i < len(order):
j = i
while j + 1 < len(order) and scores[order[j + 1]] == scores[order[i]]:
j += 1
for t in range(i, j + 1):
ranks[order[t]] = (i + j) / 2 + 1
i = j + 1
rank_sum = sum(r for r, y in zip(ranks, y_true) if y == 1)
return (rank_sum - len(pos) * (len(pos) + 1) / 2) / (len(pos) * len(neg))
def average_precision(y_true, scores):
total_pos = sum(1 for y in y_true if y == 1)
if total_pos == 0:
raise ValueError("no positives")
order = sorted(range(len(scores)), key=lambda i: -scores[i])
tp = seen = 0
prev_recall = 0.0
ap = 0.0
i = 0
while i < len(order):
j = i
while j + 1 < len(order) and scores[order[j + 1]] == scores[order[i]]:
j += 1
for t in range(i, j + 1):
tp += 1 if y_true[order[t]] == 1 else 0
seen = j + 1
recall = tp / total_pos
ap += (recall - prev_recall) * (tp / seen)
prev_recall = recall
i = j + 1
return ap
def precision_recall_at_threshold(y_true, scores, threshold):
tp = sum(1 for y, s in zip(y_true, scores) if s >= threshold and y == 1)
fp = sum(1 for y, s in zip(y_true, scores) if s >= threshold and y == 0)
fn = sum(1 for y, s in zip(y_true, scores) if s < threshold and y == 1)
precision = tp / (tp + fp) if tp + fp else 0.0
recall = tp / (tp + fn) if tp + fn else 0.0
return precision, recall
def cost_threshold(c_fn, c_fp):
return c_fp / (c_fp + c_fn)
def best_threshold_by_cost(y_true, scores, c_fn, c_fp):
best = None
for t in sorted(set(scores)) + [float("inf")]:
fn = sum(1 for y, s in zip(y_true, scores) if y == 1 and s < t)
fp = sum(1 for y, s in zip(y_true, scores) if y == 0 and s >= t)
cost = c_fn * fn + c_fp * fp
if best is None or cost <= best[1]:
best = (t, cost)
return best
def expected_calibration_error(y_true, probs, n_bins=10):
n = len(y_true)
bins = [[] for _ in range(n_bins)]
for y, p in zip(y_true, probs):
bins[min(int(p * n_bins), n_bins - 1)].append((y, p))
ece = 0.0
for b in bins:
if b:
frac = sum(y for y, _ in b) / len(b)
conf = sum(p for _, p in b) / len(b)
ece += len(b) / n * abs(frac - conf)
return ece
def duplicate_rows(train_rows, test_rows):
seen = {tuple(r) for r in train_rows}
return [i for i, r in enumerate(test_rows) if tuple(r) in seen]
def shared_groups(train_groups, test_groups):
return sorted(set(train_groups) & set(test_groups))
def balance_by_duplication(indices, labels):
by_class = {}
for i in indices:
by_class.setdefault(labels[i], []).append(i)
if not by_class:
return []
target = max(len(v) for v in by_class.values())
out = list(indices)
for cls in sorted(by_class):
rows = by_class[cls]
for j in range(target - len(rows)):
out.append(rows[j % len(rows)])
return out
T0 = time.time()
def mean(xs):
xs = list(xs)
return sum(xs) / len(xs)
def counts(idx, labels):
out = {}
for i in idx:
out[labels[i]] = out.get(labels[i], 0) + 1
return dict(sorted(out.items()))
def sigmoid(z):
return 1 / (1 + math.exp(-z))
def logit(p):
return math.log(p / (1 - p))
def log_loss(y, p):
return -mean(math.log(q) if t == 1 else math.log(1 - q) for t, q in zip(y, p))
def nn_predict(train_x, train_y, x):
best, label = None, None
for r, t in zip(train_x, train_y):
d = sum((a - b) ** 2 for a, b in zip(r, x))
if best is None or d < best:
best, label = d, t
return label
def balanced_accuracy(y, pred):
recalls = []
for c in sorted(set(y)):
hits = [p == c for t, p in zip(y, pred) if t == c]
recalls.append(sum(hits) / len(hits))
return mean(recalls)
print("== 1. The fraud confusion matrix: 10,000 transactions, 20 fraud ==")
for flagged, caught in ((40, 15), (60, 18)):
tp, fp, fn = caught, flagged - caught, 20 - caught
tn = 10000 - tp - fp - fn
prec, rec = tp / (tp + fp), tp / (tp + fn)
print("flag %d, catch %d: TP %d FP %d FN %d TN %d | accuracy %.4f precision %.3f recall %.2f F1 %.3f"
% (flagged, caught, tp, fp, fn, tn, (tp + tn) / 10000, prec, rec, 2 * prec * rec / (prec + rec)))
print("never-fraud model: accuracy %.3f, recall 0, cost %d" % (9980 / 10000, 20 * 5000))
for name, fn_, fp_ in (("flag 40, catch 15", 5, 25), ("flag 60, catch 18", 2, 42)):
print("%s: total cost at 5000 per miss and 50 per false alarm = %d" % (name, 5000 * fn_ + 50 * fp_))
print("\n== 2. ROC-AUC and PR-AUC: the same 100 positives (score ~ N(2,1)), negatives ~ N(0,1) ==")
rng = random.Random(7)
pos = [rng.gauss(2, 1) for _ in range(100)]
neg_all = [rng.gauss(0, 1) for _ in range(49900)]
for name, neg in (("100 negatives (50% positive)", neg_all[:100]), ("49,900 negatives (0.2% positive)", neg_all)):
y = [1] * len(pos) + [0] * len(neg)
s = pos + neg
p, r = precision_recall_at_threshold(y, s, 1.0)
print("%-34s ROC-AUC %.3f AP %.3f | at score >= 1: precision %.3f recall %.2f"
% (name, roc_auc(y, s), average_precision(y, s), p, r))
print("AP of a constant score on the 0.2%% set: %.4f (the positive rate)" % average_precision(y, [0.5] * len(y)))
print("\n== 3. Threshold from cost: a miss costs 5000, a false alarm 50 (cost units) ==")
print("threshold 50 / 5050 = %.4f" % cost_threshold(5000, 50))
rng = random.Random(3)
probs = [0.8 * rng.random() ** 12 for _ in range(20000)]
ys = [1 if rng.random() < p else 0 for p in probs]
print("calibrated scores: positive rate %.4f" % mean(ys))
for t in (0.5, 0.1, cost_threshold(5000, 50)):
pr, rc = precision_recall_at_threshold(ys, probs, t)
fn = sum(1 for y, p in zip(ys, probs) if y == 1 and p < t)
fp = sum(1 for y, p in zip(ys, probs) if y == 0 and p >= t)
print("threshold %.4f: cost per row %.2f precision %.3f recall %.3f" % (t, (5000 * fn + 50 * fp) / 20000, pr, rc))
grid = [i / 1000 for i in range(1, 100)]
cost_of = lambda t: (5000 * sum(1 for y, p in zip(ys, probs) if y == 1 and p < t) + 50 * sum(1 for y, p in zip(ys, probs) if y == 0 and p >= t)) / 20000
bt = min(grid, key=cost_of)
print("cheapest threshold on a 0.001 grid: %.3f (cost per row %.2f)" % (bt, cost_of(bt)))
print("\n== 4. Split indices ==")
y = [0] * 45 + [1] * 5
print("stratified, 45 vs 5, k=3, test class counts:", [counts(te, y) for _, te in stratified_kfold(y, 3)])
print("stratified train class counts:", [counts(tr, y) for tr, _ in stratified_kfold(y, 3)])
print("group k-fold test sets:", [te for _, te in group_kfold([1, 1, 1, 2, 2, 2, 3, 3, 3, 3], 3)])
for i, (tr, te) in enumerate(time_series_split(12, 3, test_size=2, gap=2)):
print("time series, gap 2, fold %d: train %s test %s" % (i, tr, te))
print("\n== 5. Leakage, measured ==")
# 5a. feature selection before the split, on pure noise
def pick(X, y, rows, k):
ybar = mean(y[i] for i in rows)
score = []
for j in range(len(X[0])):
xbar = mean(X[i][j] for i in rows)
score.append(abs(sum((X[i][j] - xbar) * (y[i] - ybar) for i in rows)))
return sorted(range(len(score)), key=lambda j: -score[j])[:k]
def centroid_accuracy(X, y, cols, tr, te):
cents = {}
for c in (0, 1):
rows = [i for i in tr if y[i] == c]
cents[c] = [mean(X[i][j] for i in rows) for j in cols]
hit = 0
for i in te:
d = {c: sum((X[i][j] - m) ** 2 for j, m in zip(cols, cents[c])) for c in (0, 1)}
hit += (0 if d[0] <= d[1] else 1) == y[i]
return hit / len(te)
leaky, honest = [], []
for seed in range(20):
rng = random.Random(seed)
X = [[rng.gauss(0, 1) for _ in range(2000)] for _ in range(100)]
yy = [rng.randrange(2) for _ in range(100)]
tr, te = list(range(50)), list(range(50, 100))
leaky.append(centroid_accuracy(X, yy, pick(X, yy, range(100), 10), tr, te))
honest.append(centroid_accuracy(X, yy, pick(X, yy, tr, 10), tr, te))
print("5a. noise features and labels, 100 rows, 2000 features, 10 kept, 20 repeats:")
print(" selection on all rows: test accuracy %.3f | selection on train rows only: %.3f" % (mean(leaky), mean(honest)))
# 5b. the same patient on both sides of the split
def patient_cv(seed):
rng = random.Random(seed)
rows, labels, who = [], [], []
for p in range(100):
base = [rng.gauss(0, 1) for _ in range(3)]
label = rng.randrange(2)
for _ in range(5):
rows.append([b + rng.gauss(0, 0.1) for b in base])
labels.append(label)
who.append(p)
perm = list(range(len(rows)))
rng.shuffle(perm)
row_folds = [([i for i in range(500) if perm[i] % 5 != f], [i for i in range(500) if perm[i] % 5 == f]) for f in range(5)]
out = []
for folds in (row_folds, group_kfold(who, 5)):
hits = 0
for tr, te in folds:
trx, trl = [rows[i] for i in tr], [labels[i] for i in tr]
hits += sum(nn_predict(trx, trl, rows[i]) == labels[i] for i in te)
out.append(hits / 500)
out.append(len(shared_groups([who[i] for i in folds[0][0]], [who[i] for i in folds[0][1]])))
return out
runs = [patient_cv(s) for s in range(5)]
print("5b. 100 patients x 5 visits, labels are coin flips per patient, 1-nearest-neighbour, 5 repeats:")
print(" row-level 5-fold: accuracy %.3f, patients on both sides in fold 0: %.0f" % (mean(r[0] for r in runs), mean(r[1] for r in runs)))
print(" group 5-fold: accuracy %.3f, patients on both sides in fold 0: %.0f" % (mean(r[2] for r in runs), mean(r[3] for r in runs)))
# 5c. a random split on a time series
rng = random.Random(5)
walk, v = [], 0.0
for _ in range(300):
v += rng.gauss(0, 1)
walk.append(v)
def nearest_time_mae(folds):
errs = []
for tr, te in folds:
for i in te:
j = min(tr, key=lambda t: abs(t - i))
errs.append(abs(walk[i] - walk[j]))
return mean(errs)
perm = list(range(300))
rng.shuffle(perm)
rand_folds = [([i for i in range(300) if perm[i] % 5 != f], [i for i in range(300) if perm[i] % 5 == f]) for f in range(5)]
print("5c. random walk, predict each value from the nearest training time step:")
print(" random 5-fold MAE %.2f | forward-chaining (5 splits, test blocks of 50) MAE %.2f" % (nearest_time_mae(rand_folds), nearest_time_mae(time_series_split(300, 5))))
print("\n== 6. Resampling inside versus outside the folds (noise data, 15 positives of 300) ==")
res = {"duplicate first": [], "inside folds": []}
overlap = []
for seed in range(5):
rng = random.Random(100 + seed)
X = [[rng.gauss(0, 1) for _ in range(4)] for _ in range(300)]
yy = [1] * 15 + [0] * 285
rng.shuffle(yy)
allrows = balance_by_duplication(list(range(300)), yy)
rng.shuffle(allrows)
bx, by = [X[i] for i in allrows], [yy[i] for i in allrows]
accs = []
for tr, te in stratified_kfold(by, 5):
pred = [nn_predict([bx[i] for i in tr], [by[i] for i in tr], bx[i]) for i in te]
accs.append(balanced_accuracy([by[i] for i in te], pred))
res["duplicate first"].append(mean(accs))
first = stratified_kfold(by, 5)[0]
overlap.append(len(duplicate_rows([bx[i] for i in first[0]], [bx[i] for i in first[1]])) / len(first[1]))
accs = []
for tr, te in stratified_kfold(yy, 5):
tr2 = balance_by_duplication(tr, yy)
pred = [nn_predict([X[i] for i in tr2], [yy[i] for i in tr2], X[i]) for i in te]
accs.append(balanced_accuracy([yy[i] for i in te], pred))
res["inside folds"].append(mean(accs))
print("balanced accuracy over 5 seeds, 1-nearest-neighbour (honest value is about 0.5):")
for k, v in res.items():
print(" %-17s %.3f" % (k, mean(v)))
print(" share of validation rows that have an exact copy in the training part (duplicate first): %.2f" % mean(overlap))
print("\n== 7. Calibration ==")
w, p0 = 99, 0.01
print("upweighting positives by %d turns a true probability of %.2f into %.3f" % (w, p0, w * p0 / (1 - p0 + w * p0)))
print("downsampling negatives 25x turns a 99/1 split into %.1f%% positives" % (100 * 1 / (1 + 99 / 25)))
rng = random.Random(1)
true_p = [min(max(rng.random(), 0.001), 0.999) for _ in range(20000)]
yc = [1 if rng.random() < p else 0 for p in true_p]
over = [sigmoid(2 * logit(p)) for p in true_p]
fixed = [sigmoid(logit(p) / 2) for p in over]
for name, q in (("calibrated", true_p), ("overconfident (logit x2)", over), ("rescaled back (logit / 2)", fixed)):
print("%-26s ECE %.3f log loss %.3f ROC-AUC %.4f" % (name, expected_calibration_error(yc, q), log_loss(yc, q), roc_auc(yc, q)))
print("\n== 8. Regression metrics and error slices ==")
err = [1, 1, 1, 1, 20]
print("errors %s: MAE %.1f, RMSE %.2f" % (err, mean(err), math.sqrt(mean(e * e for e in err))))
print("actual 0.1 predicted 1.1: absolute percentage error %.0f%%" % (100 * abs(1.1 - 0.1) / 0.1))
n_, n_pos = 100, 1
print("balanced class weights for 99 negatives and 1 positive: negative %.4f, positive %.1f" % (n_ / (2 * (n_ - n_pos)), n_ / (2 * n_pos)))
prior = 0.002
print("log loss of always predicting the base rate 0.002: %.4f" % -(prior * math.log(prior) + (1 - prior) * math.log(1 - prior)))
print("slices: 9000 rows at 95%% correct and 1000 rows at 70%% correct give overall %.1f%%" % (100 * (9000 * 0.95 + 1000 * 0.70) / 10000))
print("\ntotal %.1f s" % (time.time() - T0))What to look for: section 1 (the confusion matrix and the costs), section 2 (the same ROC-AUC, a collapsing AP), section 3 (cost per row at three thresholds), section 4 (split indices), section 5 (the three leakage experiments), section 6 (resampling before and inside folds), section 7 (calibration), section 8 (regression metrics, class weights, baselines, slices). In scikit-learn the equivalents are StratifiedKFold, GroupKFold, TimeSeriesSplit, Pipeline, average_precision_score, roc_auc_score, log_loss, CalibratedClassifierCV, TunedThresholdClassifierCV and DummyClassifier.
Real-World Application
A sound recipe for a new classifier on rare outcomes: write down the prediction time and the cost of each error, choose a splitter that matches how rows relate, put every fitted step in a pipeline, compare against a dummy and a simple model, report PR-AUC and the cost at a threshold chosen on validation data, check calibration, slice the errors, and touch the test set once. When a score looks too good, assume leakage until the duplicate, group and timestamp checks say otherwise. A good score in the first week of a project is a reason to hunt for a leak.
Interview Perspective
Expect “your fraud model has 99.8% accuracy: is it good?”, “ROC-AUC versus PR-AUC”, “name leakage sources in a readmission model”, “how do you validate a time series model”, “how would you handle 1:1000 imbalance”, “where do you set the threshold”, and “when do you need calibrated probabilities”. A strong answer names the base rate, picks the metric from the cost of errors, gives a split that matches the data’s structure, says the resampler goes inside the fold, and ends with a check it would run. A weak answer lists remedies without saying how it would know they worked.
Provenance: Common industry pattern. These are standard evaluation fundamentals for ML roles, not a verified list for any named company.
Practice Questions
- Basic (Common industry pattern): A model has 99.8% accuracy on data with 0.2% positives. What do you ask next?
- Intermediate (Common industry pattern): Why can ROC-AUC look excellent while precision is poor at every useful threshold?
- Intermediate (Generated practice): Derive the threshold and say when it is wrong.
- Advanced (Common industry pattern): Why must SMOTE be applied inside each training fold, and what exactly leaks if it is applied before the split?
- Product-Company (Generated practice): A hospital readmission model scores very well offline and poorly after launch. List the leaks you would check, in order, and how you would test each.
Activity
Run the script, then change the number of kept features in section 5 from 10 to 50 and to 2, and note how the leaky and honest accuracies move. Next, change the group size in 5b from 5 visits to 2 and check how much the row-level score drops. Finally, take a dataset of your own with a rare class, build the leaky version (resample first, row-level split) and the correct version, and write down the two scores and what changed.
Homework
Implement the evaluation toolkit: stratified, group and forward-chaining splitters, ROC-AUC and average precision, precision and recall at a threshold, the cost threshold and a cost search, the expected calibration error, two leak detectors, and balancing by duplication. The code is in homework/; run the tests until they pass.
Quick Revision
- Choose the splitter from the rows’ structure: stratified for rare classes, group for repeated entities, forward-chaining for time. Touch the test set once.
- Leakage: target, preprocessing before the split, shared entities or duplicates, temporal, resampling before the split. Fit and resample inside the training fold.
- Accuracy lies under imbalance. ROC-AUC ignores prevalence; PR-AUC and precision at a threshold show the cost of false alarms. A baseline is the first thing to report.
- Log loss and calibration judge the probabilities; weights and resampling distort them, so recalibrate. The cost threshold is for calibrated probabilities.
- Imbalance order: metric, stratify, class weights, threshold, resample inside folds, recalibrate. Analyse errors by slice.
Check yourself
- Walk-through: Without notes, explain what happens to the validation score if you oversample the minority class before a random 5-fold split, and what you would do instead.
- Variation: A churn model is 0.97 AUC offline and 0.70 a month after launch. List three leaks that could explain it and one check for each.
- Common misconception: “A 99% accurate model is good”, “ROC-AUC is wrong for imbalanced data”, and “a probability of 0.5 is always the right cut”.
Resources & Further Reading
Checked sources to go deeper. The essential ones come first in each group.
Official documentation
Cross-validation: evaluating estimator performance (opens in a new tab)Essential
The reference for every splitter in this lesson, with the outputs you can reproduce with the homework functions.
Common pitfalls and recommended practices (data leakage) (opens in a new tab)Essential
A short, concrete tour of leakage, including the feature-selection example that you can rerun.
Probability calibration (opens in a new tab)
Reliability curves and the sigmoid, isotonic and temperature methods side by side, with which models tend to be miscalibrated.
Common pitfalls and recommended practices (imbalanced-learn) (opens in a new tab)
A worked leaky-versus-pipeline comparison for resampling.
Research papers
The argument for reading precision-recall curves on imbalanced data, with simulations.
On Calibration of Modern Neural Networks (opens in a new tab)
Why deep networks are overconfident and how temperature scaling repairs it.
More for this module: Evaluation, statistics and data resources
Practice
Test what you just read. Quizzes and cards are grouped by module: Evaluation, statistics and data.
Check yourself18 questions on what this lesson set out to teach
Checking answers needs JavaScript. You can still read every question and option below.
Keyboard: arrow keys move between options. Space or Enter selects the focused option.