Machine Learning

Train/Dev/Test Splits, Cross-Validation, and Leakage

Train/dev/test splits and cross-validation keep learning, choosing, and final evaluation separate; leakage breaks that contract.

status: publishedimportance: criticaldifficulty 3/5math: undergraduateread: 18mlive demo

Concept Structure

Train/Dev/Test Splits, Cross-Validation, and Leakage

01Intuition

Start with the picture, metaphor, or geometric mechanism.

02Math

Make the objects explicit and connect them with notation.

03Code

Mirror the equations with runnable implementation details.

04Interactive Demo

Manipulate the mechanism and watch the idea respond.

2prerequisites
3next concepts
1related links

Learning map

Train/Dev/Test Splits, Cross-Validation, and Leakage
BeforeBias-Variance DecompositionNow4/4 sections readyTryManipulate one control and predict the visible change.NextRegularization: Ridge, Lasso, and Elastic Net

Object flow

4/4 sections readyAsk about thisResearch room
ConceptTrain/Dev/Test Splits, Cross-Validation, and LeakageMachine Learning
3 sources attachedLocal snapshot ready
concept:machine-learning/train-dev-test-cross-validation-leakage

Conceptual Bridge

What should feel connected as you move through this page.

Carry inBias-Variance Decomposition

Bring the mental model from Bias-Variance Decomposition; this page will reuse it instead of restarting from zero.

Work hereTrain/Dev/Test Splits, Cross-Validation, and Leakage

Train/dev/test splits and cross-validation keep learning, choosing, and final evaluation separate; leakage breaks that contract.

Carry outRegularization: Ridge, Lasso, and Elastic Net

The next edge should feel earned: use the demo prediction here before following Regularization: Ridge, Lasso, and Elastic Net.

Test the linkManipulate one control and predict the visible change.Then continue to Regularization: Ridge, Lasso, and Elastic Net
01

01

Intuition

Build the mental picture first so the rest of the page has something to attach to.

Section prompt

You are here because a model can look good for three very different reasons: it learned a pattern, it got lucky on one split, or information from the answer key slipped into the workflow. Serious AI research starts by telling those apart.

Before this, know overfitting, bias-variance, and the basic shape of logistic or linear regression. By the end, you should be able to say what the training, development, and test sets are allowed to influence, run cross-validation without using the test set, and identify a concrete leakage path.

Think of an experiment as three rooms with locked doors:

  • Training room: fit parameters, preprocessing statistics, feature selectors, embeddings, prompts, or any learned transformation.
  • Development room: choose hyperparameters, thresholds, architectures, feature counts, stopping rules, and other decisions.
  • Test room: measure the selected final pipeline once, after decisions are frozen.

The most common beginner mistake is to treat the test set as a helpful friend. It is not. If you check the test score, change the model, check again, change the threshold, check again, then the test set has become part of training-by-human-loop. The reported number is no longer an honest estimate of future performance.

Cross-validation helps when data is scarce. Instead of sacrificing one fixed development set, you rotate which part of the training budget acts as the temporary validation fold. But cross-validation does not remove the need for a final untouched test set when you want an external estimate of the selected pipeline.

Leakage is any hidden path from held-out information into the fitted pipeline or the choices around it. It can be obvious, like training on test labels. More often it is quiet:

  • standardizing with the mean and standard deviation of all rows before splitting
  • imputing missing values with all rows
  • selecting features by correlation with the target before splitting
  • deduplicating after the split so near-duplicates appear in both train and test
  • tuning thresholds, prompts, or hyperparameters after repeatedly reading the test score
  • building a benchmark from public examples that the model or retrieval system has already seen

The repair is a simple discipline: split first, fit every learned operation only inside the training fold, use development/CV for choices, and save the test set for the final selected procedure.

02

02

Math

Translate the story into symbols, assumptions, and a derivation you can inspect.

Section prompt

Let the full dataset be

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

A train/dev/test split partitions the row indices into three disjoint sets whose union is the dataset:

ItrainIdevItest={1,,n},ItrainIdev=,ItrainItest=,IdevItest=.I_{\text{train}}\cup I_{\text{dev}}\cup I_{\text{test}}=\{1,\ldots,n\},\quad I_{\text{train}}\cap I_{\text{dev}}=\varnothing,\quad I_{\text{train}}\cap I_{\text{test}}=\varnothing,\quad I_{\text{dev}}\cap I_{\text{test}}=\varnothing.

