Tutorials › High-Dimensional Genomic Data Analysis › Building Leakage-Safe Analysis Pipelines

Honest Evaluation and Leakage · Tutorial 637 of 795

Building Leakage-Safe Analysis Pipelines

Build a single analysis pipeline whose preprocessing and model-fitting steps learn only from each training fold.

Intermediate 12 min read

What You'll Learn

  • Distinguish fitting a pipeline step from applying its fitted transformation.
  • Trace training-only imputation and scaling through a validation fold.
  • Keep supervised feature selection and model fitting inside the same fold-aware procedure.
  • Refit every learned step separately for each training split.
  • Recognize leakage caused by preprocessing the full data set before splitting.
  • Diagnose practical failures such as zero-variance features and incompatible transformations.

Why Treat the Analysis as One Procedure?

A genomic prediction analysis often combines several operations: filling in missing predictor values, scaling predictors, selecting features, and fitting a prediction model. Each operation can learn something from the observed data. An imputer learns quantities such as feature means; a scaler learns centers and scales; a supervised selection rule learns which features appear related to the outcome; and the model learns its coefficients. If any of these steps uses validation observations while being fitted, the validation results no longer represent predictions from a procedure trained without those observations.

The safe approach is to define the sequence as one pipeline. For a particular training split, fit every data-dependent step using that split alone. Then apply the fitted steps in order to the held-out observations, without updating them. Repeat the whole fit-and-apply process afresh for each split. This is more than a software convenience: it specifies which information is allowed to influence each prediction.

Definition: A fold-aware analysis pipeline is an ordered set of operations in which each operation that estimates quantities from data is fitted using only the current training fold. The fitted operations are then applied, in the same order and without refitting, to that fold's validation data. The final model is fitted on the processed training data and used to predict the processed validation data.

Let \(X_{\mathrm{tr}}\) and \(y_{\mathrm{tr}}\) denote the predictor matrix and outcome vector in a training fold, and let \(X_{\mathrm{val}}\) denote the predictors in its validation fold. A pipeline can be represented as a sequence of fitted maps: an imputation map \(I\), a scaling map \(S\), a feature-selection map \(F\), and a prediction model \(M\). The maps are fitted in sequence on training data; validation predictors pass through those already-fitted maps.

$$ \begin{aligned} \widehat I &= \operatorname{fit}_{I}(X_{\mathrm{tr}}),\\ \widehat S &= \operatorname{fit}_{S}\!\left(\widehat I(X_{\mathrm{tr}})\right),\\ \widehat F &= \operatorname{fit}_{F}\!\left(\widehat S(\widehat I(X_{\mathrm{tr}})),y_{\mathrm{tr}}\right),\\ \widehat M &= \operatorname{fit}_{M}\!\left(\widehat F(\widehat S(\widehat I(X_{\mathrm{tr}}))),y_{\mathrm{tr}}\right),\\ \widehat y_{\mathrm{val}} &= \widehat M\!\left(\widehat F(\widehat S(\widehat I(X_{\mathrm{val}})))\right). \end{aligned} $$

The order shown is illustrative: some legitimate pipelines use a different order, and some omit steps. What matters is that each learned quantity is estimated from the training fold, and validation data receive the corresponding transformation without influencing its estimate. If feature selection is supervised, it uses \(y_{\mathrm{tr}}\), never validation outcomes. A fixed operation that does not estimate anything from the data does not need fitting, but it must still be applied consistently.

One Split, One Complete Fit

The pipeline is refitted from the beginning at every training split. The imputation values, scaling constants, selected features, and model parameters may all change from fold to fold. Cross-validation estimates performance for this repeated procedure; it does not create one universal set of preprocessing quantities that can be estimated once from the full data set.

1
Separate training and validation observations.
Use the split design appropriate to the prediction target and sampling structure. Keep validation outcomes unavailable to all fitting steps.
2
Fit preprocessing on training predictors.
Estimate imputation values and scaling constants from training predictors only, then transform the training predictors.
3
Fit feature selection and the model.
Use training predictors and, for supervised steps, training outcomes. Fit the model using only the features chosen by the training-only selection step.
4
Apply the fitted pipeline to validation predictors.
Use the training imputation values, scaling constants and selected feature set. Generate predictions without refitting any step.
5
Repeat for the next split.
Discard the fitted fold-specific quantities and estimate them anew using the next training fold.

Worked Fold With Imputation, Scaling, Selection and Prediction

The following small hypothetical example makes the information flow explicit. It is illustrative rather than a genomic study. Suppose the training fold contains four samples, two predictors \(A\) and \(B\), and a continuous outcome. Predictor \(A\) is missing for one training sample.

Worked Example: Fit Every Step on Training Samples

