Module contents
Lesson 8 of 24Core 105 min

Cross-validation, data leakage and pipelines

Study how to estimate model performance without misleading yourself: k-fold, stratified, grouped, repeated and time-aware validation; what cross-validation really estimates and why its variance has no unbiased estimator. The central section covers data leakage and prevention by encapsulating all preprocessing, including categorical encoding, in pipelines. Finish with nested cross-validation for selection and evaluation together.

After this lesson you can

  • Implement k-fold, stratified, grouped and time-based splits and choose according to data dependence.
  • Explain what cross-validation estimates and why its estimator variance is difficult to quantify.
  • Detect and correct preprocessing, target, temporal and duplicate leakage.
  • Build pipelines encapsulating scaling, imputation and categorical encoding (one-hot, ordinal and cross-fitted target encoding).
  • Apply nested cross-validation and quantify optimistic bias from reporting a search’s best result.

Before you start

Motivation: the number that decides too much

Nearly every decision in an ML project goes through one number: the estimated generalization error. You use it to choose models, tune hyperparameters, decide whether something is production-ready, and write the paper’s table. If that number is wrong, everything depending on it is wrong; dangerously, a poorly estimated number almost always errs in the direction you like: upward.

In polynomial regression you saw holdout validation: reserve part of the data, train on the rest, and measure on the reserved portion. It has two problems that worsen with less data.

  • It is noisy. With 200 validation examples and true accuracy 0.80.8, measured accuracy is a binomial divided by 200 with standard deviation 0.8⋅0.2/200=0.028\sqrt{0.8 \cdot 0.2 / 200} = 0.028: a 95% interval spans ±5.5\pm 5.5 points. A 3-point difference between models falls within that noise, and changing the split seed can reverse their order.
  • It wastes data. Validation examples are not used for training, so you measure a worse model than the one you would deliver. If the split is unfortunate (all difficult images in validation, or no examples of the rare class), the estimate is biased for those particular data.

There is a third problem, more serious than either and fixed by no split alone: data leakage between what the model sees in training and what evaluates it. Kapoor and Narayanan (2023) reviewed literature across disciplines using ML and found documented leakage errors in 17 fields affecting 329 papers (figures from the abstract of their arXiv version), including cases where published advantages of complex models disappear when evaluation is corrected. These are not exotic mistakes: selecting features using all data before validation, normalizing with the global mean, or allowing the same patient on both sides of a split.

This lesson builds honest evaluation piece by piece. First cross-validation and its extreme variant, LOOCV. Then a question rarely asked: what it estimates exactly, and why its variance cannot be estimated without bias. Next come splits respecting data structure (classes, groups, time), leakage, and the pipeline that prevents it by construction. Finally nested cross-validation separates selection from evaluation. Everything is implemented from scratch and checked against sklearn.model_selection.

k-fold and LOOCV

The idea is to reuse every example for validation exactly once. Split indices {1,…,n}\{1, \dots, n\} into kk blocks, train kk models, each without its block, and average each model’s errors on the block it did not see.

Three details of the definition matter. First, validation assesses A\mathcal{A}, the entire procedure, not one particular model: the kk models differ and none is the one you deliver, which is trained on all nn observations. Second, loss ℓ\ell can be any from the metrics lesson: squared error, 0-1, log-loss. For metrics that are not per-example means, such as AUC, calculate the metric in each fold and average the kk figures; this differs from computing it on concatenated predictions because the kk models need not share a scale. Third, the split is random unless data structure demands otherwise, as discussed in the splits section.

Choosing k: bias, variance and cost

Each model trains on n(1−1/k)n(1 - 1/k) observations rather than nn, and a model trained on fewer data is worse on average. Thus CV^k\widehat{\mathrm{CV}}_k has pessimistic bias depending on the slope of the learning curve between n(1−1/k)n(1 - 1/k) and nn. One case can be calculated exactly: for least-squares linear regression with x∼N(0,Id)\vb{x} \sim \Normal(\vb{0}, \mat{I}_d), noise variance σ2\sigma^2 and mm training observations, expected prediction error is

Err(m)=σ2(1+dm−d−1),m>d+1,\mathrm{Err}(m) = \sigma^2\Big(1 + \frac{d}{m - d - 1}\Big), \qquad m > d + 1,

because E∥w^−w∥2=σ2tr⁡E[(X⊤X)−1]\E\norm{\hat{\vb{w}} - \vb{w}}^2 = \sigma^2\tr\E[(\mat{X}\T\mat{X})\inv] and the inverse Wishart mean is Id/(m−d−1)\mat{I}_d/(m - d - 1). With n=40n = 40 and d=10d = 10, Err(40)=1.345 σ2\mathrm{Err}(40) = 1.345\,\sigma^2, while 5 folds train on 32 observations and estimate Err(32)=1.476 σ2\mathrm{Err}(32) = 1.476\,\sigma^2: 10% pessimism. With k=2k = 2, training uses 20 observations and bias rises sharply.

LOOCV minimizes that bias because each model uses n−1n - 1 observations. In exchange it costs nn fits, except for models linear in y\vb{y}, where you already know the closed-form LOOCV formula: 1n∑i(ei/(1−hii))2\frac{1}{n}\sum_i \big(e_i / (1 - h_{ii})\big)^2 using residuals and the hat-matrix diagonal from one fit. What about variance? Folklore says LOOCV has high variance because its nn models are nearly identical and errors highly correlated. This is not a law: it depends on algorithm stability, how much its prediction changes when removing one point (the same property linking stability and generalization in learning theory). For highly stable least squares, the next section’s first cell measures the standard deviation of CV^k\widehat{\mathrm{CV}}_k over 2000 datasets and obtains 0.8740.874, 0.4450.445, 0.3850.385 and 0.3540.354 for k=2,5,10,40k = 2, 5, 10, 40: here more folds are better on both counts. For unstable algorithms (deep trees, k-NN with k=1k = 1, feature selection), the picture changes, hence the common practical recommendation of k=5k = 5 or 1010: moderate bias, moderate cost and reasonable behavior for almost any algorithm. Ambroise and McLachlan explicitly recommend 10 folds over LOOCV in the gene-selection study we will see.

Index generators from scratch

A CV implementation is just a generator of (training, validation) pairs. Here are the four you need: random k-fold, stratified, grouped and time-based (the time-based version returns pairs directly because training and validation are not complements). The toy data are 30 time-ordered samples with 30% positives and 7 patients.

[ ]Fold generators from scratchBrowser
import numpy as np

def kfold_indices(n, k, seed=0):
    """k pliegues aleatorios de tamaños que difieren como mucho en 1 (índices de validación)."""
    perm = np.random.default_rng(seed).permutation(n)
    return [np.sort(perm[f::k]) for f in range(k)]

def stratified_naive(y, k, seed=0):
    """Reparte cada clase por turnos empezando siempre en el pliegue 0."""
    rng = np.random.default_rng(seed)
    folds = [[] for _ in range(k)]
    for c in np.unique(y):
        idx = rng.permutation(np.flatnonzero(y == c))
        for j, i in enumerate(idx):
            folds[j % k].append(i)
    return [np.sort(np.array(f, dtype=int)) for f in folds]

def group_kfold_indices(groups, k):
    """Grupos enteros a pliegues: el más grande primero, al pliegue con menos muestras (la regla de GroupKFold)."""
    labels, counts = np.unique(groups, return_counts=True)
    load = np.zeros(k, dtype=int)
    fold_of = {}
    for g in labels[np.argsort(counts)[::-1]]:
        f = int(np.argmin(load))
        fold_of[g] = f
        load[f] += counts[labels == g][0]
    f_arr = np.array([fold_of[g] for g in groups])
    return [np.flatnonzero(f_arr == f) for f in range(k)]

def time_series_splits(n, k, gap=0, max_train=None):
    """k + 1 bloques consecutivos; en la iteración j se valida el bloque j + 1 con el pasado."""
    test = n // (k + 1)
    out = []
    for j in range(k):
        va_start = n - (k - j) * test
        tr_end = va_start - gap
        tr_start = 0 if max_train is None else max(0, tr_end - max_train)
        out.append((np.arange(tr_start, tr_end), np.arange(va_start, va_start + test)))
    return out