For a hyperparameter value λ\lambda, the training algorithm produces a fitted model using only the training rows:

f^λ=Aλ(DItrain).\hat f_{\lambda}=A_{\lambda}(D_{I_{\text{train}}}).

The development loss estimates which candidate looks best:

R^dev(λ)=1IdeviIdevL(f^λ(xi),yi).\widehat R_{\text{dev}}(\lambda)= \frac{1}{|I_{\text{dev}}|} \sum_{i\in I_{\text{dev}}} L(\hat f_{\lambda}(x_i),y_i).

Model selection is the act of choosing

λ^=argminλΛR^dev(λ).\hat\lambda=\arg\min_{\lambda\in\Lambda}\widehat R_{\text{dev}}(\lambda).

After that choice is frozen, the test loss is computed once:

R^test=1ItestiItestL(f^λ^(xi),yi).\widehat R_{\text{test}}= \frac{1}{|I_{\text{test}}|} \sum_{i\in I_{\text{test}}} L(\hat f_{\hat\lambda}(x_i),y_i).

This number estimates the performance of the selected procedure only if ItestI_{\text{test}} did not influence AλA_\lambda, the preprocessing, the feature selection, the prompt, the stopping rule, the threshold, or λ^\hat\lambda.

Some protocols refit the selected pipeline on ItrainIdevI_{\text{train}}\cup I_{\text{dev}} before this one test evaluation. That is valid only if the refit rule was fixed before reading the test set. The invariant is not "never use dev again"; it is "never let test influence the selected procedure."

With KK-fold cross-validation, we partition the training budget ItrainI_{\text{train}} into folds F1,,FKF_1,\ldots,F_K. For each λ\lambda, fit on all folds except FkF_k and validate on FkF_k. A per-example version is

R^cv(λ)=1Itraink=1KiFkL ⁣(Aλ(DItrainFk)(xi),yi).\widehat R_{\text{cv}}(\lambda)= \frac{1}{|I_{\text{train}}|}\sum_{k=1}^K \sum_{i\in F_k} L\!\left(A_\lambda(D_{I_{\text{train}}\setminus F_k})(x_i),y_i\right).

When all folds have the same size, this is the same as averaging the fold losses.

Then choose λ^\hat\lambda by cross-validation, refit the chosen pipeline on the full training budget, and evaluate on the untouched test set.

Leakage appears when the fitted pipeline depends on held-out rows. Suppose TT is a preprocessing operation such as scaling, imputation, PCA, or feature selection. A clean pipeline is

T^train=B(DItrain),f^=A(T^train(DItrain)).\hat T_{\text{train}}=B(D_{I_{\text{train}}}),\qquad \hat f=A(\hat T_{\text{train}}(D_{I_{\text{train}}})).

The same learned transform T^train\hat T_{\text{train}} may be applied to dev/test inputs, but it must not be fitted from dev/test rows. The leaky version is

T^all=B(DItrainDIdevDItest),\hat T_{\text{all}}=B(D_{I_{\text{train}}}\cup D_{I_{\text{dev}}}\cup D_{I_{\text{test}}}),

then evaluating on ItestI_{\text{test}} after the test rows helped define the feature space. That reported score answers the wrong question: "how well does a pipeline do after seeing statistics from the evaluation set?"

Inside cross-validation, "training rows" means ItrainFkI_{\text{train}}\setminus F_k for the current fold. A scaler, imputer, PCA map, or feature selector fitted once on all of ItrainI_{\text{train}} before scoring folds has already leaked validation-fold information into the CV estimate.

For time series, groups, people, papers, or benchmark items with near-duplicates, the disjoint-index condition is not enough. The split must respect the unit of generalization: future time after past time, new users after old users, new papers after training papers, or new problem families after seen families.

03

03

Code

Keep the implementation aligned with the notation so the algorithm is legible.

Section prompt
import numpy as np

rng = np.random.default_rng(10)
n, p = 300, 120
X = rng.normal(size=(n, p))
y = 2 * X[:, 0] - 1.3 * X[:, 1] + 0.8 * X[:, 2] + rng.normal(scale=1.2, size=n)
idx = rng.permutation(n)
train, dev, test = idx[:160], idx[160:230], idx[230:]