The training-fold values are \(A=(1,2,\text{missing},5)\), \(B=(10,12,11,13)\), and \(y=(1,2,2,5)\). A held-out sample has \(A=100\), \(B=1000\), and its outcome is not used in fitting. For this example, impute each feature by its training mean, scale by its training sample standard deviation, select the feature with the larger absolute training correlation with \(y\), and fit a least-squares linear regression using the selected standardized feature.

Impute. The mean of the observed training values of \(A\) is \((1+2+5)/3=8/3\). Thus the completed training values are \((1,2,8/3,5)\). The training mean of \(B\) is \((10+12+11+13)/4=11.5\). No held-out value enters either calculation.

Scale. The completed training mean of \(A\) is \(8/3\). Its sample standard deviation is \(s_A=\sqrt{\{(1-8/3)^2+(2-8/3)^2+(8/3-8/3)^2+(5-8/3)^2\}/3}=\sqrt{26/9}\approx1.700\). For \(B\), the sample standard deviation is \(s_B=\sqrt{\{(-1.5)^2+(0.5)^2+(-0.5)^2+(1.5)^2\}/3}=\sqrt{5/3}\approx1.291\). The standardized training features therefore have mean zero and sample standard deviation one, up to rounding.

Select using training data. For \(A\), the centered values are \((-5/3,-2/3,0,7/3)\), and the centered outcomes are \((-1.5,-0.5,-0.5,2.5)\). Their cross-product sum is \(8.667\), the sum of squared centered \(A\) values is \(8.667\), and the outcome sum of squares is \(9\). Hence \(r_A=8.667/\sqrt{8.667(9)}\approx0.9813\). For \(B\), the centered values are \((-1.5,0.5,-0.5,1.5)\); their cross-product sum with the centered outcomes is \(6\), and their sum of squares is \(5\). Thus \(r_B=6/\sqrt{5(9)}\approx0.8944\). The rule selects \(A\), since \(|r_A|>|r_B|\).

Fit and predict. The least-squares slope is 1, giving the fitted line \(\widehat y=-1/6+A\); the observed training values do not all lie exactly on this line. Since \(z_A=(A-8/3)/(\sqrt{26}/3)\), this is equivalently \(\widehat y=2.5+\sqrt{26}/3\,z_A\), or approximately \(\widehat y=2.5+1.700z_A\). For the held-out sample, impute nothing because \(A=100\) is observed, and use the training scale: \(z_A=(100-8/3)/(\sqrt{26}/3)\approx57.27\). The prediction is \(2.5+(\sqrt{26}/3)(100-8/3)/(\sqrt{26}/3)=2.5+100-8/3\approx99.83\) outcome units. The held-out \(B\) value is irrelevant because \(B\) was not selected. Neither held-out predictor values nor the unavailable held-out outcome changed the imputation, scaling, selection, or fitted coefficients.

Why the Whole Pipeline Must Be Refit

Suppose two folds have different training samples. Even if both folds use the same named operations, their fitted maps are generally different. For example, a feature's training mean, its scale, and its association with the outcome depend on which observations are in that fold. Reusing estimates from another fold is not equivalent to fitting the stated procedure on the current training fold.

Worked Example: Different Training Folds Give Different Scaling

Consider one predictor measured in arbitrary units. In one hypothetical split its training values are \(2,4,6\), and its validation value is \(8\). The training mean is \((2+4+6)/3=4\). Its sample standard deviation is \(\sqrt{\{(2-4)^2+(4-4)^2+(6-4)^2\}/2}=2\). Therefore the validation value, transformed using this fold's estimates, is \((8-4)/2=2\).

In a different hypothetical split, suppose the training values are \(2,4,8\), with validation value \(6\). The training mean is \(14/3\). The sample standard deviation is \(\sqrt{\{(2-14/3)^2+(4-14/3)^2+(8-14/3)^2\}/2}=\sqrt{28/3}\approx3.055\). The transformed validation value is \((6-14/3)/\sqrt{28/3}\approx0.4364\). The same raw value would not have the same standardized value under both folds. Each split requires its own fitted scaling map.

A short justification follows directly from the definition of the prediction procedure. Conditional on the training fold, its fitted pipeline is determined by \(X_{\mathrm{tr}}\) and \(y_{\mathrm{tr}}\). A valid held-out prediction is then a function of that fitted pipeline and the held-out predictors. If an imputer, scaler, or selector is instead fitted using the validation observations, the fitted map also depends on validation data. The resulting score evaluates a procedure that had access to information unavailable in the intended training setting.

$$ \widehat y_{\mathrm{val}} = g\!\left(X_{\mathrm{val}};\,X_{\mathrm{tr}},y_{\mathrm{tr}}\right) \quad\text{is fold-safe, whereas}\quad g\!\left(X_{\mathrm{val}};\,X_{\mathrm{tr}},y_{\mathrm{tr}},X_{\mathrm{val}}\right) \quad\text{allows validation predictors to affect fitting.} $$

