Validation Strategies and Data Leakage › Formula

Michael BrenndoerferOctober 25, 202611 min read
Machine Learning from ScratchAll chapters
Part 4 of 15Model Evaluation and Selection
Chapter 31Validation Strategies and Data Leakage › Formula
Reading section 4 of 10 · Formula · 11 minSection 4 of 10 · 11 min

Section 4 of 10 · 11 min read

Validation Strategies and Data Leakage › FormulaSection view · Sections in this chapter4 / 10 ↓
Reading tools Definitions, links & notes

Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.

Article links

Make inline references clickable

Notes & comments

The formulas separate the population quantity we want from the sample quantity we can compute. We first define risk and held-out loss, then describe which observations may contribute to fitting. The grouped and temporal constraints express different deployment tasks; cross-validation repeats the corresponding fitting and evaluation procedure.

Let the collected observations be

D={(xi,yi,gi)}i=1n,\mathcal{D} = \{(x_i, y_i, g_i)\}_{i=1}^{n},

Here xi∈Rdx_i \in \mathbb{R}^d is the feature vector, yi∈Ry_i \in \mathbb{R} is the regression target, and gig_i identifies the customer or other group. The examples use the group column to construct splits, rather than as an input to 1-NN. We use squared loss, L(y^,y)=(y^−y)2L(\hat y,y)=(\hat y-y)^2; classification uses a loss suited to its target.

Training, validation, and final test roles

Let P\mathcal P be the joint distribution of a fresh deployment observation (x,y)(x,y), and let ff be a fixed predictor. Assume the loss L(f(x),y)L(f(x),y) has a finite expectation. Generalization risk is its expected loss:

R(f)=E(x,y)∼P[L(f(x),y)].\mathcal{R}(f) = \mathbb{E}_{(x, y) \sim \mathcal{P}}\left[ L(f(x), y) \right].

We generally do not know this population expectation. Validation estimates it from a finite sample. The fitted model and all learned transformations must be evaluated under the information restrictions of the intended task, rather than on rows that contributed to their fitting or selection.

Let ItrainI_\text{train}, IvalI_\text{val}, and ItestI_\text{test} be disjoint sets of row indices. The corresponding data subsets are denoted by Dtrain\mathcal D_\text{train}, Dval\mathcal D_\text{val}, and Dtest\mathcal D_\text{test}. Fit f^\hat f on the training subset and let ItestI_\text{test} be nonempty. Its empirical test risk is the average loss on the held-out indices:

R^test(f^)=1∣Itest∣∑i∈ItestL(f^(xi),yi).\hat{\mathcal{R}}_\text{test}(\hat f) = \frac{1}{|I_\text{test}|} \sum_{i \in I_\text{test}} L(\hat f(x_i), y_i).

Two details in that expression carry all the weight:

  • We divided by ∣Itest∣|I_\text{test}|, not by nn: the estimator is an average over the specific rows in the test set, not over the whole data.
  • The model is fixed before those rows are scored; nothing about them influenced the fit.

Sufficient conditions for this additive mean loss to be conditionally unbiased for R(f^)\mathcal R(\hat f), given the fitted model, are:

  • each (xi,yi)(x_i, y_i) with i∈Itesti \in I_\text{test} is drawn from the same distribution P\mathcal{P} as the future data, and
  • each test observation is statistically independent of the fitted model f^\hat f.

Under these conditions, conditioning on the fitted model leaves each test loss with expectation R(f^)\mathcal R(\hat f), so their mean has that expectation too. Dependence among test rows can still affect its variance. Correlated training and test observations can make the model and test rows statistically dependent even without direct test-data reuse. Distribution shift and adaptive use of test information can invalidate this argument. The result concerns the mean loss; applying a nonlinear operation such as a square root need not preserve unbiasedness.

In practice we divide D\mathcal{D} into three disjoint sets with sizes ntrainn_\text{train}, nvaln_\text{val}, and ntestn_\text{test} such that

ntrain+nval+ntest=n.n_\text{train} + n_\text{val} + n_\text{test} = n.
  • Training fits model parameters under a given hyperparameter setting.
  • Validation compares candidate hyperparameters and chooses the best.
  • Test assesses the chosen, frozen procedure on data that did not guide that choice.

The third role matters because validation outcomes guide model selection. Selecting the candidate with the best noisy validation result and reporting that same result can introduce optimism. Separate test data assess the choice without participating in it; another option is an outer resampling scheme that includes the entire selection procedure inside each outer training split.

A practical protocol is to inspect the final test result after choices are fixed. Recomputing the same frozen result does not itself change its statistical role. Changing the model, features, threshold, or evaluation protocol in response to that result uses it for validation; the revised procedure then needs fresh uninvolved evaluation data.