def complemento(n, va):
    m = np.ones(n, bool)
    m[va] = False
    return np.flatnonzero(m)

rng = np.random.default_rng(1)
n, k = 30, 5
y = np.r_[np.ones(9, int), np.zeros(21, int)][rng.permutation(n)]
grupos = rng.integers(0, 7, n)

print("k-fold aleatorio:")
for f, va in enumerate(kfold_indices(n, k)):
    tr = complemento(n, va)
    comp = len(set(grupos[va]) & set(grupos[tr]))
    futuro = int((tr > va.min()).sum())
    print(f"  pliegue {f}: positivos {y[va].mean():.2f}   pacientes a ambos lados {comp}   "
          f"entrenamiento posterior al inicio de la validación {futuro}")
print("estratificado (reparto ingenuo por clase):")
for f, va in enumerate(stratified_naive(y, k)):
    print(f"  pliegue {f}: tamaño {len(va)}   positivos {y[va].sum()}   proporción {y[va].mean():.2f}")
print("por grupos:")
for f, va in enumerate(group_kfold_indices(grupos, k)):
    tr = complemento(n, va)
    print(f"  pliegue {f}: tamaño {len(va)}   pacientes {sorted(set(grupos[va].tolist()))}   "
          f"a ambos lados {len(set(grupos[va]) & set(grupos[tr]))}")
print("temporal expansiva | deslizante (ventana 10, hueco 1):")
for (tr, va), (tr2, va2) in zip(time_series_splits(n, k), time_series_splits(n, k, gap=1, max_train=10)):
    print(f"  entrena {tr.min()}..{tr.max()} valida {va.min()}..{va.max()}   |   "
          f"entrena {tr2.min()}..{tr2.max()} valida {va2.min()}..{va2.max()}")

Read the output carefully: it previews the splits section. Random k-fold leaves validation positive fractions between 0 and 0.50 despite a global 0.30, puts patients on both sides in every fold, and always trains on samples later than validation. Naive stratification fixes proportions, but notice sizes: 7, 6, 6, 6, 5. Each class starts distribution at fold 0, so early folds collect every class’s “remainders.” With many small classes the difference grows; the final coding exercise asks for a version preserving both proportions and sizes. Group splits put no patient on both sides, at the cost of unequal folds (9 versus 5). Time-based splitting never trains on the future.

What cross-validation estimates

Two different quantities are often called “model error,” and the distinction matters. Let D\Data be your training sample and f^=A(D)\hat f = \mathcal{A}(\Data) the model you deliver. Its conditional error is

ErrXY=E[ℓ(f^(X),Y)∣D],\mathrm{Err}_{XY} = \E\big[\ell(\hat f(X), Y) \given \Data\big],

the error of your particular model on new data from the same distribution. The procedure’s expected error also averages over possible training samples:

Err(n)=ED[ErrXY].\mathrm{Err}(n) = \E_{\Data}\big[\mathrm{Err}_{XY}\big].

What you almost always want to know is ErrXY\mathrm{Err}_{XY}: you will deploy f^\hat f, not the average of every model you might have trained. Which does CV estimate? Bates, Hastie and Tibshirani (2021) answer: CV estimates average error of models fitted on other training sets from the same population, not the error of the model fitted to your data. They prove this for least squares and argue it holds for common estimators, as well as holdout and bootstrap. You can check: in the Gaussian linear model above, ErrXY=σ2+∥w^−w∥2\mathrm{Err}_{XY} = \sigma^2 + \norm{\hat{\vb{w}} - \vb{w}}^2 is exact for each dataset, so simulate many datasets and compare.

InteractiveWhat does cross-validation estimate?
CV with 5 folds versus the true error of the model fitted on all nn observations
Err(n(1 − 1/k))Err(n)CV = Err_XY
  • one dataset
  • diagonal: CV = true error
  • expected error with n(1−1/k)n(1-1/k) observations
  • expected error with nn observations
Folds kk
40
10
Correlation between CV and ErrXY\mathrm{Err}_{XY}−0.04
Mean CV1.505
Err\mathrm{Err} training on n(1−1/k)=32n(1 - 1/k) = 321.476
Mean ErrXY\mathrm{Err}_{XY} and Err(n)\mathrm{Err}(n)1.345 and 1.345
Standard deviation of CV and ErrXY\mathrm{Err}_{XY}0.456 and 0.187
Naive 95% CI coverage: ErrXY\mathrm{Err}_{XY} / Err(n)\mathrm{Err}(n)84 % / 86 %
The correlation is −0.04: knowing the CV of your data tells you very little about the error of the model you will deliver. What CV estimates correctly on average is the expected error of the procedure, 1.476 for samples of 3232 observations.
Each point is a size-nn dataset generated with x∼N(0,Id)\vb{x} \sim \Normal(\vb{0}, \mat{I}_d) and y=x⊤w+εy = \vb{x}\T\vb{w} + \eps, ε∼N(0,1)\eps \sim \Normal(0, 1). Horizontally is true error ErrXY\mathrm{Err}_{XY} of the least-squares model fitted on its nn observations (exact); vertically its kk-fold CV estimate (LOO uses the closed form). If CV estimated your model's error, the cloud would lie on the diagonal. It does not: it is almost round, centered on the orange line, expected procedure error training on n(1−1/k)n(1 - 1/k) observations. Change kk, nn and dd and watch the correlation.

The next cell runs the same simulation with 2000 datasets and breaks it down.

[ ]CV versus the error of the model you deliverBrowser
import numpy as np

# x ~ N(0, I_d), y = x·w + eps, eps ~ N(0, sigma^2); mínimos cuadrados sin intercepto.
# Para un ajuste concreto, Err_XY = sigma^2 + ||w_hat - w||^2 exactamente.
n, d, k, sigma, R = 40, 10, 5, 1.0, 2000
rng = np.random.default_rng(0)
w = np.ones(d)
X = rng.standard_normal((R, n, d))
Y = X @ w + sigma * rng.standard_normal((R, n))

def ols(X, y):                                    # en lotes: X (..., m, d), y (..., m)
    XtX = np.swapaxes(X, -1, -2) @ X
    Xty = np.einsum("...md,...m->...d", X, y)
    return np.linalg.solve(XtX, Xty[..., None])[..., 0]

def cv_ols(X, Y, fold):
    """Errores cuadráticos de validación de cada ejemplo, para todos los conjuntos a la vez."""
    loss = np.empty(Y.shape)
    for f in np.unique(fold):
        tr, va = fold != f, fold == f
        b = ols(X[:, tr], Y[:, tr])
        loss[:, va] = (Y[:, va] - np.einsum("rmd,rd->rm", X[:, va], b)) ** 2
    return loss

err_xy = sigma**2 + ((ols(X, Y) - w) ** 2).sum(1)          # error real del modelo de cada conjunto
Err = lambda m: sigma**2 * (1 + d / (m - d - 1))            # error esperado entrenando con m datos

print(" k   media CV   Err(n(1-1/k))   desv. típ. CV   corr(CV, Err_XY)")
for kk in (2, 5, 10, n):
    cv_k = cv_ols(X, Y, np.arange(n) % kk).mean(1)
    print(f"{kk:2d}   {cv_k.mean():8.3f}   {Err(n - n // kk):13.3f}   {cv_k.std():13.3f}   {np.corrcoef(cv_k, err_xy)[0, 1]:+16.3f}")

fold = np.arange(n) % k                                       # los datos ya son iid: basta un reparto fijo
loss = cv_ols(X, Y, fold)
cv = loss.mean(1)
print(f"\nmedia de Err_XY {err_xy.mean():.3f}   Err(n = {n}) = {Err(n):.3f}   desv. típ. de Err_XY {err_xy.std():.3f}")

# intervalo «de libro»: los n errores por ejemplo tratados como independientes
se_naive = loss.std(1, ddof=1) / np.sqrt(n)
lo, hi = cv - 1.96 * se_naive, cv + 1.96 * se_naive
print(f"cobertura del IC ingenuo del 95 % (k = {k}):  de Err_XY {np.mean((lo <= err_xy) & (err_xy <= hi)):.3f}   "
      f"de Err(n) {np.mean((lo <= Err(n)) & (Err(n) <= hi)):.3f}")

Three results. The center is right, but for another quantity: mean 5-fold CV is 1.4941.494 and Err(32)=1.476\mathrm{Err}(32) = 1.476; LOOCV is 1.3631.363 versus Err(39)=1.357\mathrm{Err}(39) = 1.357. CV estimates expected error training on n(1−1/k)n(1 - 1/k) observations well. It knows nothing about the particular model: correlation between CV and ErrXY\mathrm{Err}_{XY} is +0.016+0.016 for 5 folds and between −0.01-0.01 and +0.022+0.022 for any kk. If your data produce an unusually good or bad model, CV does not notice; this is precisely what Bates, Hastie and Tibshirani prove for least squares. Textbook intervals mislead: CV^±1.96 s/n\widehat{\mathrm{CV}} \pm 1.96\,s/\sqrt{n}, treating the nn errors as independent, covers ErrXY\mathrm{Err}_{XY} 83.6% of the time and Err(n)\mathrm{Err}(n) 85.3%, not 95%. CV’s standard deviation, 0.4450.445, is over twice that of what you want to estimate, 0.1840.184.

CV variance has no unbiased estimator

The preceding interval fails because it underestimates variance. Why not estimate it correctly? Bengio and Grandvalet (2004) proved this cannot be done, at least without distributional assumptions. Let ei=ℓ(f^(−f(i))(xi),yi)e_i = \ell(\hat f^{(-f(i))}(\vb{x}_i), y_i) be example ii‘s validation error, with f(i)f(i) its fold, so CV^=1n∑iei\widehat{\mathrm{CV}} = \frac{1}{n}\sum_i e_i. Suppose kk equal-sized folds of size m=n/km = n/k. By symmetry (examples are exchangeable), the covariance matrix of eie_i has only three distinct values:

