AI Wiki中文/EN

Train, validation, and test splits

训练验证测试划分

Choose a split that matches deployment, keep learned preprocessing inside training, and detect entity leakage with a reproducible group split.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

New rows are not always new cases

Suppose eight machines each contribute four sensor records, and every record from one machine shares the same maintenance label. Put two records per machine into training and the other two into testing. A program can memorize the label attached to each machine ID and score perfectly without learning a sensor pattern.

That split may answer a question about new records from already known machines. It does not establish performance on a machine never seen before. If deployment involves new machines, their IDs must be separated across the relevant training and evaluation groups. Choosing the unit of generalization comes before choosing percentages.

Three roles, one selection procedure

Training data fits parameters and learned preprocessing. Validation data helps choose architectures, hyperparameters, features, thresholds, and stopping points. Test data evaluates the selected procedure under the stated sampling conditions. These names describe how data is used, not a property conferred by a filename. scikit-learn, cross-validation guide

For an independently held-out test set of size mm, the average loss is:

R^test=1m∑i=1mℓ(fselected(xi),yi).\widehat R_{\mathrm{test}}=\frac1m\sum_{i=1}^{m}\ell(f_{\mathrm{selected}}(x_i),y_i).

Under independent identically distributed sampling from the target distribution, conditioning on the training and selection data makes the expected test average equal to the selected model’s population risk. This argument fails if test outcomes help select the model or if the test sampling process represents a different target. Correlated records also change uncertainty calculations; the number of rows is not necessarily the number of independent observations.

Preprocessing belongs inside this separation. A training-fitted mean for standardization is:

μtrain=1ntrain∑i∈trainxi,zj=xj−μtrainσtrain.\mu_{\mathrm{train}}=\frac1{n_{\mathrm{train}}}\sum_{i\in\mathrm{train}}x_i,\qquad z_j=\frac{x_j-\mu_{\mathrm{train}}}{\sigma_{\mathrm{train}}}.

Use the same fitted mean and scale to transform validation and test examples. Refitting them on test inputs changes the evaluation procedure, even without using test labels. Pipelines help fit transformations within each cross-validation fold; feature selection and vocabulary construction require the same care. scikit-learn, common pitfalls

Different splits answer different questions:

Intended useTypical separationWhat it protects against
New independent examplesRandom holdoutReusing fitted examples
New patients, users, or devicesGroup holdoutShared-entity information
Future observationsTime-respecting holdoutLearning from the future
Hyperparameter selection with limited dataInner validation within outer evaluationReporting selection scores as independent evaluation

These are starting points. Group and temporal constraints may need to apply together. A chronological split alone does not stop a feature from including measurements recorded after the prediction time.

Check the split before fitting a model

This complete standard-library example creates the machine records, demonstrates memorization under the row split, and constructs a seeded split of whole machines. It checks disjoint IDs, complete row coverage, and consistent use of training-fitted preprocessing. Its toy labels are invented for the experiment, not industrial data.

import random
import math

rows = [{'id':4*g+j,'machine':g,'x':10*g+j,'y':g%2}
        for g in range(8) for j in range(4)]
row_train = [r for r in rows if r['id']%4 < 2]
row_test = [r for r in rows if r['id']%4 >= 2]
memory = {r['machine']:r['y'] for r in row_train}
assert all(memory[r['machine']] == r['y'] for r in row_test)

def group_split(rows, seed=17):
    groups = sorted({r['machine'] for r in rows})
    if len(groups) != 8 or len({r['id'] for r in rows}) != len(rows):
        raise ValueError("example requires eight groups and unique row IDs")
    random.Random(seed).shuffle(groups)
    owner = {g:(0 if i < 4 else 1 if i < 6 else 2) for i,g in enumerate(groups)}
    parts = [[],[],[]]
    for row in rows:
        parts[owner[row['machine']]].append(row)
    return parts