Allocations such as 60/20/2060/20/20 or 70/15/1570/15/15 are examples, not prescriptions. The needed sizes depend on the learning problem, event counts, group structure, and required precision. Cross-validation rotates validation folds within the development data after the final test portion has been reserved.

Preprocessing and target leakage

Preprocessing is part of the fitted procedure. Let ϕ\phi be a scaler, imputer, encoder, or feature selector; fit its parameters on training data and fit the predictor on the transformed training rows. If the transform is instead learned from all collected rows, the resulting composite predictor is

f^leaked(x)=f^θ(ϕ^D(x)).\hat{f}_\text{leaked}(x) = \hat{f}_\theta\big(\hat{\phi}_\mathcal{D}(x)\big).

The transform ϕ^D\hat\phi_\mathcal D has used held-out information. A scaler or unsupervised imputer uses held-out feature values; a supervised selector or target encoder can also use held-out labels. This violates the standard inductive evaluation boundary even when the fitted predictor itself only receives training rows.

For example, a target encoder replaces category cc by its mean target. If cic_i is the category of row ii and cc occurs in the collected data, the full-data mean is

TED(c)=1∣{i:ci=c}∣∑i:ci=cyi,\text{TE}_\mathcal{D}(c) = \frac{1}{|\{i : c_i = c\}|} \sum_{i : c_i = c} y_i,

This mean includes the labels of held-out rows in category cc. It therefore cannot be used to encode those rows in an inductive test. A training-only mean is

TEtrain(c)=1∣{i∈Itrain:ci=c}∣∑i∈Itrain:ci=cyi,\text{TE}_\text{train}(c) = \frac{1}{|\{i \in I_\text{train} : c_i = c\}|} \sum_{i \in I_\text{train} : c_i = c} y_i,

Apply this fitted mapping to held-out categories. If a category has no training observations, the denominator is zero, so an explicit fallback is needed; the implementation uses the overall training-target mean. Training rows encoded using their own labels can still overfit even when the outer held-out labels are excluded. Inner cross-fitting can construct training encodings from other training folds; scikit-learn documents this behavior for TargetEncoder.fit_transform, whereas fit followed by transform does not invoke that cross-fitting scheme.

Target leakage occurs when a feature supplies the outcome, or information unavailable when that prediction would have been made. A discharge field recorded after the prediction origin or a refund recorded only after the predicted return are examples when those events have not yet occurred. A historical purchase count can be valid. Audit the computation and availability of each feature at the prediction origin; neither a grouped split nor a modest score proves that this audit has passed.

Stratified, grouped, and temporal splits

For an i.i.d. prediction task, a random row split can be appropriate. Exchangeability means the joint distribution is unchanged by permuting row order; it does not mean the rows are independent. Repeated entities and time order require checking whether the available information and dependence match the intended task, rather than treating every row as a fresh independent case.

Stratified splits aim to preserve class proportions across folds, up to integer and allocation constraints. If pc(Fk)p_c(F_k) is the fraction of class cc among indices in fold FkF_k, the aim is pc(Fk)≈pc(D)p_c(F_k)\approx p_c(\mathcal D). This reduces variation in class counts, but does not create independence or preserve all sources of uncertainty. A rare class with fewer observations than folds cannot appear in every fold. When groups or time impose other constraints, exact class balance may be infeasible or inappropriate.

Grouped splits hold out whole entities for a new-entity task. To see why this can matter, consider yi=θgi+εiy_i=\theta_{g_i}+\varepsilon_i with mutually independent, zero-mean residuals that are independent of the random group effects, all with finite second moments. Two distinct rows in the same group then have covariance Var⁡(θgi)\operatorname{Var}(\theta_{g_i}), which is positive when that effect varies. A learner that recognizes the group may use its training history. For an unseen-group test, impose

Gtrain∩Gtest=∅,Gtrain={gi:i∈Itrain}.\mathcal{G}_\text{train} \cap \mathcal{G}_\text{test} = \emptyset, \qquad \mathcal{G}_\text{train} = \{g_i : i \in I_\text{train}\}.

Every group is assigned wholly to one side. This removes direct entity overlap for the chosen grouping level. Five hundred rows from five customers still provide only five sampled customer histories; their statistical information also depends on within-customer loss dependence and group sizes, so it is not generally equivalent to exactly five independent rows. Group disjointness does not ensure that customers are otherwise independent or representative of future customers.

Temporal splits are appropriate when the task predicts later observations from information available earlier. For a simple chronological hold-out, let tit_i be the event time and choose cutoff tsplitt_\text{split}:

