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
- 11Holdout train, validation and test splitClosed-form leave-one-out cross-validationConfusion matrix and derived metricsRegression metricsRidge regressionHandling class imbalance
- 05Bias of an estimatorMean squared error bias-variance decompositionNonparametric bootstrap
- 04Order statisticsMaximal inequality for sub-Gaussian variables
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 , measured accuracy is a binomial divided by 200 with standard deviation : a 95% interval spans 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 into blocks, train 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 , the entire procedure, not one particular model: the models differ and none is the one you deliver, which is trained on all observations. Second, loss 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 figures; this differs from computing it on concatenated predictions because the 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 observations rather than , and a model trained on fewer data is worse on average. Thus has pessimistic bias depending on the slope of the learning curve between and . One case can be calculated exactly: for least-squares linear regression with , noise variance and training observations, expected prediction error is
because and the inverse Wishart mean is . With and , , while 5 folds train on 32 observations and estimate : 10% pessimism. With , training uses 20 observations and bias rises sharply.
LOOCV minimizes that bias because each model uses observations. In exchange it costs fits, except for models linear in , where you already know the closed-form LOOCV formula: using residuals and the hat-matrix diagonal from one fit. What about variance? Folklore says LOOCV has high variance because its 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 over 2000 datasets and obtains , , and for : here more folds are better on both counts. For unstable algorithms (deep trees, k-NN with , feature selection), the picture changes, hence the common practical recommendation of or : 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.
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 be your training sample and the model you deliver. Its conditional error is
the error of your particular model on new data from the same distribution. The procedure’s expected error also averages over possible training samples:
What you almost always want to know is : you will deploy , 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, is exact for each dataset, so simulate many datasets and compare.
The next cell runs the same simulation with 2000 datasets and breaks it down.
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 and ; LOOCV is versus . CV estimates expected error training on observations well. It knows nothing about the particular model: correlation between CV and is for 5 folds and between and for any . 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: , treating the errors as independent, covers 83.6% of the time and 85.3%, not 95%. CV’s standard deviation, , is over twice that of what you want to estimate, .
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 be example ‘s validation error, with its fold, so . Suppose equal-sized folds of size . By symmetry (examples are exchangeable), the covariance matrix of has only three distinct values:
captures that two examples in the same fold are evaluated by the same model, and that models from different folds share training observations and each one’s validation examples are in the other’s training set. Summing the covariances,
The proof for estimators quadratic in the , 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 combines , and , with , and no coefficients can reproduce the variance coefficients while canceling . 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 with ,
obtained from . With positive correlations, the naive estimate ignores nearly all of the contribution from and , whose factors and do not vanish as grows. This is the variance of the CV estimate and its problem: it cannot be estimated without bias, and the obvious method underestimates it.
# 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, , while the naive estimator averages : 58% of the truth. Both covariances are small compared with , but weigh and , while weighs . The second part measures repeated CV (repeated k-fold): repeat CV with different splits and average. Of total variance , only (22%) comes from the split; the rest comes from the sample and no repetition removes it. With 10 repetitions variance falls to . 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 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 ). 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.
GroupKFoldassigns whole groups to folds, balancing sizes;StratifiedGroupKFoldalso tries to preserve class proportions, not always possible when labels belong to units. - Repeated. Repeat CV with 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.
TimeSeriesSplittakes the last consecutive blocks of size as successive validations, training each iteration on everything before the validation block (an expanding window); withmax_train_sizethe window slides and forgets old data, useful when the process changes.gapleaves 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.
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, (5 variables) and are independent random walks: there is no relationship to learn.
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 . For the series, random k-fold gives between independent walks: a time’s nearest neighbor in space is almost always adjacent, with similar because the walks are continuous. With temporal splits all values are negative: the model predicts worse than the block’s own mean, appropriate for no signal. Neither inflated figure warns you: 100% or 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:
| Type | What happens | Example | Prevention |
|---|---|---|---|
| L1.1 No test set | training error is reported | “99% accuracy” of the fitted model | CV or holdout |
| L1.2 Preprocessing with training and test | scaling, imputation or reduction fitted on everything | global mean for imputation | pipeline |
| L1.3 Feature selection with training and test | features chosen using validation labels | 20 most correlated genes, then CV | pipeline |
| L1.4 Duplicates | same (or nearly same) example on both sides | repeated photos, rows merged twice | deduplicate, split by group |
| L2 Illegitimate features | a feature contains or anticipates the target | “refunded amount” to predict fraud | audit each feature |
| L3.1 Temporal leakage | training uses future information | random k-fold for time series | time-based split |
| L3.2 Train-test dependence | shared units on both sides | images from the same patient | group split |
| L3.3 Test sampling bias | test does not represent real use | evaluating only easy cases | design 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 samples and 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 independent of everything, each feature’s sample correlation with is approximately , and among features the largest are around : with and , about . 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.
Four things the simulator shows, explained below. Selection outside CV turns noise into accuracy of 90% or more, and leakage grows with : 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 , 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.
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 with , with and with . With the selector inside the pipeline, it is , and , 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 levels into numeric columns, and each encoding has its place.
- One-hot. One indicator per level: columns (or if the model has an unregularized intercept, because all sum to 1 and are collinear with it). It imposes no order or distances. Problems: dimensionality grows with , 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 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 with rows is encoded as
a level mean shrunk toward global mean with strength : levels with few rows barely depart from . For binary it is the posterior mean of the level probability with prior , the same mechanism as Laplace smoothing.
Target encoding itself leaks if computed using the rows it later encodes. Consider row of a level with rows: its encoding contains its own label with weight . If changes from 0 to 1, holding the global mean fixed, rises exactly . With and , encoding is : it perfectly separates classes without the feature having any relationship to . There are two ways to err, and the second is subtle:
- Encode all data before CV (L1.2): validation-row encodings contain their labels. CV misleads.
- 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 parts and encoding each using the other . 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.
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 “predict” with 86.2% accuracy. Inside the pipeline, CV reports , 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
fitor statistic (mean, quantile, vocabulary, selection) calculated before splitting.
Nested cross-validation
So far we have evaluated a fixed procedure. In practice you try 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 configurations have the same true performance and CV estimates with independent standard normals . You report , whose expectation is
obtained from the density of the maximum of independent variables, (order statistics). The Gaussian maximal inequality gives : bias grows without bound, though slowly, with the number of things tried. Similar configurations have correlated errors: with correlation for each pair, , and shared part does not affect the winner, so bias is .
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, : 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 , with all you have seen about its variance.
The interactive’s model trains nothing: it only samples successes. Hence outer-fold count does not change nested CV’s bias, zero for any ; with a real algorithm, 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 ). 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 features, with , on signal-free data.
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 and nested CV , just over one standard error () 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 , and . They are not independent: selecting 21 or 34 variables gives nearly identical predictions, and correlation reduces bias by factor . The final line shows each outer fold can choose a different .
The scikit-learn version
Everything above has an equivalent in sklearn.model_selection, sklearn.pipeline and sklearn.compose:
| From scratch | scikit-learn |
|---|---|
kfold_indices, stratified_naive, group_kfold_indices, time_series_splits | KFold, StratifiedKFold, GroupKFold, TimeSeriesSplit, RepeatedStratifiedKFold, StratifiedGroupKFold |
Pipeline | Pipeline / make_pipeline, and ColumnTransformer to treat columns differently |
SelectTopK, Standardize, NearestCentroid | SelectKBest(f_classif), StandardScaler, NearestCentroid |
MEstimateEncoder | TargetEncoder (with cross-fitting in fit_transform), OneHotEncoder, OrdinalEncoder |
cv_accuracy | cross_val_score, cross_validate, cross_val_predict |
nested_cv_accuracy | cross_val_score(GridSearchCV(...)) |
First, check our implementation does the same. For two classes, the f_classif F statistic is , increasing in , 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.
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.
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 , CV and test , and the code gets coefficient . Without cross-fitting: training , CV and test , with coefficient 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 versus 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.
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: versus . This will not always hold; with large grids, long random searches or many manually tried preprocessing decisions, bias grows like . The next lesson on hyperparameter tuning revisits this with real searches.
Common mistakes
Exercises
More than one answer may be correct.
Step 1 of 4. What is ?
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 []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 computed only from other parts' rows (including their mean ). 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)])Summary
- -fold CV validates each example once with a model that has not seen it. It has pessimistic bias from training on observations; or is a good compromise, and LOOCV is cheap for linear models.
- CV estimates expected procedure error, , not error of the delivered model, : in the linear example its correlation with the latter was virtually zero.
- Its variance has three components (, , ) 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_transformdoes it andfit(...).transform(...)does not. - The best score in a search is biased by about ; nested CV evaluates the full search and removes that bias.