train, validation, test = group_split(rows)
assert [len(p) for p in (train,validation,test)] == [16,8,8]
sets = [{r['machine'] for r in part} for part in (train,validation,test)]
assert all(sets[i].isdisjoint(sets[j]) for i in range(3) for j in range(i))
assert sorted(r['id'] for part in (train,validation,test) for r in part) == list(range(32))
assert group_split(rows) == group_split(rows)
mean = sum(r['x'] for r in train)/len(train)
scale = math.sqrt(sum((r['x']-mean)**2 for r in train)/len(train))
assert scale > 0
transformed = [[(r['x']-mean)/scale for r in part] for part in (train,validation,test)]
assert abs(sum(transformed[0])) < 1e-12
assert len(transformed[2]) == len(test)

For nn rows and gg groups, collecting and assigning groups takes O(n+glog⁡g)O(n+g\log g) time here because IDs are sorted before seeded shuffling. The stored partitions use O(n+g)O(n+g) space. A fixed seed reproduces this particular split; it does not prove the split is appropriate or that a result is stable across samples.

Repeated peeking changes the test set’s role

If a team repeatedly changes the model after seeing its test score, that set participates in selection. Reporting only the winning score understates the search that produced it. Nested cross-validation separates an inner selection loop from an outer evaluation loop, although it cannot repair entity leakage or invalid temporal features. Cawley and Talbot, 2010

There is no universally correct 80/10/10 ratio. Rare outcomes, limited groups, training requirements, and the precision of the final estimate affect the allocation. Stratification can preserve label proportions but does not enforce group independence. If groups differ greatly in size, balancing rows and balancing groups are different goals.

After selecting settings, refitting on training plus validation data can be reasonable when specified in advance. Refit the entire learned pipeline, then evaluate once on the untouched test set. If data is later used for final production fitting, it no longer provides independent evaluation of that newly fitted model.

Name the population you want to predict

  1. Why can the machine-ID memorizer score 100% on the row split? Answer: each test machine already has labeled training records.
  2. Is a stratified random split sufficient for evaluating new patients with repeated visits? Answer: no. Stratification balances labels; patient grouping addresses a different dependency.
  3. Where should an imputer’s replacement values be estimated? Answer: on training data, separately inside each training fold during cross-validation.
  4. A forecasting feature averages the following week’s readings. Does an earlier/later row split make it valid? Answer: no. The feature uses information unavailable at prediction time.

Evaluate the procedure that will actually be used

A report should state the split unit, prediction time, group overlap, selection budget, preprocessing scope, and final sample counts. Confidence intervals and external validation build on that design. A sophisticated metric cannot compensate for evaluating the wrong population or allowing future information into the model.

Make a prediction, then check

To evaluate previously unseen devices, how should records from one device be handled?

Choose one answer

Learning objectives

  • Choose random, grouped, or temporal splits for the target population and detect entity leakage.
  • Fit preprocessing within training folds and distinguish model selection from final evaluation.

Prerequisites & connections

Explore related knowledge →

References

  1. Cross-validation: evaluating estimator performance
    scikit-learn developers
  2. scikit-learn — Common pitfalls and recommended practices
    scikit-learn developers
  3. On Over-fitting in Model Selection and Subsequent Selection Bias in Performance Evaluation
    Gavin C. Cawley; Nicola L. C. Talbot · 2010

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-05 · Codex technical check: cited-source comparison, re-derivation and recalculation, bilingual argument comparison, and executed Python assertions; no independent human peer review.

  • Verified the device memorizer’s perfect row-split result; group splits at 30 seeds preserved disjoint IDs and complete row coverage.
  • Checked the conditional-expectation argument for test means, within-fold preprocessing, temporal availability, stratification versus grouping, and evaluation after refitting.
  • Compared bilingual arguments, conditions, examples, and exercise answers; structural checks separately compare formulas, code, sections, and references. No independent human peer review.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.