ti≤tsplit,∀ i∈Itrain,tj>tsplit,∀ j∈Itest.t_i \leq t_\text{split}, \quad \forall\, i \in I_\text{train}, \qquad t_j > t_\text{split}, \quad \forall\, j \in I_\text{test}.

Training precedes the held-out event period in this construction, but event times alone do not establish label or feature availability. Delayed labels and overlapping outcome windows may require additional exclusions. A known future calendar value can be available at prediction time; an unobserved future outcome cannot. Future observations from existing patients call for chronology with eligible patient history. Future observations from previously unseen patients require both temporal and group hold-outs.

Out-of-fold predictions and reproducible evaluation

For the following cross-validation notation, use only development data after the final test set has been reserved, and let nn now denote the development sample size. Choose an integer KK with 2≤K≤n2 \le K \le n and partition the development indices into KK nonempty disjoint folds F1,…,FKF_1,\ldots,F_K. Fit f^(−k)\hat f^{(-k)} on all development rows outside FkF_k, including fitting every learned transform there. The unweighted mean of the fold mean losses is

R^KCV=1K∑k=1K1∣Fk∣∑i∈FkL(f^(−k)(xi),yi),\hat{\mathcal{R}}^\text{CV}_K = \frac{1}{K} \sum_{k=1}^K \frac{1}{|F_k|} \sum_{i \in F_k} L\big(\hat{f}^{(-k)}(x_i), y_i\big),

Here f^(−k)\hat f^{(-k)} is the complete pipeline fitted without fold kk. For a complete K-fold partition, each development observation appears in exactly one held-out fold. Its out-of-fold prediction is

y^ioof=f^(−k(i))(xi),i=1,…,n,\hat{y}^\text{oof}_i = \hat{f}^{(-k(i))}(x_i), \qquad i = 1, \dots, n,

The function k(i)k(i) identifies the fold holding out row ii. An OOF prediction excludes that row from fitting its prediction pipeline, provided preprocessing and any selection are also restricted correctly. OOF values support error analysis, stacking, calibration, and threshold selection. If they guide a choice, they serve as validation data; the reused selected score is not an independent final test.

GroupKFold forms a complete partition of the groups, so every row can receive one group-held-out prediction. TimeSeriesSplit instead trains on earlier indices and tests on later blocks. With its default unbounded training window, successive training sets expand. Its initial training block receives no held-out prediction, and max_train_size can limit the training history. A manual temporal prediction array should leave unscored rows explicit; cross_val_predict requires every input row to appear in a test fold exactly once and therefore does not accept ordinary TimeSeriesSplit output.

Record the data snapshot, stable row identities, split configuration or exact fold assignments, and the fitted procedure. For a randomized splitter or estimator, also record the relevant randomness settings and dependency versions. A fixed seed does not protect against a changed row order or changed data. Save and apply indices to the same ordered dataset, or map them through stable row identifiers.

Mathematical properties

A few properties of the estimators above matter for how we interpret them.

CV fits use fewer development observations than a final fit on all development data. For equal row folds, each fit uses (1−1/K)n(1-1/K)n rows; grouped folds can differ in size. The CV result therefore describes those training sizes and held-out tasks. It can be pessimistic when the learning procedure improves with additional data, but its bias and variance do not have a universal direction or monotonic relationship with KK.

The variation of a held-out mean depends on the individual loss variances and their covariances. Under independent losses with a common finite variance σL2\sigma_L^2, its variance is σL2/m\sigma_L^2/m for mm scored rows. The general variance formula includes pairwise covariances; dependent losses can still be uncorrelated. CV fits share data, so treating the KK fold scores as independent replicates and dividing their standard deviation by K\sqrt K does not give a general confidence interval.

For a chosen pair of evaluations, define a signed observed loss difference:

Δleak  =  R^honest−R^leaked.\Delta_\text{leak} \;=\; \hat{\mathcal{R}}^\text{honest} - \hat{\mathcal{R}}^\text{leaked}.

A positive difference means the evaluation labeled leaky reports a smaller loss in this pair; a negative value means it reports a larger loss. Its sign and magnitude are not guaranteed. If the two evaluations also change customers, training sizes, or fitted models, the gap does not isolate the causal effect of one information leak. The examples below diagnose the information boundary directly.

Loss units matter. Squared-error risk has squared-target units, whereas RMSE has target units. A gap between two RMSEs is therefore a separate descriptive quantity, not the same number as the squared-loss difference above. Neither gap is generally equal to a customer-effect variance.

Comments

Add to the conversation

A question, a correction, or an example from your own work.

No comments yet. Be the first to share your thoughts!

Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy