Concepts / Hyperparameter Tuning with Cross-Validation

Hyperparameter Tuning with Cross-Validation

Data leakage happens when information from the test part of a cross-validation split is used during preprocessing, which makes the results overly optimistic.

  • Programming

A Preprocessing Step That Feels Harmless

Imagine you have already tried a few settings for a model, and now you want to tune its hyperparameters with a grid search. You will use cross-validation to compare the candidate settings. Before any of that starts, you prepare the data: you scale the features so that they sit on comparable ranges. Doing this step once, at the very beginning, feels efficient and harmless.

A common assumption says this is fine. The reasoning goes like this: scaling is just a bit of arithmetic applied to the features, so the order in which it happens should not matter. The source material identifies this exact belief as a misconception. This article traces what happens to the data step by step, so you can see where the belief breaks down and why the order of preprocessing and splitting changes how much you can trust the numbers that come back.

Key point

The question to keep in mind throughout: when a score comes back from cross-validation, has the held-out data been kept truly unseen, or has it already shaped something the model learned from?

Tracing the Leak Step by Step

Follow the data through the wrong order first. Start with the full training set. Before cross-validation begins, you learn a scaling from the entire training set and apply it to every row. Only after that do you divide the already-transformed data into splits. Each split takes a portion of the training set and designates it as the test part of that split.

Here is the subtle detail. Even though a portion is held out during fitting, that portion still belongs to the training set as a whole. When the scaling was learned from the entire training set, it absorbed information from every row, including the rows that later serve as test parts. By the time cross-validation begins, the held-out data has already shaped the transformation applied to the training data. The test part is no longer independent of what the model learns from.

Full training setall rowsTest part rowsheld out in one splitScaling statisticsinclude test rowsTransform every rowtraining and test alikeCross-validationsplitsalready transformedOptimistic scoretest no longer unseenFit scaler on allrowslearns statisticsfed inalso fed inproducesapplied tothen splitleads to
When a scaler is fit on the full training set before splitting, what data flows from the test part into the transformation that the training part receives?

The purpose of the test part is to simulate what new data will look like to a model trained on the training part. That simulation only works if the test part behaves like unseen data. Once preprocessing has already drawn on the test part, it no longer behaves that way. The splits stop being an honest stand-in for future data, and the model appears to perform better than it would on data it has never encountered.

Worked example

Watching one feature leak into a split

A single feature has the values 1 through 10 across the training set. A scaler that centers on the mean learns its statistic from whichever rows it is given. Suppose the rows 9 and 10 are held out as the test part of one split. Compare what the scaler learns in the leaky order and in the correct order.

  1. 1
    Leaky order: fit on the full training set

    The scaler sees all ten values, 1 through 10. The mean is 5.5. This mean already includes the values 9 and 10, which will later be the test part.

  2. 2
    Leaky order: split afterward

    The training part, values 1 through 8, has been centered using a mean that was influenced by the test values. The test values have shaped the training transformation before the split happened.

  3. 3
    Correct order: split first

    The training part is values 1 through 8 only. Its mean is 4.5. The scaler learns only from these rows.

  4. 4
    Correct order: transform the test part

    The test values 9 and 10 are transformed using the mean of 4.5 learned from the training part. Nothing about them was used to compute that statistic.

Result

In the leaky order, the test values contributed to the statistic that defines the training transformation. In the correct order, the test values stayed out of the learning step entirely, so the held-out part still behaves like unseen data.

The Correct Ordering: Split First, Then Learn

The remedy is a change in ordering. The dataset should be split during cross-validation before any preprocessing takes place. Any process that extracts knowledge from the dataset, such as learning a scaling, should only ever be applied to the training portion of each split. The test portion is then transformed using what was learned from the training portion, not using statistics that include it.

In other words, cross-validation becomes the outermost loop in the processing pipeline, and everything that learns from data sits inside it. Read the diagram below from top to bottom. The split happens first, the preprocessing is fit only on the training part, both parts are transformed, the model is trained, and only then is the test part scored.

Full datasetnot yet preprocessedSplit into foldsoutermost loopTraining part of foldonly this is used to learnFit preprocessinglearned from training partTransform both partstest uses trainingstatisticsTrain modelon transformed trainingpartScore test parthonest estimatedivideselect training partlearn fromapplytrain onthen score
In what exact order do splitting, fitting the preprocessing step, and training happen, and where does the test fold enter that sequence?
In the real world

Consider a grid search that compares several candidate hyperparameter settings. In the correct design, each candidate is evaluated across the folds, and every fold repeats the full sequence above. The preprocessing is re-learned for each fold from that fold's training part, so the scores that the search compares reflect how each setting handles data it was not allowed to influence.