def top_corr(rows, k):
    Xr, yr = X[rows], y[rows] - y[rows].mean()
    xr = Xr - Xr.mean(axis=0)
    denom = np.sqrt(np.sum(xr * xr, axis=0)) * np.sqrt(np.sum(yr * yr)) + 1e-12
    score = np.abs(np.sum(xr * yr[:, None], axis=0)) / denom
    return np.argsort(score)[-k:]

def fit_eval(features, rows):
    A = np.c_[np.ones(len(train)), X[train][:, features]]
    w = np.linalg.lstsq(A, y[train], rcond=None)[0]
    B = np.c_[np.ones(len(rows)), X[rows][:, features]]
    pred = np.sum(B * w, axis=1)
    return np.mean((pred - y[rows]) ** 2)

ks = [3, 5, 10, 20]
dev_scores = [(fit_eval(top_corr(train, k), dev), k) for k in ks]
k = min(dev_scores)[1]

clean_test_mse = fit_eval(top_corr(train, k), test)
leaky_test_mse = fit_eval(top_corr(np.concatenate([train, dev, test]), k), test)

print("chosen k from dev:", k)
print("clean test MSE:", round(clean_test_mse, 3))
print("leaky test MSE:", round(leaky_test_mse, 3))

The clean path selects features using only the training rows, uses the development set to choose k, and touches the test set only once. The leaky path selects features using all rows, including test targets. With this fixed seed, the leaky score is lower not because the model is better, but because the held-out targets helped choose lucky columns.

04

04

Interactive Demo

Use direct manipulation to connect the explanation to a moving system.

Section prompt

Use the controls to create a harder or easier feature-selection problem. First predict which pipeline is invalid because information leaked before model fitting. Then reveal the scores and trace the arrow that made the test estimate too optimistic.

The demo uses a synthetic regression task with three real signal features and many noise features. Feature selection is preprocessing. If it sees the test target, it can pick noise columns that accidentally match the held-out answers.

Live Concept Demo

Explore Train/Dev/Test Splits, Cross-Validation, and Leakage

The stage is code-native and interactive. Use it to test the explanation against the mechanism.

difficulty 3/5undergraduatecode-aligned
Demo Prediction Checkpoint

Manipulate one control and predict the visible change.

Commit to what Train/Dev/Test Splits, Cross-Validation, and Leakage should make visible before reading the result.

After The First Pass

Turn the concept into an inspected object.

Once the invariant is visible in the intuition, math, code, and demo, use these panels to inspect the mechanism visually, check source support, practice the idea, and attach a grounded research question.

Mechanism Storyboard

See the idea move before the page explains it

Train/dev/test splits and cross-validation keep learning, choosing, and final evaluation separate; leakage breaks that contract.

Prediction open01 / Intuition
Prediction lens

Start with the picture, metaphor, or geometric mechanism.

Commit first

Before reading further, choose the kind of change Train/Dev/Test Splits, Cross-Validation, and Leakage should make visible.

Visual Inquiry

Make the image answer a mathematical question

Train/dev/test splits and cross-validation keep learning, choosing, and final evaluation separate; leakage breaks that contract.

4/4 stages readyLive demo connected
Prediction

Which visible object should carry the first intuition?

Commit first

Pick the cue that should make Train/Dev/Test Splits, Cross-Validation, and Leakage easier to reason about before the page gives the answer.

Source Grounding

Canonical references for the mechanism on this page.

course-notes · 2019CS229 Notes: Regularization and Model SelectionStanford CS229

Source for hold-out cross-validation, k-fold cross-validation, and model selection by held-out empirical error.

Open source
book · 2023An Introduction to Statistical LearningJames, Witten, Hastie, Tibshirani, and Taylor

Source for validation-set and cross-validation estimates of test error and model assessment/selection framing.

Open source
documentation · 2026scikit-learn User Guide: Common pitfalls and recommended practicesscikit-learn developers

Source for data leakage, train-only preprocessing, feature-selection leakage, and pipeline discipline.

Open source

Claim Review

Train/dev/test splits and cross-validation keep learning, choosing, and final evaluation separate; leakage breaks that contract.

