Bring the mental model from Bias-Variance Decomposition; this page will reuse it instead of restarting from zero.
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.
Concept Structure
Train/Dev/Test Splits, Cross-Validation, and Leakage
Start with the picture, metaphor, or geometric mechanism.
Make the objects explicit and connect them with notation.
Mirror the equations with runnable implementation details.
Manipulate the mechanism and watch the idea respond.
Learning map
Train/Dev/Test Splits, Cross-Validation, and LeakageConceptual Bridge
What should feel connected as you move through this page.
Train/dev/test splits and cross-validation keep learning, choosing, and final evaluation separate; leakage breaks that contract.
The next edge should feel earned: use the demo prediction here before following Regularization: Ridge, Lasso, and Elastic Net.
01
Intuition
Build the mental picture first so the rest of the page has something to attach to.
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
Math
Translate the story into symbols, assumptions, and a derivation you can inspect.
Let the full dataset be
A train/dev/test split partitions the row indices into three disjoint sets whose union is the dataset:
For a hyperparameter value , the training algorithm produces a fitted model using only the training rows:
The development loss estimates which candidate looks best:
Model selection is the act of choosing
After that choice is frozen, the test loss is computed once:
This number estimates the performance of the selected procedure only if did not influence , the preprocessing, the feature selection, the prompt, the stopping rule, the threshold, or .
Some protocols refit the selected pipeline on 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 -fold cross-validation, we partition the training budget into folds . For each , fit on all folds except and validate on . A per-example version is
When all folds have the same size, this is the same as averaging the fold losses.
Then choose 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 is a preprocessing operation such as scaling, imputation, PCA, or feature selection. A clean pipeline is
The same learned transform may be applied to dev/test inputs, but it must not be fitted from dev/test rows. The leaky version is
then evaluating on 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 for the current fold. A scaler, imputer, PCA map, or feature selector fitted once on all of 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
Code
Keep the implementation aligned with the notation so the algorithm is legible.
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
Interactive Demo
Use direct manipulation to connect the explanation to a moving system.
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.
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.
Start with the picture, metaphor, or geometric mechanism.
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.
Which visible object should carry the first intuition?
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.
Source for hold-out cross-validation, k-fold cross-validation, and model selection by held-out empirical error.
Open sourceSource for validation-set and cross-validation estimates of test error and model assessment/selection framing.
Open sourceSource for data leakage, train-only preprocessing, feature-selection leakage, and pipeline discipline.
Open sourceClaim Review
Train/dev/test splits and cross-validation keep learning, choosing, and final evaluation separate; leakage breaks that contract.
Claims without a substantive review badge still need exact source-support review.
cs229-model-selection, islr-cross-validation, sklearn-data-leakage
Use equation, code, and demo objects to check whether the source support is operational.
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-28Source support candidates
course-notes 2019CS229 Notes: Regularization and Model SelectionSource for hold-out cross-validation, k-fold cross-validation, and model selection by held-out empirical error.
book 2023An Introduction to Statistical LearningSource for validation-set and cross-validation estimates of test error and model assessment/selection framing.
documentation 2026scikit-learn User Guide: Common pitfalls and recommended practicesSource for data leakage, train-only preprocessing, feature-selection leakage, and pipeline discipline.
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.
Before touching the demo, predict one visible change that should happen in Train/Dev/Test Splits, Cross-Validation, and Leakage.
Reveal when your model needs a nudge.
Reveal when your model needs a nudge.
Reveal when your model needs a nudge.
A concrete answer is on the canvas.
The answer names why the claim should hold.
It touches the page context or a neighboring idea.
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.Open the draft below to save one note and next action in this browser.
Train/Dev/Test Splits, Cross-Validation, and Leakage
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
This draft stays locally in this browser for concept:machine-learning/train-dev-test-cross-validation-leakage.
- 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
- 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
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.
concept/concept-notebook/machine-learning/train-dev-test-cross-validation-leakage
concept:machine-learning/train-dev-test-cross-validation-leakage