Train, validation and test sets
A data split assigns examples to different roles. Training data determines fitted parameters, validation data helps choose settings or model families, and a test set estimates performance of the frozen selection on new examples. A trustworthy split represents the actual prediction situation; randomness alone cannot make that happen. Imagine forecasting shipment delays for next week using records available today.
Separate fitting, selection and final evaluation
Suppose two models predict whether a shipment arrives late. Fit both using training records, compare their errors on validation records, choose one using a rule established beforehand, and freeze the choice. Evaluate that frozen procedure on test records. If you change the model because of test results, those results become selection evidence; obtain a fresh independent test set before making a new final claim. A predefined final refit on training plus validation is possible, but must occur before opening the test results. Fit any preprocessing again on the allowed final fitting data only.
| Split | Allowed use | Not allowed in a clean experiment |
|---|---|---|
| Training | Fit model and preprocessing | Claim independent generalization from training score |
| Validation | Compare configurations and choose a threshold | Present repeated selection scores as final unbiased evidence |
| Test | Evaluate the frozen procedure | Tune features, thresholds or model choices after seeing results |
There is no universal 80/10/10 ratio. The number of independent observations, rare outcomes, expected shift and precision requirements determine whether each set is useful. If data are too scarce, consider cross-validation within development data, with a separate final test when feasible.
Chronological splits: predict the future using the past
Our toy records are pairs of integer day and unique order ID. Days 1–3 form training, days 4–5 validation, and day 6 or later test. All labels in an earlier window are assumed available before the next window begins. In a real delay forecast, delivery outcomes may arrive days later, so use label-availability timestamps and possibly a gap between windows. Sorting alone cannot resolve that problem.
def chronological_split(records, validation_start, test_start): if validation_start >= test_start: raise ValueError('Cutoffs must be increasing') train, validation, test = [], [], [] for day, order in sorted(records): if day < validation_start: train.append(order) elif day < test_start: validation.append(order) else: test.append(order) return [train, validation, test]
records = [(6, 'F'), (1, 'A'), (4, 'D'), (2, 'B'), (5, 'E'), (3, 'C')]print(chronological_split(records, 4, 6))Output: [['A', 'B', 'C'], ['D', 'E'], ['F']]. The cutoffs are inclusive at the start of the later window. Sorting the pairs creates a new list; the input is not modified. A day equal to 4 belongs to validation, and one equal to 6 belongs to test. Empty windows are returned as empty lists for auditing; they cannot support fitting or evaluation without more data. The function assumes comparable integer days and unique order IDs. It does not check label availability or group overlap.
Random splits for exchangeable independent examples
When predicting new independent observations from a comparable distribution, a shuffled split can be reasonable. The following example assumes one record per independent ID and no temporal dependence. It uses Python standard-library Random with an explicit seed and sorted IDs to reproduce the partition for the same interpreter and inputs. This is not stratified sampling; a rare class can disappear from a subset. For classification with independent rows, stratification may help preserve class proportions, but it does not solve group dependence or time leakage.
from random import Random
def seeded_split(ids, train_size, validation_size, seed): if len(set(ids)) != len(ids): raise ValueError('IDs must be unique') if min(train_size, validation_size) < 0 or train_size + validation_size > len(ids): raise ValueError('Invalid split sizes') ordered = sorted(ids) Random(seed).shuffle(ordered) end = train_size + validation_size return [ordered[:train_size], ordered[train_size:end], ordered[end:]]
ids = ['A', 'B', 'C', 'D', 'E', 'F']split = seeded_split(ids, 3, 1, 7)print([len(part) for part in split])print(split == seeded_split(list(reversed(ids)), 3, 1, 7))print(sorted(item for part in split for item in part))Output on three lines: [3, 1, 2], True, ['A', 'B', 'C', 'D', 'E', 'F']. These outputs check counts, repeatability under input reordering, and membership rather than rely on an exact shuffle order across Python releases. Record the actual membership, seed, data version and interpreter for repeatable experiments. The seed does not guarantee representativeness, independence or model quality. The function deliberately permits empty subsets; check that all required subsets are usable before starting a real experiment.
Choose the unit of evaluation
If multiple records come from one order, machine or customer, independent-row assumptions may fail. If deployment must handle unseen orders, split at order level. If deployment predicts later events for known orders, a carefully timestamped split may instead match the intended task. In both cases check whether features and labels were available at prediction time. Random row splitting across repeated measurements can make a model appear to generalize when it has merely recognized an earlier example.
Check the dataset before interpreting a score
Document source and permission, collection window, prediction unit, feature and label timing, missing values, inclusion criteria, group identity, class counts, sampling bias and any changes since collection. A test set of daytime deliveries does not measure nighttime performance. Use synthetic or approved data, protect held-out labels with access controls, and log evaluation runs. Access separation limits accidental tuning; it does not remove distribution mismatch. Keep immutable split membership and data versions for reproducibility.
Practice
Given records on days 2, 3, 5, 5 and 7, place them in windows with cutoffs 5 and 7. Then explain why random shuffling would be inappropriate for a future-week forecast. Check: days 2 and 3 are training, both day-5 rows validation, day 7 test. The next lesson checks group overlap and fitted preprocessing.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Train, validation and test sets quiz
Apply split and leakage concepts to original shipment scenarios.
Which set is used to choose between two model configurations?
Using chronological_split with validation_start=4 and test_start=7, which subset receives a record on day 4?
Delivery labels arrive two days after dispatch. What must be checked before using historical rows to fit a forecast at a cutoff?
For which evaluation design is a seeded row shuffle a reasonable candidate?
A threshold is changed after inspecting final test results. What supports a new independent final performance claim?