Status1 substantive review recorded

Claims without a substantive review badge still need exact source-support review.

Sources3 references

cs229-model-selection, islr-cross-validation, sklearn-data-leakage

Witnesses4 local objects

Use equation, code, and demo objects to check whether the source support is operational.

Substantively reviewedA valid evaluation workflow separates fitting, model selection, and final testing; preprocessing or tuning learned from held-out data leaks information and can make performance estimates too optimistic.Claim metadata: source checked

CS229 supports held-out and k-fold model selection; ISLR supports validation/CV as estimates of test error; scikit-learn directly supports train-only preprocessing and the optimistic-bias leakage warning.

Sources: CS229 Notes: Regularization and Model Selection, An Introduction to Statistical Learning, scikit-learn User Guide: Common pitfalls and recommended practicesThe demo is a finite synthetic feature-selection witness, not a universal leakage-size guarantee; valid splits still require time/group/task-aware split design.A bounded review summary is present; still check caveats and exact source scope.

Matched the page's split/CV/leakage contract to CS229's hold-out and k-fold model-selection algorithms, ISLR's validation/CV test-error framing, and scikit-learn's explicit fit/fit_transform, feature-selection leakage, and pipeline guidance. GPT Pro reviewed pushed commit 03f125f and required only small precision/demo/graph fixes before publication.

Reviewer: codex+gpt-pro-oracle; reviewed 2026-06-28

Practice Loop

Try the idea before it explains itself

Train/dev/test splits and cross-validation keep learning, choosing, and final evaluation separate; leakage breaks that contract.

Readiness0/3 checks ready
Predict

Before touching the demo, predict one visible change that should happen in Train/Dev/Test Splits, Cross-Validation, and Leakage.

Hint 1

Reveal when your model needs a nudge.

Hint 2

Reveal when your model needs a nudge.

Hint 3

Reveal when your model needs a nudge.

Object research drawerClose
ConceptTrain/Dev/Test Splits, Cross-Validation, and LeakageMachine Learning

Research Room

Attach the question to an exact object

Pick the concept, equation, source, code witness, claim, misconception, or demo state before asking for help. The handoff stays grounded to that object.
Next local actionNo local draft saved yet

Open the draft below to save one note and next action in this browser.

conceptMachine Learning

Train/Dev/Test Splits, Cross-Validation, and Leakage

Anchored question

What is the smallest example that makes Train/Dev/Test Splits, Cross-Validation, and Leakage click without losing the math?

Local action draftNo local draft saved yetExpand only when ready to capture one local next action
Local action draft

This draft stays locally in this browser for concept:machine-learning/train-dev-test-cross-validation-leakage.

No local draft saved.
Evidence to inspect
  • Source ids to inspect: cs229-model-selection, islr-cross-validation, sklearn-data-leakage
  • Definition, prerequisite, and contrast concept links
  • The equation or code witness that makes the concept operational
  • One demo state that shows the invariant instead of a slogan
What would resolve this
  • The learner can state the mechanism in their own words
  • The learner can name the prerequisite that would repair confusion
  • The learner can predict how the mechanism changes under one perturbation
Grounded AI handoff

I am working in Continuous Function's research reading room. Object: concept - Train/Dev/Test Splits, Cross-Validation, and Leakage Object key: concept:machine-learning/train-dev-test-cross-validation-leakage Context: Machine Learning Anchor id: concept/concept-notebook/machine-learning/train-dev-test-cross-validation-leakage Open question: What is the smallest example that makes Train/Dev/Test Splits, Cross-Validation, and Leakage click without losing the math? Evidence to inspect: - Source ids to inspect: cs229-model-selection, islr-cross-validation, sklearn-data-leakage - Definition, prerequisite, and contrast concept links - The equation or code witness that makes the concept operational - One demo state that shows the invariant instead of a slogan What would resolve this: - The learner can state the mechanism in their own words - The learner can name the prerequisite that would repair confusion - The learner can predict how the mechanism changes under one perturbation Answer as a careful research tutor: stay source-grounded, separate verified evidence from assumptions, name the relevant math objects, and end with one next action.

Open source object
concept/concept-notebook/machine-learning/train-dev-test-cross-validation-leakage concept:machine-learning/train-dev-test-cross-validation-leakage