Cov⁡(ei,ej)={σ2i=j,ωi≠j, mismo pliegue,γpliegues distintos.\Cov(e_i, e_j) = \begin{cases} \sigma^2 & i = j, \\ \omega & i \neq j, \text{ mismo pliegue}, \\ \gamma & \text{pliegues distintos}. \end{cases}

ω\omega captures that two examples in the same fold are evaluated by the same model, and γ\gamma that models from different folds share n−2mn - 2m training observations and each one’s validation examples are in the other’s training set. Summing the n2n^2 covariances,

Var⁡(CV^)=1n2∑i,jCov⁡(ei,ej)=σ2n+m−1n ω+n−mn γ.\Var\big(\widehat{\mathrm{CV}}\big) = \frac{1}{n^2}\sum_{i,j}\Cov(e_i, e_j) = \frac{\sigma^2}{n} + \frac{m - 1}{n}\,\omega + \frac{n - m}{n}\,\gamma.

The proof for estimators quadratic in the eie_i, used in practice (all those of the “sum of squared deviations” form), is a guided exercise at the end and fits in four lines: expectation of any quadratic form ∑ijWijeiej\sum_{ij} W_{ij}e_ie_j combines σ2+μ2\sigma^2 + \mu^2, ω+μ2\omega + \mu^2 and γ+μ2\gamma + \mu^2, with μ=Eei\mu = \E e_i, and no coefficients can reproduce the variance coefficients while canceling μ2\mu^2. The paper treats the general case. The theorem does not mean nothing can be done: every CV variance estimator is biased for some distribution, and the naive one is almost always biased in the wrong direction. Indeed, for estimator s2/ns^2/n with s2=1n−1∑i(ei−eˉ)2s^2 = \frac{1}{n-1}\sum_i(e_i - \bar e)^2,

E[s2n]=σ2−Var⁡(CV^)n−1=σ2n−(m−1) ω+(n−m) γn(n−1),\E\Big[\frac{s^2}{n}\Big] = \frac{\sigma^2 - \Var(\widehat{\mathrm{CV}})}{n - 1} = \frac{\sigma^2}{n} - \frac{(m - 1)\,\omega + (n - m)\,\gamma}{n(n-1)},

obtained from E∑i(ei−eˉ)2=n(σ2+μ2)−n(Var⁡(eˉ)+μ2)\E\sum_i(e_i - \bar e)^2 = n(\sigma^2 + \mu^2) - n\big(\Var(\bar e) + \mu^2\big). With positive correlations, the naive estimate ignores nearly all of the contribution from ω\omega and γ\gamma, whose factors m−1m - 1 and n−mn - m do not vanish as nn grows. This is the variance of the CV estimate and its problem: it cannot be estimated without bias, and the obvious method underestimates it.

[ ]Measuring the Bengio-Grandvalet decompositionBrowser
# continúa la celda anterior: loss (R x n) son los errores por ejemplo con k = 5
C = np.cov(loss.T)                                  # covarianzas entre ejemplos, estimadas con las R réplicas
mismo = fold[:, None] == fold[None, :]
diag = np.eye(n, dtype=bool)
s2, om, ga = C[diag].mean(), C[mismo & ~diag].mean(), C[~mismo].mean()
m = n // k
print(f"sigma^2 = {s2:.4f}   omega = {om:.4f}   gamma = {ga:.4f}")
print(f"Var(CV): por la descomposición {s2/n + (m - 1)*om/n + (n - m)*ga/n:.4f}   medida {cv.var(ddof=1):.4f}")
print(f"E[s^2/n] del estimador ingenuo {np.mean(se_naive**2):.4f}")

# CV repetida: 10 particiones aleatorias distintas de cada conjunto
B = 10
rep = np.empty((R, B))
for b in range(B):
    fb = np.empty(n, int)
    fb[np.random.default_rng(b).permutation(n)] = np.arange(n) % k
    rep[:, b] = cv_ols(X, Y, fb).mean(1)
dentro = rep.var(1, ddof=1).mean()
print(f"\nvarianza de una CV {rep[:, 0].var(ddof=1):.4f}   de ella, debida a la partición {dentro:.4f}   "
      f"varianza de la media de {B} repeticiones {rep.mean(1).var(ddof=1):.4f}")

The decomposition reproduces measured variance, 0.19780.1978, while the naive estimator averages 0.11520.1152: 58% of the truth. Both covariances are small compared with σ2=4.69\sigma^2 = 4.69, but weigh (m−1)/n(m - 1)/n and (n−m)/n(n - m)/n, while σ2\sigma^2 weighs 1/n1/n. The second part measures repeated CV (repeated k-fold): repeat CV with different splits and average. Of total variance 0.19930.1993, only 0.04290.0429 (22%) comes from the split; the rest comes from the sample and no repetition removes it. With 10 repetitions variance falls to 0.15390.1539. Repetition is cheap and useful to prevent your number depending on the seed, but supplies no new data.

Splits that respect data structure

Everything above assumes the nn examples are independent and identically distributed and your model will see new examples from that distribution in production. When data have structure, random splitting breaks the second condition: validation no longer resembles deployment. We call splits that imitate how new data arrive structured splits.

  • Stratified. Every fold preserves dataset class proportions (in regression, sometimes quantiles of yy). This does not change what is estimated, but reduces split variance and avoids folds with no rare-class examples, frequent in imbalanced problems and making recall or AUC impossible to calculate in that fold. This is scikit-learn’s classification default.
  • Grouped. If there are multiple samples per unit (images per patient, sessions per user, files per repository, sentences per document) and production units will be new, all samples from one unit go into the same fold. Otherwise the model can succeed in validation by recognizing the unit (scanner, handwriting, coding style) rather than learning the task. GroupKFold assigns whole groups to folds, balancing sizes; StratifiedGroupKFold also tries to preserve class proportions, not always possible when labels belong to units.
  • Repeated. Repeat CV with BB random splits and average to remove split variance, as measured above. Combine with the preceding methods (RepeatedStratifiedKFold).
  • Time-based. If the model predicts the future, validation must lie after its training data. TimeSeriesSplit takes the last kk consecutive blocks of size ⌊n/(k+1)⌋\lfloor n/(k+1) \rfloor as successive validations, training each iteration on everything before the validation block (an expanding window); with max_train_size the window slides and forgets old data, useful when the process changes. gap leaves a gap between training and validation, necessary when a time’s label depends on later events (for example, five-day return). The version with purging and embargo, essential in finance, is purged cross-validation, and its relative walk-forward validation.
InteractiveHow folds are assigned
Samples in chronological order (left to right)
classpatientCACEBEDABFABGAAHFGCBGEBFCACEDDHDiter. 1iter. 2iter. 3iter. 4patientfuturetime →
  • training
  • validation
  • sick (●) or healthy (○)
  • patient leakage
  • trains on future data
Strategy
4
iteration 1 of 4
Training / validation24 / 8
Sick patients in validation (37.5% overall)4 of 8 (50 %)
Training samples from validation patients18
Training samples after validation begins23
Each fold mixes patients and times: in this iteration, 18 training samples belong to patients also in validation and 23 come after validation starts. The fraction of sick patients in validation ranges from 25% to 50%.
32 time-ordered samples from 8 patients (A to H); the label belongs to the patient (● sick, ○ healthy) and 3 of 8 are sick. Each row is a CV iteration: blue trains, orange validates, blank is unused. Below the active iteration, red rings mark training samples from a patient also in validation, and diamonds mark training samples after validation starts. Explore the five strategies: random k-fold has both leaks and fluctuating proportions; stratification balances proportions but retains leaks; grouping removes patient leakage; time-based methods remove future leakage. Sort columns by patient to see groups.

Notice what no strategy does alone: time-based splits still place patients on both sides, and grouped splitting still trains on the future. If both structures exist and deployment means “new patients in the future,” impose both constraints (validate on a time block and remove its patients from training). The general rule: the split must imitate the relationship between training and deployment data. If that relationship is a known distribution shift (another hospital, another country), the split should reproduce it; reliability covers this as validation under distribution shift.

How much does it matter? The next cell constructs two signal-free situations and evaluates them with a nearest-neighbor classifier (1-NN), which memorizes especially easily. The first has 40 patients with 6 images each; the label belongs to the patient and does not depend on images, but each patient has a distinctive “appearance” shared by their images. In the second, xtx_t (5 variables) and yty_t are independent random walks: there is no relationship to learn.

[ ]Structural leakage: groups and timeBrowser
class Uno_NN:
    def fit(self, X, y):
        self.X_, self.y_ = X, y
        return self
    def predict(self, X):
        d2 = (X**2).sum(1)[:, None] - 2 * X @ self.X_.T + (self.X_**2).sum(1)[None]
        return self.y_[d2.argmin(1)]

def cv_predict(model_cls, X, y, folds):
    pred = np.empty_like(y)
    for va in folds:
        tr = complemento(len(y), va)
        pred[va] = model_cls().fit(X[tr], y[tr]).predict(X[va])
    return pred

rng = np.random.default_rng(0)
P, por, dg = 40, 6, 20
grupos = np.repeat(np.arange(P), por)
y_pac = rng.permutation(np.r_[np.ones(P // 2, int), np.zeros(P // 2, int)])
yg = y_pac[grupos]
Xg = rng.standard_normal((P, dg))[grupos] * 2.0 + rng.standard_normal((P * por, dg))
acc_k = (cv_predict(Uno_NN, Xg, yg, kfold_indices(len(yg), 5)) == yg).mean()
acc_g = (cv_predict(Uno_NN, Xg, yg, group_kfold_indices(grupos, 5)) == yg).mean()
print(f"Pacientes, sin señal:  k-fold aleatorio {acc_k:.3f}   GroupKFold {acc_g:.3f}")

def r2(y, yhat):
    return 1 - ((y - yhat) ** 2).sum() / ((y - y.mean()) ** 2).sum()

T = 300
xt = np.cumsum(rng.standard_normal((T, 5)), axis=0)
yt = np.cumsum(rng.standard_normal(T))
r2_k = r2(yt, cv_predict(Uno_NN, xt, yt, kfold_indices(T, 5)))
r2_t = [r2(yt[va], Uno_NN().fit(xt[tr], yt[tr]).predict(xt[va])) for tr, va in time_series_splits(T, 5)]
print(f"Paseos independientes:  R² con k-fold aleatorio {r2_k:.3f}   R² por bloque con la partición temporal {np.round(r2_t, 2)}")

With patients on both sides, 1-NN achieves 100% despite no image-diagnosis relationship: each image’s nearest neighbor is another image of the same patient, with the same label. Grouped splitting gives 56.2%, compatible with chance: since the label belongs to the patient, accuracy is really decided on 40 patients, and 40 coin tosses have standard deviation 0.25/40≈0.08\sqrt{0.25/40} \approx 0.08. For the series, random k-fold gives R2=0.967R^2 = 0.967 between independent walks: a time’s nearest neighbor in xx space is almost always adjacent, with similar yy because the walks are continuous. With temporal splits all R2R^2 values are negative: the model predicts worse than the block’s own mean, appropriate for no signal. Neither inflated figure warns you: 100% or R2R^2 of 0.97 look good.

Data leakage

Kapoor and Narayanan’s (2023) taxonomy has eight types in three families. Keep it handy as a checklist:

TypeWhat happensExamplePrevention
L1.1 No test settraining error is reported“99% accuracy” of the fitted modelCV or holdout
L1.2 Preprocessing with training and testscaling, imputation or reduction fitted on everythingglobal mean for imputationpipeline
L1.3 Feature selection with training and testfeatures chosen using validation labels20 most correlated genes, then CVpipeline
L1.4 Duplicatessame (or nearly same) example on both sidesrepeated photos, rows merged twicededuplicate, split by group
L2 Illegitimate featuresa feature contains or anticipates the target“refunded amount” to predict fraudaudit each feature
L3.1 Temporal leakagetraining uses future informationrandom k-fold for time seriestime-based split
L3.2 Train-test dependenceshared units on both sidesimages from the same patientgroup split
L3.3 Test sampling biastest does not represent real useevaluating only easy casesdesign the test

You have seen the L3 family. No procedure solves L2: for each feature, ask whether its value is known at prediction time. Kaufman and coauthors cite the KDD Cup 2008 mammography cancer-detection contest, where patient ID turned out to contain predictive diagnosis information (documented by Rosset and coauthors, the competition winners). An identifier should predict nothing; when it does, the data-generation process has left a trace of the target. L1.2 and L1.3, by contrast, slip in through code order without anyone deciding to introduce them; these are what we examine next.

Leakage through feature selection

Ambroise and McLachlan (2002) studied papers building tumor classifiers with a few genes selected from thousands and reporting CV errors near zero. Their colon cancer data had n=62n = 62 samples and p=2000p = 2000 genes. The error was order: genes were selected using all samples and CV performed afterward with those genes, so validation labels participated in selection. To measure the effect they randomly permuted colon-set labels, leaving no gene-class relationship, and repeated the procedure. Leave-one-out CV computed after selection gave average error near zero with 128 genes and around 10% with only 8. Ten-fold CV with selection inside each fold and .632+ bootstrap gave 0.40–0.45, appropriate for an uninformative dataset.

The mechanism is a maximal inequality in action. With yy independent of everything, each feature’s sample correlation with yy is approximately N(0,1/n)\Normal(0, 1/n), and among pp features the largest are around 2log⁡p/n\sqrt{2\log p / n}: with n=62n = 62 and p=2000p = 2000, about 0.500.50. Chosen using all rows, those correlations also hold in validation rows, because those rows partly produced them. The classifier learns nothing about the population; it learns noise in these 62 rows, and CV evaluates it on those same rows.

InteractiveLeakage simulator
Accuracy on 20 pure-noise datasets (n=60n = 60, p=5000p = 5000, stratified 5-fold CV) · calculating…
chancetraining (yours)CV, your configurationCV, correct pipeline
  • CV with your configuration
  • CV with the correct pipeline (same data)
  • training accuracy
  • mean
Target encoding of the categorical feature
5000
20
CV accuracy, your configuration…
CV accuracy, correct pipeline…
Training accuracy (yours)…
True accuracy of any model50% (no signal)
Pure-noise data: n=60n = 60 rows, pp normal features and a balanced label independent of everything, plus an independent categorical feature with LL levels. The classifier is diagonal LDA (each feature is weighted by the class-mean difference divided by its variance, estimated in training) and CV is stratified 5-fold. Each point is one of 20 datasets; the blue row is the correct pipeline with the same data and folds. Start with feature selection outside CV; turn it off; lower pp. Then try the three target-encoding variants and compare training accuracy with CV accuracy.

Four things the simulator shows, explained below. Selection outside CV turns noise into accuracy of 90% or more, and leakage grows with pp: more variables offer more spurious correlations. Scaling on all rows changes nothing here because diagonal LDA is invariant to each feature’s scale; generally it is mild leakage since the scaler does not inspect yy, but remains a procedural error and can matter with little data or richer transforms (PCA, neighbor imputation). Target encoding on all data invents signal from nothing. Target encoding without cross-fitting inside the pipeline gives honest CV yet a damaged model.

A minimal pipeline from scratch

The way to avoid L1.2 and L1.3 is not to rely on remembering: make preprocessing part of the model so CV refits it in every fold.

[ ]Minimal pipeline and the Ambroise-McLachlan experimentBrowser
class SelectTopK:
    """Se queda con las m columnas de mayor |correlación| con y en los datos de fit."""
    def __init__(self, m):
        self.m = m
    def fit(self, X, y):
        Xc, yc = X - X.mean(0), y - y.mean()
        score = np.abs(Xc.T @ yc) / (np.sqrt((Xc**2).sum(0)) * np.sqrt((yc**2).sum()) + 1e-12)
        self.idx_ = np.sort(np.argsort(-score, kind="stable")[: self.m])
        return self
    def transform(self, X):
        return X[:, self.idx_]

class Standardize:
    def fit(self, X, y=None):
        self.mu_, self.sd_ = X.mean(0), X.std(0) + 1e-12
        return self
    def transform(self, X):
        return (X - self.mu_) / self.sd_

class NearestCentroid:
    def fit(self, X, y):
        self.classes_ = np.unique(y)
        self.C_ = np.stack([X[y == c].mean(0) for c in self.classes_])
        return self
    def predict(self, X):
        d2 = ((X[:, None, :] - self.C_[None]) ** 2).sum(-1)
        return self.classes_[d2.argmin(1)]

class Pipeline:
    """fit encadena fit y transform de cada paso con los datos que recibe; predict solo transforma."""
    def __init__(self, steps):
        self.steps = steps
    def fit(self, X, y):
        for s in self.steps[:-1]:
            X = s.fit(X, y).transform(X)
        self.steps[-1].fit(X, y)
        return self
    def predict(self, X):
        for s in self.steps[:-1]:
            X = s.transform(X)
        return self.steps[-1].predict(X)

def cv_accuracy(make_model, X, y, folds):
    """Exactitud de CV: cada pliegue se predice con un modelo NUEVO ajustado solo con el resto."""
    pred = np.empty_like(y)
    for va in folds:
        tr = complemento(len(y), va)
        pred[va] = make_model().fit(X[tr], y[tr]).predict(X[va])
    return (pred == y).mean()

# Ruido puro con n = 62, como el conjunto de colon; 20 repeticiones por cada p
n, m, k, reps = 62, 10, 5, 20
for p in (100, 500, 2000):
    fuera, dentro = [], []
    for r in range(reps):
        rng = np.random.default_rng(100 * p + r)
        X = rng.standard_normal((n, p))
        y = rng.permutation(np.r_[np.ones(n // 2, int), np.zeros(n - n // 2, int)])
        folds = stratified_naive(y, k, seed=r)
        S = SelectTopK(m).fit(X, y).idx_                    # MAL: elige con todas las filas
        fuera.append(cv_accuracy(lambda: Pipeline([Standardize(), NearestCentroid()]), X[:, S], y, folds))
        dentro.append(cv_accuracy(lambda: Pipeline([SelectTopK(m), Standardize(), NearestCentroid()]), X, y, folds))
    print(f"p = {p:4d}:  selección antes de la CV {np.mean(fuera):.3f} ± {np.std(fuera):.3f}   "
          f"selección dentro del pipeline {np.mean(dentro):.3f} ± {np.std(dentro):.3f}")

With 10 features chosen before CV, accuracy on noise is 0.7600.760 with p=100p = 100, 0.8350.835 with p=500p = 500 and 0.9040.904 with p=2000p = 2000. With the selector inside the pipeline, it is 0.4980.498, 0.4950.495 and 0.5190.519, compatible with chance (standard deviation across repetitions is about 9 points, so each mean’s standard error is about 2). The function cv_accuracy receives a model factory, not a model: each fold constructs a fresh one, with nothing fitted beforehand. That detail is the whole trick.

Encoding categorical features

Linear models, networks and k-NN need numbers. Categorical encoding translates a feature with LL levels into numeric columns, and each encoding has its place.

  • One-hot. One indicator per level: LL columns (or L−1L - 1 if the model has an unregularized intercept, because all LL sum to 1 and are collinear with it). It imposes no order or distances. Problems: dimensionality grows with LL, rare levels produce nearly empty columns, and a new production level has no column (handle_unknown="ignore" encodes it as all zeros).
  • Ordinal. One integer per level. Appropriate when a real order exists (size S < M < L, education level) and the model can exploit it; for nominal levels it imposes arbitrary order on a linear model, though it does little harm to a tree, which can split using thresholds.
  • Target encoding. Replace each level with a summary of yy at that level. For high-cardinality features (postal codes, product IDs), it is often the only reasonable choice for a linear model. With m-estimate smoothing (Micci-Barreca, 2001, proposed such a mixture for high-cardinality features), level cc with ncn_c rows is encoded as
enc(c)=∑i:ci=cyi+a yˉnc+a,\mathrm{enc}(c) = \frac{\sum_{i: c_i = c} y_i + a\,\bar y}{n_c + a},

a level mean shrunk toward global mean yˉ\bar y with strength aa: levels with few rows barely depart from yˉ\bar y. For binary yy it is the posterior mean of the level probability with prior Beta(ayˉ,a(1−yˉ))\mathrm{Beta}(a\bar y, a(1 - \bar y)), the same mechanism as Laplace smoothing.

Target encoding itself leaks if computed using the rows it later encodes. Consider row ii of a level with ncn_c rows: its encoding contains its own label with weight 1/(nc+a)1/(n_c + a). If yiy_i changes from 0 to 1, holding the global mean fixed, enc(ci)\mathrm{enc}(c_i) rises exactly 1/(nc+a)1/(n_c + a). With nc=1n_c = 1 and a=1a = 1, encoding is (yi+yˉ)/2(y_i + \bar y)/2: it perfectly separates classes without the feature having any relationship to yy. There are two ways to err, and the second is subtle:

  1. Encode all data before CV (L1.2): validation-row encodings contain their labels. CV misleads.
  2. Encode inside the pipeline but without cross-fitting: the encoder fits training rows and transforms those same rows. CV is honest because validation rows are encoded using training statistics. But the model trains on a column where each row contains its own label, finds it highly predictive and gives it enormous weight, while the column is much less informative on new data. CV does not lie: it correctly says the model is bad.

The second problem’s solution is cross-fitting: within training, encode each row with statistics calculated on other rows, splitting training into KK parts and encoding each using the other K−1K - 1. Validation or production rows are encoded using all training data. Thus in training, each row’s encoding is independent of its label given the other data, as it will be in production. CatBoost solves the same problem differently with ordered statistics: encode each row using only preceding ones in a random permutation.

[ ]Target encoding: leakage and the pipeline from scratchBrowser
class MEstimateEncoder:
    """Sustituye la columna categórica `col` por (suma de y en el nivel + a·media global) / (cuenta + a)."""
    def __init__(self, col, a=1.0):
        self.col, self.a = col, a
    def fit(self, X, y):
        cat = X[:, self.col].astype(int)
        L = cat.max() + 1
        self.g_ = y.mean()
        s = np.bincount(cat, weights=y, minlength=L)
        c = np.bincount(cat, minlength=L)
        self.enc_ = (s + self.a * self.g_) / (c + self.a)
        return self
    def transform(self, X):
        X = X.astype(float).copy()
        cat = X[:, self.col].astype(int)
        conocido = cat < len(self.enc_)
        X[:, self.col] = np.where(conocido, self.enc_[np.minimum(cat, len(self.enc_) - 1)], self.g_)
        return X

# Una sola variable: un código casi único (L = 300 niveles para n = 200 filas), sin relación con y
n, L, k, reps = 200, 300, 5, 30
res = {"codificar antes de la CV": [], "codificar dentro del pipeline": [], "entrenamiento (dentro)": []}
for r in range(reps):
    rng = np.random.default_rng(r)
    y = rng.permutation(np.r_[np.ones(n // 2, int), np.zeros(n - n // 2, int)])
    X = rng.integers(0, L, n)[:, None].astype(float)
    folds = stratified_naive(y, k, seed=r)
    Xe = MEstimateEncoder(0).fit(X, y).transform(X)              # MAL: cada fila lleva su propia y
    res["codificar antes de la CV"].append(cv_accuracy(lambda: NearestCentroid(), Xe, y, folds))
    res["codificar dentro del pipeline"].append(cv_accuracy(lambda: Pipeline([MEstimateEncoder(0), NearestCentroid()]), X, y, folds))
    pipe = Pipeline([MEstimateEncoder(0), NearestCentroid()]).fit(X, y)
    res["entrenamiento (dentro)"].append((pipe.predict(X) == y).mean())
for nombre, v in res.items():
    print(f"{nombre:30s} {np.mean(v):.3f} ± {np.std(v):.3f}")

Encoding before CV makes a code unrelated to yy “predict” with 86.2% accuracy. Inside the pipeline, CV reports 0.4990.499, the truth. But the same pipeline correctly predicts 87.4% of its own training rows: the second trap, whose real cost you will measure with scikit-learn at the end on a problem with signal. You implement cross-fitting in a coding exercise.

Detecting leakage

No list is exhaustive, but these checks catch most cases:

  • Results too good. A 99% score where literature gets 80%, or a simple model greatly outperforming everything published, deserves an audit before celebration.
  • One feature dominates. If one feature’s importance greatly exceeds the rest, ask when its value is known. This is a typical L2 symptom.
  • Training and validation are distinguishable. Train a classifier to distinguish training rows from test rows (adversarial validation): if successful, the samples do not come from the same distribution, and the features used often point to temporal leakage or sampling bias.
  • Exact or near matches. Look for identifiers, image hashes or nearly identical rows on both sides of the split.
  • Procedure order. Walk through code looking for any fit or statistic (mean, quantile, vocabulary, selection) calculated before splitting.

Nested cross-validation

So far we have evaluated a fixed procedure. In practice you try NN configurations (hyperparameters, preprocessing, algorithms), keep the best CV score and report it. That last step is another kind of leakage: the winning score was used for selection and is therefore biased upward. This is the same phenomenon as feature selection, except you now select models.

To see this in its purest form, suppose the NN configurations have the same true performance μ\mu and CV estimates s^j=μ+σZj\hat s_j = \mu + \sigma Z_j with independent standard normals ZjZ_j. You report max⁡js^j\max_j \hat s_j, whose expectation is

E[max⁡js^j]=μ+σ eN,eN=E[max⁡(Z1,…,ZN)]=∫−∞∞z Nϕ(z)Φ(z)N−1 ⁣dz,\E\big[\max_j \hat s_j\big] = \mu + \sigma\,e_N, \qquad e_N = \E\big[\max(Z_1, \dots, Z_N)\big] = \int_{-\infty}^{\infty} z\,N\phi(z)\Phi(z)^{N-1}\dd z,

obtained from the density of the maximum of NN independent variables, Nϕ(z)Φ(z)N−1N\phi(z)\Phi(z)^{N-1} (order statistics). The Gaussian maximal inequality gives eN≤2log⁡Ne_N \le \sqrt{2\log N}: bias grows without bound, though slowly, with the number of things tried. Similar configurations have correlated errors: with correlation ρ\rho for each pair, s^j=μ+σ(ρ W+1−ρ Zj)\hat s_j = \mu + \sigma(\sqrt{\rho}\,W + \sqrt{1 - \rho}\,Z_j), and shared part WW does not affect the winner, so bias is σ1−ρ eN\sigma\sqrt{1 - \rho}\,e_N.

[ ]The bias of the best of NBrowser
import numpy as np
from scipy import integrate, stats

def e_max(N):
    """E[máximo de N normales estándar independientes]."""
    f = lambda z: z * N * stats.norm.pdf(z) * stats.norm.cdf(z) ** (N - 1)
    return integrate.quad(f, -10, 10)[0]

rng = np.random.default_rng(0)
print("   N    e_N   simulado   sqrt(2 log N)")
for N in (1, 2, 5, 10, 20, 100):
    sim = rng.standard_normal((20000, N)).max(1).mean()
    print(f"{N:4d}  {e_max(N):5.3f}  {sim:8.3f}   {np.sqrt(2 * np.log(N)):8.3f}")
print(f"\n20 configuraciones de rendimiento 0.80 con sigma = 0.02: E[mejor] = {0.80 + 0.02 * e_max(20):.4f}")

With 20 equivalent configurations, e20=1.867e_{20} = 1.867: the best score exceeds truth by nearly two CV standard deviations. Cawley and Talbot (2010) showed that such overfitting of the selection criterion can degrade performance surprisingly much, and in their experiments its effect was often as large as performance differences among learning algorithms. Many published comparisons may therefore measure how much was searched rather than which algorithm is better.

Two clarifications prevent common confusion. Nested CV does not choose the model: each outer fold can choose a different configuration, correctly, because it evaluates the selection recipe. The delivered model comes from applying that recipe (inner CV) to all data. Like any CV estimate, the nested estimate targets expected error of that recipe with sample size n(1−1/kext)n(1 - 1/k_{\text{ext}}), with all you have seen about its variance.

InteractiveBias of the best of N
Distribution of the reported score over 250 repetitions · calculating…
truth 0.80prediction
  • best score in the search
  • nested CV
  • true accuracy
  • prediction for the maximum
20
200
5
0.80
0.00
Mean of the best of NN (bias)…
Prediction p+σ1−ρ E[max⁡]p + \sigma\sqrt{1-\rho}\,\mathbb{E}[\max]0.853
Mean nested CV…
Standard deviation: best of N / nested…
σ\sigma of one CV and ρ=λ2\rho = \lambda^20.028 and 0.00
No configuration is better than another, but the best score averages NaN: NaN points of pure optimism (the normal approximation predicts 1.87·σ = 5.3 points). Reporting that number promises performance that does not exist.
Explicit model: NN configurations with identical true accuracy pp. On nn validation examples, each configuration gets each example right with probability pp; with probability λ\lambda it copies the example's “common” outcome, so two configurations' successes correlate at ρ=λ2\rho = \lambda^2. Across 250 repetitions, compute the best of NN scores (orange) and nested CV (blue), which for each outer fold selects the best-accuracy configuration on the other examples and scores it on that fold. The dashed line predicts p+σ1−ρ eNp + \sigma\sqrt{1 - \rho}\,e_N with σ=p(1−p)/n\sigma = \sqrt{p(1-p)/n}. Increase NN, change nn and λ\lambda, and check that nested CV stays at pp for any kk.

The interactive’s model trains nothing: it only samples successes. Hence outer-fold count does not change nested CV’s bias, zero for any kk; with a real algorithm, kk also changes pessimistic bias from training on less data. Notice standard deviations too: at initial values nested CV is substantially wider than the maximum, and even than one CV (the readout’s σ\sigma). Each outer fold may choose a different configuration, and one fold’s successes helped select configurations for the others, so their scores are not independent. Nested CV trades bias for variance, so its between-fold spread is not a reliable standard error either. In the next cell the search is real: 10 configurations of a pipeline choosing the best mm features, with m∈{1,2,3,5,8,13,21,34,55,89}m \in \{1, 2, 3, 5, 8, 13, 21, 34, 55, 89\}, on signal-free data.

[ ]Nested CV from scratchBrowser
def nested_cv_accuracy(make_model, grid, X, y, k_out=5, k_in=5, seed=0):
    """Bucle externo para evaluar; en cada pliegue externo, una CV interna (solo con su entrenamiento) elige."""
    pred = np.empty_like(y)
    elegidas = []
    for f, va in enumerate(stratified_naive(y, k_out, seed)):
        tr = complemento(len(y), va)
        inner = stratified_naive(y[tr], k_in, seed + 1000 + f)
        scores = [cv_accuracy(lambda: make_model(g), X[tr], y[tr], inner) for g in grid]
        best = grid[int(np.argmax(scores))]
        elegidas.append(best)
        pred[va] = make_model(best).fit(X[tr], y[tr]).predict(X[va])
    return (pred == y).mean(), elegidas

make = lambda m: Pipeline([SelectTopK(m), Standardize(), NearestCentroid()])
grid = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
n, p, reps = 60, 300, 16
mejor, anidada = [], []
for r in range(reps):
    rng = np.random.default_rng(r)
    X = rng.standard_normal((n, p))
    y = rng.permutation(np.r_[np.ones(n // 2, int), np.zeros(n - n // 2, int)])
    folds = stratified_naive(y, 5, seed=r)
    mejor.append(max(cv_accuracy(lambda: make(g), X, y, folds) for g in grid))
    acc, elegidas = nested_cv_accuracy(make, grid, X, y, seed=r)
    anidada.append(acc)
print(f"mejor puntuación de la búsqueda  {np.mean(mejor):.3f} ± {np.std(mejor):.3f}")
print(f"CV anidada                        {np.mean(anidada):.3f} ± {np.std(anidada):.3f}")
print("configuraciones elegidas en los pliegues externos de la última repetición:", elegidas)

Across 16 signal-free datasets, the search’s best score averages 0.5590.559 and nested CV 0.4730.473, just over one standard error (0.082/16≈0.020.082/\sqrt{16} \approx 0.02) from the true 0.5. Measured search bias, about 6 points, is less than predicted for 10 independent configurations: accuracy measured on 60 examples has σ≈0.25/60=0.065\sigma \approx \sqrt{0.25/60} = 0.065, and e10 σ≈1.539⋅0.065=0.10e_{10}\,\sigma \approx 1.539 \cdot 0.065 = 0.10. They are not independent: selecting 21 or 34 variables gives nearly identical predictions, and correlation reduces bias by factor 1−ρ\sqrt{1 - \rho}. The final line shows each outer fold can choose a different mm.

The scikit-learn version

Everything above has an equivalent in sklearn.model_selection, sklearn.pipeline and sklearn.compose:

From scratchscikit-learn
kfold_indices, stratified_naive, group_kfold_indices, time_series_splitsKFold, StratifiedKFold, GroupKFold, TimeSeriesSplit, RepeatedStratifiedKFold, StratifiedGroupKFold
PipelinePipeline / make_pipeline, and ColumnTransformer to treat columns differently
SelectTopK, Standardize, NearestCentroidSelectKBest(f_classif), StandardScaler, NearestCentroid
MEstimateEncoderTargetEncoder (with cross-fitting in fit_transform), OneHotEncoder, OrdinalEncoder
cv_accuracycross_val_score, cross_validate, cross_val_predict
nested_cv_accuracycross_val_score(GridSearchCV(...))

First, check our implementation does the same. For two classes, the f_classif F statistic is F=(n−2) r2/(1−r2)F = (n - 2)\,r^2/(1 - r^2), increasing in ∣r∣\abs{r}, so it selects the same features as our SelectTopK; and cross_val_predict accepts a list of (training, validation) pairs, so we can provide our exact folds.

[ ]The same CV with scikit-learnBrowser
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.model_selection import GroupKFold, TimeSeriesSplit, cross_val_predict
from sklearn.neighbors import NearestCentroid as SkNearestCentroid
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

rng = np.random.default_rng(7)
n, p, m = 62, 2000, 10
X = rng.standard_normal((n, p))
y = rng.permutation(np.r_[np.ones(31, int), np.zeros(31, int)])
cv_list = [(complemento(n, va), va) for va in stratified_naive(y, 5, seed=0)]

nuestro = np.empty(n, int)
for tr, va in cv_list:
    nuestro[va] = Pipeline([SelectTopK(m), Standardize(), NearestCentroid()]).fit(X[tr], y[tr]).predict(X[va])
sk = cross_val_predict(make_pipeline(SelectKBest(f_classif, k=m), StandardScaler(), SkNearestCentroid()), X, y, cv=cv_list)
print("mismas predicciones que scikit-learn:", np.array_equal(nuestro, sk), "  exactitud", round((sk == y).mean(), 3))

grupos = rng.integers(0, 12, n)
iguales_g = all(np.array_equal(np.sort(va), vb)
                for (_, va), vb in zip(GroupKFold(5).split(X, y, grupos), group_kfold_indices(grupos, 5)))
iguales_t = all(np.array_equal(a[0], b[0]) and np.array_equal(a[1], b[1])
                for a, b in zip(TimeSeriesSplit(5, gap=2, max_train_size=20).split(X), time_series_splits(n, 5, gap=2, max_train=20)))
print("GroupKFold coincide:", iguales_g, "  TimeSeriesSplit coincide:", iguales_t)

Now a problem with signal and every column type: two numeric (one 10% missing), one nominal with 3 levels, one ordinal (sizes S, M, L), and a 400-level code with a real but noisy effect. ColumnTransformer applies a separate pipeline to each group of columns. Compare scikit-learn’s TargetEncoder, whose fit_transform performs cross-fitting (5-fold StratifiedKFold for a binary target), with a wrapper misusing it: fit followed by transform on the same rows. Measure on a separate test set used for nothing else.

[ ]ColumnTransformer and target encoding with and without cross-fittingBrowser
import warnings
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import StratifiedKFold, cross_validate, train_test_split
from sklearn.preprocessing import OneHotEncoder, OrdinalEncoder, TargetEncoder
warnings.filterwarnings("ignore", category=FutureWarning)   # versiones recientes avisan de cambios en TargetEncoder

def datos(n, seed):
    rng = np.random.default_rng(seed)
    efecto_codigo = np.random.default_rng(999).normal(0, 0.6, 400)     # el efecto real de cada código
    df = pd.DataFrame({
        "x1": rng.normal(size=n), "x2": rng.normal(size=n),
        "color": rng.choice(["rojo", "verde", "azul"], n),
        "talla": rng.choice(["S", "M", "L"], n),
        "codigo": rng.integers(0, 400, n).astype(str),
    })
    logit = (0.8 * df.x1 - 0.5 * df.x2 + df.color.map({"rojo": 0.4, "verde": 0.0, "azul": -0.4})
             + df.talla.map({"S": -0.5, "M": 0.0, "L": 0.5}) + efecto_codigo[df.codigo.astype(int)])
    y = (rng.uniform(size=n) < 1 / (1 + np.exp(-logit))).astype(int).to_numpy()
    df.loc[rng.uniform(size=n) < 0.1, "x1"] = np.nan
    return df, y

class SinCrossFit(BaseEstimator, TransformerMixin):
    """TargetEncoder usado mal: fit y luego transform sobre las mismas filas."""
    def fit(self, X, y):
        self.te_ = TargetEncoder(random_state=0).fit(X, y)
        return self
    def transform(self, X):
        return self.te_.transform(X)

def preproc(te):
    return ColumnTransformer([
        ("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), ["x1", "x2"]),
        ("nom", OneHotEncoder(handle_unknown="ignore"), ["color"]),
        ("ord", OrdinalEncoder(categories=[["S", "M", "L"]]), ["talla"]),
        ("alta", te, ["codigo"]),
    ])

df, y = datos(1500, 0)
Xtr, Xte, ytr, yte = train_test_split(df, y, test_size=0.5, random_state=0, stratify=y)
cv5 = StratifiedKFold(5, shuffle=True, random_state=0)
for nombre, te in [("con cross-fitting", TargetEncoder(random_state=0)), ("sin cross-fitting", SinCrossFit())]:
    pipe = make_pipeline(preproc(te), LogisticRegression(max_iter=1000))
    r = cross_validate(pipe, Xtr, ytr, cv=cv5, scoring="roc_auc", return_train_score=True)
    pipe.fit(Xtr, ytr)
    auc = roc_auc_score(yte, pipe.predict_proba(Xte)[:, 1])
    print(f"{nombre:18s} AUC entrenamiento {r['train_score'].mean():.3f}   CV {r['test_score'].mean():.3f}   "
          f"prueba {auc:.3f}   coeficiente del código {pipe[-1].coef_[0][-1]:.2f}")

With cross-fitting: training AUC 0.8170.817, CV 0.7530.753 and test 0.7090.709, and the code gets coefficient 0.740.74. Without cross-fitting: training 0.9540.954, CV 0.6710.671 and test 0.6050.605, with coefficient 6.266.26 for the code. The model relied eight times more on a column containing each training row’s own label, losing 10 AUC points on new data. CV detects it (0.671 versus 0.753): evaluation has no leakage; the model is worse. Test being 4–7 points below CV in both cases is not a CV failure: CV estimates the recipe’s average error, while the particular model trained on these 750 rows and measured on another specific 750 deviates from that mean. This is Err\mathrm{Err} versus ErrXY\mathrm{Err}_{XY} in action; the ordering and size of the difference between variants are robust. The detail making scikit-learn’s pipeline correct: Pipeline.fit calls fit_transform at each intermediate step, and TargetEncoder.fit_transform cross-fits, whereas fit(X, y).transform(X) does not. The documentation warns of this; other transformers would make the two calls equivalent.

Finally, nested CV with scikit-learn is one line: GridSearchCV is an estimator, and cross_val_score refits it (including search) in every outer fold.

[ ]Nested CV with GridSearchCV inside cross_val_scoreBrowser
from sklearn.model_selection import GridSearchCV, cross_val_score

pipe = make_pipeline(preproc(TargetEncoder(random_state=0)), LogisticRegression(max_iter=1000))
grid = GridSearchCV(pipe, {"logisticregression__C": [0.01, 0.1, 1, 10]},
                    cv=StratifiedKFold(5, shuffle=True, random_state=1), scoring="roc_auc")
grid.fit(Xtr, ytr)
anidada = cross_val_score(grid, Xtr, ytr, cv=StratifiedKFold(5, shuffle=True, random_state=2), scoring="roc_auc")
print(f"mejor puntuación de la rejilla {grid.best_score_:.3f} (C = {grid.best_params_['logisticregression__C']})")
print(f"CV anidada {anidada.mean():.3f}   por pliegue {np.round(anidada, 3)}")

Here the grid has only 4 highly correlated values, and optimistic bias is small: 0.7520.752 versus 0.7480.748. This will not always hold; with large grids, long random searches or many manually tried preprocessing decisions, bias grows like eNe_N. The next lesson on hyperparameter tuning revisits this with real searches.

Common mistakes

Exercises

QuizMedical images
You have 5000 radiographs from 800 patients (several per patient) and want to estimate classifier performance on new patients. What cross-validation split do you use?
QuizWhat does CV estimate?
You fit a model on your nn observations and calculate 10-fold CV. What does that number best estimate?
QuizLeakage or not?
Which procedures introduce leakage into the CV estimate?

More than one answer may be correct.

NumericThe best of 20
You test 20 configurations with the same true performance, 0.800.80. Their CV estimates are independent with standard deviation 0.020.02. Approximately what is the expected best score?
NumericWeight of a row's own label
You encode a categorical feature with m-estimate smoothing a=2a = 2 using all rows. One level has nc=3n_c = 3 rows. If one row's binary label changes from 0 to 1 (and nothing else changes except the global mean, treated as fixed across thousands of rows), how much does that row's encoding change?
ProofNo unbiased quadratic estimator
Prove: Let CV^=1n∑iei\widehat{\mathrm{CV}} = \frac{1}{n}\sum_i e_i with kk folds of size m=n/km = n/k, Eei=μ\mathbb{E}e_i = \mu and the lesson's covariance structure (σ2,ω,γ)(\sigma^2, \omega, \gamma). No quadratic form θ^=∑i,jWijeiej\hat\theta = \sum_{i,j} W_{ij}e_ie_j is an unbiased estimator of Var(CV^)\mathrm{Var}(\widehat{\mathrm{CV}}) for all possible values of (μ,σ2,ω,γ)(\mu, \sigma^2, \omega, \gamma).
0
Recall Var(CV^)=σ2n+m−1nω+n−mnγ\mathrm{Var}(\widehat{\mathrm{CV}}) = \frac{\sigma^2}{n} + \frac{m-1}{n}\omega + \frac{n-m}{n}\gamma.

Step 1 of 4. What is E[eiej]\E[e_ie_j]?

CodeTruly stratified k-fold
Implement stratified_kfold_indices(y, k, seed), returning a list of k validation-index arrays such that: (1) together they cover 0..n-1 without repetition; (2) for each class, counts in any two folds differ by at most 1; (3) any two fold sizes differ by at most 1; (4) assignment is random and reproducible with np.random.default_rng(seed). The lesson's naive allocation, starting every class at fold 0, satisfies (2) but not (3). Labels may be any comparable type (integers, strings).
import numpy as np

def stratified_kfold_indices(y, k, seed=0):
  """Lista de k arrays de índices de validación, estratificados por clase y de tamaños equilibrados."""
  y = np.asarray(y)
  rng = np.random.default_rng(seed)
  # tu código
  return []
Shift+Enter to run
CodeTarget encoder with cross-fitting
Complete CrossFitTargetEncoder(a, k, seed) for one categorical column (1-D array of hashable values) and a binary or real target. fit_transform(cats, y) must return cross-fitted training-row encodings: split rows with perm = np.random.default_rng(seed).permutation(n) and assign position j in perm to part j % k; encode each row using m-estimate (∑y+ayˉ)/(nc+a)(\sum y + a\bar y)/(n_c + a) computed only from other parts' rows (including their mean yˉ\bar y). Also save statistics from all rows so transform(cats) encodes new data using the full-training m-estimate and unseen levels using the global mean. The starter code is the leaky version.
import numpy as np

class CrossFitTargetEncoder:
  def __init__(self, a=1.0, k=5, seed=0):
      self.a, self.k, self.seed = a, k, seed

  def _stats(self, cats, y):
      g = float(np.mean(y))
      sums, counts = {}, {}
      for c, v in zip(cats, y):
          sums[c] = sums.get(c, 0.0) + v
          counts[c] = counts.get(c, 0) + 1
      enc = {c: (sums[c] + self.a * g) / (counts[c] + self.a) for c in sums}
      return enc, g

  def fit_transform(self, cats, y):
      cats, y = np.asarray(cats), np.asarray(y, dtype=float)
      self.enc_, self.g_ = self._stats(cats, y)
      return self.transform(cats)          # FUGA: cada fila se codifica con su propia etiqueta

  def transform(self, cats):
      return np.array([self.enc_.get(c, self.g_) for c in np.asarray(cats)])
Shift+Enter to run

Summary

Key idea
A performance estimate is honest only if every decision producing it (preprocessing, feature selection, encoding, hyperparameter choice) is made without looking at evaluation data, and if the split imitates the relationship between training and deployment data.
  • kk-fold CV validates each example once with a model that has not seen it. It has pessimistic bias from training on n(1−1/k)n(1-1/k) observations; k=5k = 5 or 1010 is a good compromise, and LOOCV is cheap for linear models.
  • CV estimates expected procedure error, Err\mathrm{Err}, not error of the delivered model, ErrXY\mathrm{Err}_{XY}: in the linear example its correlation with the latter was virtually zero.
  • Its variance has three components (σ2\sigma^2, ω\omega, γ\gamma) and no universal unbiased estimator; the naive estimate understates it and textbook intervals fail to cover. Repeating CV removes only the part due to the split.
  • Stratify classification, group multiple samples per unit, and respect time when predicting the future. With groups or series, random k-fold can give spectacular results without any signal.
  • Common leakage (preprocessing or selection on all data, illegitimate features, duplicates, future information) is prevented by pipelines refitted within each fold and by auditing every feature.
  • Target encoding needs cross-fitting even within a pipeline; TargetEncoder.fit_transform does it and fit(...).transform(...) does not.
  • The best score in a search is biased by about σ1−ρ eN\sigma\sqrt{1-\rho}\,e_N; nested CV evaluates the full search and removes that bias.