The distinction matters even when validation outcomes are never used. Using validation predictors to estimate scaling or imputation still changes the learning procedure and allows information from the evaluation sample into its fitted representation. Whether that constitutes a practically large bias depends on the setting, but it is not the same validation design as training-only preprocessing.

Worked Example: Validation Data Contaminating Imputation

Suppose a training fold has observed values \(2\) and \(4\) for a predictor, plus one missing value. Its training-only mean-imputation value is \((2+4)/2=3\). If a held-out sample has value \(100\), fitting the imputer on the combined training and validation observations instead gives \((2+4+100)/3=35.33\). The missing training value would then be filled with \(35.33\), rather than \(3\), because of a value from the held-out sample.

The held-out sample's outcome was not involved, but its predictor has nevertheless changed the training representation. A pipeline that first fits the imputer on training values fills the training missing value with \(3\), then leaves the held-out observed value at \(100\). This is the appropriate operation when the intended prediction procedure estimates imputation from its training data.

Assumptions, Diagnostics, and Boundaries

Fold awareness prevents a particular information-flow error; it does not guarantee that the prediction model is appropriate or that the evaluation split answers the scientific question. The split must respect the target population and dependence structure. In genomic data, for example, related individuals or samples from a shared site may require grouped or site-aware splits when the intended prediction is to new families or sites. The pipeline cannot repair a split that places related observations on both sides when that split is incompatible with the prediction target.

The individual operations also need explicit rules for their edge cases. A feature can be entirely missing in a training fold, so its training mean is undefined. A feature can be constant in a fold, so standardization by its sample standard deviation is undefined. The analysis must specify a consistent response, such as dropping that feature in that fold or using a prespecified fallback rule; the validation data must not be used to decide the response. Likewise, a feature selector may choose no features, or a model may fail to converge. These are pipeline failures to report and handle, not reasons to silently substitute validation information.

Useful diagnostics include checking, for every fold, the number of missing values before and after imputation, the estimated centers and scales, the number and identity of selected features, and whether model fitting completed. Check that the validation transformation has the same feature names and order expected by the fitted model. Investigate unexpectedly identical preprocessing values across folds when the training subsets differ, since that can indicate accidental reuse of globally fitted transformations. Also verify that no validation outcomes were passed to any step that selects features or estimates model parameters.

A common mistake is to scale or select features once on the complete data set and then run cross-validation on the resulting matrix. The reasoning is often, “The validation outcomes were hidden, so there can be no leakage.” The correction is that predictors alone can affect estimated imputation and scaling values, and supervised selection can directly use outcomes if it is done globally. All data-adaptive steps belong inside the fold-specific pipeline. The alternative—preprocessing once before splitting—is only appropriate for operations that are genuinely fixed in advance and do not estimate their behavior from the data being evaluated.

A second alternative is to write separate preprocessing code for every fold. That can be valid if it faithfully refits every learned step and applies the fitted versions consistently, but it is error-prone: one global scaling call or a feature-name mismatch can break the information boundary. A pipeline implementation packages the ordered operations together and reduces this risk. It does not decide the right split design, imputation strategy, feature selector, or model; those choices still require scientific justification. Nor does this tutorial decide how to choose among competing hyperparameter settings. The essential point here is that whichever procedure is evaluated must be refitted in its entirety inside the relevant training split.

Key takeaway: For each split, learn imputation values, scaling constants, selected features, and model parameters from that split's training data. Apply those fitted quantities unchanged to its validation data, then refit everything for the next split.

Check Your Understanding

Answer each question, then compare your reasoning with the solutions below.

  1. A supervised selector ranks genes by their training association with the outcome. Which outcomes may it use when producing predictions for a validation fold?
  2. A training fold has observed values \(4\) and \(8\) for a feature, with one missing value. What value does mean imputation use? If the validation value is \(100\), should that value change the imputation?
  3. A feature has training mean \(10\) and training sample standard deviation \(2\). What is the standardized value of a validation observation equal to \(14\)?
  4. Why is it not sufficient to hide validation outcomes if scaling was estimated on the full predictor matrix before splitting?
  5. What should be checked when a feature has zero variance in one training fold?

Solutions. (1) It may use only the outcomes in that fold's training set, \(y_{\mathrm{tr}}\); validation outcomes must not influence selection. (2) The imputation is \((4+8)/2=6\). The validation value must not change it, because the imputer is fitted from training observations only. (3) Apply the training estimates: \((14-10)/2=2\). Do not recalculate the mean or standard deviation using the validation observation. (4) Validation predictors can affect the full-data scaling estimates, so the resulting fitted representation uses information from the evaluation sample even without its outcomes. (5) Standardization would divide by zero. Use a specified, training-only rule such as dropping the feature for that fold or applying a prespecified fallback, and record the action; do not consult validation data to resolve it.

Clinical Biostats