Each Fold Gets Its Own Partition and Fit

Cross-validation is a loop, and the correct workflow depends on that loop running the whole process again for every split. Each fold has its own train and test partition. Because the test part changes from fold to fold, what the model sees as unseen also changes. The preprocessing that is learned must change with it, which is why it belongs inside the loop rather than outside.

Fold 1test: fold 1 | train: folds2 and 3Fold 2test: fold 2 | train: folds1 and 3Fold 3test: fold 3 | train: folds1 and 2Refit scalingfrom the current trainingpartnext splitnext spliteach iteration
Across successive folds, which rows serve as training and which as test, and what gets refit on each iteration? Each fold refits its own preprocessing from its own training part.

Read the loop as a repeated cycle. For every split, the scaling is learned only from that split's training part, the training part and the test part are each transformed, the model is trained, and only then is the test part scored. Because no test information enters the preprocessing step, the score reflects how the model handles data it has not been allowed to influence.

Why Inflated Scores Mislead Hyperparameter Choices

The first consequence of leakage is that the scores come out overly optimistic. The model appears to perform better than it would on data it has never encountered, because the test part was no longer a faithful stand-in for future data. A reported score that looks excellent may simply reflect the leak rather than real generalization.

The second consequence is less obvious and can be more damaging. Grid search chooses settings based on the scores it sees. If those scores are inflated, the search can pick a setting that benefited from the leak rather than the one that truly generalizes best. Leakage therefore does not only misreport the final number; it can also lead to suboptimal parameter selection.

  • Common mistake

    Scaling the full training set once before running cross-validation

    What it looks like

    Learn a scaling from every training row, then split the already-scaled data into folds.

    Why it fails

    The test part of each split is still part of the training set, so its values have shaped the transformation applied to the training data.

    Do this instead

    Split first, then learn the scaling only from each split's training part, and transform the test part using those statistics.

  • Common mistake

    Assuming the order of preprocessing does not affect validity

    Why it fails

    The reasoning that scaling is just arithmetic overlooks that the arithmetic learns from data. The source identifies this as a misconception.

    Do this instead

    Treat any step that extracts knowledge from data as something that must sit inside the cross-validation loop.

  • Common mistake

    Trusting a high cross-validation score without asking how it was produced

    Why it fails

    A leaked score looks like strong performance, so it can hide the problem.

    Do this instead

    Check whether any preprocessing learned from data before the split, and treat an unusually high score as a reason to re-examine the workflow.

Checking Whether a Score Can Be Trusted

What do you think happens?

A workflow scales the full training set first, then runs cross-validation on the scaled data. Is the resulting score trustworthy?

  • Yes, because scaling is only arithmetic and does not depend on which rows are used

  • No, because the test parts of the splits were already used when the scaling was learned

Reveal answer
Answer:

No, because the test parts of the splits were already used when the scaling was learned

The scaling was learned from the entire training set, which includes every row later designated as a test part. The held-out data has already shaped the transformation, so the splits no longer simulate unseen data.

MEDIUM

Describe the correct ordering for a workflow that uses cross-validation to tune a hyperparameter and also needs feature scaling. List the steps in order, and say which step must be repeated for every fold.

Hints
  • Ask first where the split must happen relative to any step that learns from data.
  • Think about which portion is allowed to inform the scaling in each fold.
  • The learning step, including fitting the scaling, is the one that must be repeated per fold.

Key Takeaways for Trustworthy Tuning

  1. 1
    Data leakage happens when information from the test part of a cross-validation split is used during preprocessing, which makes the results overly optimistic.
  2. 2
    Preprocessing learned from the full training set leaks information, because the test parts of the splits are themselves part of that training set.
  3. 3
    The fix is to split first and treat cross-validation as the outermost loop, fitting any knowledge-extracting preprocessing only on each split's training part.
  4. 4
    Leakage can also cause poor parameter choices, because grid search selects settings based on inflated scores.

At a glance

  • Data leakage happens when information from the test part of a cross-validation split is used during preprocessing, which makes the results overly optimistic.
  • Scaling learned from the entire training set absorbs information from rows that later serve as test parts, so the held-out data shapes the training transformation.
  • The correct ordering splits the data first, with cross-validation as the outermost loop, and fits any knowledge-extracting preprocessing only on each training part.
  • Leakage can also lead to suboptimal hyperparameter choices, because grid search selects settings based on inflated scores.

Related concepts

More concepts starting with H