Data splits and leakage

Once you build a model you need a number for how well it does. But the same model can score 94% or 67% depending on which data you test it on. Split data from people who were each measured several times in two different ways, and see where the score puffs up.

Short answer. A model's score only means something when it is measured on data the model never learned from. You learn on the training set, pick on the validation set, and measure once at the end on the test set. When information from the test side slips into learning or picking, that is data leakage, and the score comes out better than it really is. Split along the unit that is new when the model is used: a new person, the next day.

The 60 points are two numbers measured 6 times for each of 10 people. The data is made up with a fixed-seed random generator, so it is the same every time you open the page. Each person belongs to a group (A or B), and the model looks at one measurement and guesses that person's group. The model is a nearest neighbor classifier: it finds the single closest training point and answers with its group. Green circles are group A, blue squares are group B, black numbers are person numbers. Large hollow marks are test points, small filled marks are training points, gray lines run from a test point to its nearest training point, and orange rings mark wrong answers. Both splits put 18 points on the test side.

Try this. ① At the start (random split) the model gets 17 of the 18 test points right: 94%. Follow the gray lines: 15 of the 18 land on another measurement of the same person. The model did not recognize the group, it recognized the person. ② Press "Split by person". All 18 measurements of people 4, 8 and 9 go to the test side, and the model gets 12 right: 67%. Every gray line now lands on a different person. ③ Same model, same data, only the split changed. The setup that copies using the model on people it has never seen is ②. The screen shows the data for seed 1. Make the data 200 times with seeds 1 to 200 and the average is 90% for the random split and 56% for the split by person.

Definitions

The text below compares the parts to a workbook, a mock exam and the final exam. These are the textbook definitions. The names differ a little between books and tools, and this page uses them as below.

training set
The data used to learn the model's parameters (weights).
validation set
Data held back from training and used to choose hyperparameters and models. Because it is used many times while choosing, the validation score of the chosen model can come out better than its performance on new data.
test set
Data used for neither training nor choosing. It is held back until the model is chosen, then used once at the end to estimate performance on new data (generalization performance).
data leakage
Information that is not available when the model is really used gets into training or model selection. Examples are statistics of the test set and values you cannot know at the moment of prediction. The evaluation score then comes out better than the real performance. When a feature that is only set after the outcome leaks in, it is called target leakage.
k-fold cross-validation
A method that splits the data into k folds that do not overlap. Each fold takes one turn as the test part while the other k − 1 folds are used for training, which gives k scores, and their mean is the performance estimate. Setting k equal to the number of samples is called leave-one-out.
group k-fold cross-validation
k-fold cross-validation that splits by group (person, patient, site, date and so on), so that all samples of one group go into the same fold. The data of one group is never split between training and test.

1. Train, validation, test: what each part does

You want to know how well the model will do on new data, but you do not have new data yet. So you hold out part of the data you have and treat it as if it were new. A score measured on held-out data copies the score on new data only if the model has never seen that data. The work is split three ways. In school terms: the workbook, the practice exam, the final exam.

PartWhat it is forHow often you look
Training set (workbook)The model fits its numbers (weights)All through training
Validation set (practice exam)You pick settings (learning rate, number of layers, when to stop) and modelsMany times, every time you pick
Test set (final exam)You measure the final score after all picking is doneOnce

If you pick many times with the validation set, your choices bend toward it. So the final score is measured again on test data that was not used for picking. Books and tools do not always use the same names, and some call this page's test set the "validation" set. What the gap between training and test scores means is on the overfitting page.

2. Data leakage: four common forms

Data leakage is when information that you will not have when the model is really used slips into training or picking. The test score looks good, but the model does not do as well in real use. Nothing throws an error, so it is easy to miss.

FormWhat leaksHow to stop it
Normalizing before splittingIf you compute the mean and standard deviation on all the data, the test data's mean and spread mix into training. Filling blanks and picking features work the same waySplit first. Compute on the training side only and reuse those numbers on the test side (normalization, section 7). In cross-validation, wrap preprocessing and model in one pipeline
Same person or same day on both sidesMeasurements of one person, several photos of one patient, photos taken the same day on the same machine all look alike. The model can memorize the person or the machine and still score well (the experiment above)Split by group (person, patient, date) so each group sits on one side only
Using the future to predict the pastShuffling time-ordered data mixes in questions where tomorrow's value helps guess yesterday. A column that is only filled in after the outcome (a "refund date" column when you predict refunds) leaks the same wayCut by time. For each column, ask "would I know this value at the moment of predicting?"
Picking with the test set many timesIf you look at the test score, change a setting and measure again over and over, you end up with settings that suit the test dataPick with a validation set or cross-validation, and look at the test set once at the end

3. How the formula is built: k-fold cross-validation

If you split only once, the score swings with which data landed on the test side. k-fold cross-validation cuts the data into k folds and gives each fold one turn as the test side, for k rounds. Below, the 60 points from the experiment above are cut into 5 folds by person.

Press "Next" to go one step at a time. A piece is added to the formula on top (the orange background is the piece just added), rounds are added to the grid, and the reason appears below. Each cell says "test" or "train" in words.

  1. Cut into folds: k = 5. Cut the 10 people into 5 folds of 2. All measurements of a person go into one fold.
  2. First round: s₁. Fold 1 is the test side and the other 4 folds are the training side. Measure the share right, s₁. So far this is the same as a single split.
  3. Rotate: s₁ + s₂ + s₃ + s₄ + s₅. Move the test fold along and do all 5 rounds. Every point is used for testing exactly once.
  4. Average: CV = (s₁ + s₂ + s₃ + s₄ + s₅) ÷ 5. The mean of the round scores is the cross-validation score. With k folds, CV = (s₁ + s₂ + … + s_k) ÷ k.

If every round has the same number of test points, this mean equals the share right over all the data. If the folds differ in size, the two differ a little. Set k equal to the number of points and you get leave-one-out. After scoring, the model you actually use is usually trained again on all the data. Cross-validation measures how well "this way of building a model" does, and the 5 models built in the rounds are thrown away.

Try this. ① At the start you only see the 10 people grouped into 5 folds. ② "Next": the first round tests the 12 measurements of people 1 and 2 and gets 6 right, so s₁ = 0.5. ③ "Next": the 5 round scores are 0.5, 0.67, 0.75, 0.42, 1. With a single split you could have gotten 0.42 or 1. ④ "Next": the mean, 0.67, appears as an orange dashed line. It equals 40 right out of 60. Cut the same data into 5 random folds and the mean is 1.

4. Work it by hand

Four people each measured one number twice. People 1 and 2 are in group A, people 3 and 4 in group B. The model is the same nearest neighbor classifier as above.

PersonGroupMeasured
1A1.0, 1.4
2A2.0, 2.4
3B3.0, 3.4
4B6.0, 6.4
  1. Leave out one measurement at a time (the far end of random). Leave out 1.4 and its nearest value is the same person's 1.0 (distance 0.4), so it is right. Every measurement has its twin at distance 0.4 and every other person at 0.6 or more, so all 8 are right. Score 1.
  2. Leave out one person at a time (4 folds by group). Leave out person 1: the nearest value to both 1.0 and 1.4 is 2.0 (A), both right, s₁ = 1. Leave out person 2: 2.0 is nearest to 1.4 (A, distance 0.6), right; 2.4 is nearest to 3.0 (B, distance 0.6), wrong, s₂ = 0.5. Leave out person 3: both 3.0 and 3.4 are nearest to 2.4 (A), both wrong, s₃ = 0. Leave out person 4: both 6.0 and 6.4 are nearest to 3.4 (B), both right, s₄ = 1.
  3. Average. CV = (1 + 0.5 + 0 + 1) ÷ 4 = 2.5 ÷ 4 = 0.625. The same as 5 right out of 8, 5 ÷ 8.

Same data, same model, and the split alone gives 1 or 0.625. People 2 and 3 sit near the line between A and B (between 2.4 and 3.0), and they start getting wrong answers as soon as their own twin is gone.

5. When to use which

SplitGoodBadUse it when
Random
KFold, train_test_split
The simplest. Honest when each row was collected on its ownPuffs up the score when rows are grouped or in time order. A rare class can almost miss a foldRows are independent and classes are balanced
Stratified
StratifiedKFold
Each fold keeps the class shares of the whole. Rare classes land in every fold, so scores swing lessStill ignores groups and time. Works directly only for classificationClassification with skewed classes (for example very few fraud cases). scikit-learn uses it by default for classifiers
Group
GroupKFold, StratifiedGroupKFold
Keeps data from one person, device or day on one side. Measures the score on new groupsWith few groups, round scores swing a lot. Groups of different size make folds of different sizeOne person, patient or shop gives many rows, and the model will be used on new people or shops
Time-ordered
TimeSeriesSplit
Learns on the past and tests on the period after, just like real useEarly rounds have little training data. If things change over time, round scores differData piles up over time (sales, sensor logs, orders) and you predict what comes next
Spatial blocks, whole site
GroupKFold, LeaveOneGroupOut
Keeps nearby data on one side only. Measures the score on a zone or a site the model has not seenScores come out lower and swing a lot between rounds. If zones are small, neighbouring zones still look alike and it still leaksData with a value at each place: drone and satellite images, soil, weather

Splitting grouped data

Decide what a group is by the unit that is new when the model is used. A model for new patients groups by patient. A model for new shops groups by shop. Give every row a group number and split on that number. The "Split by person" button above does exactly this. To also keep class shares even, use StratifiedGroupKFold, which does group and stratified splitting together.

Splitting time-ordered data

Do not shuffle. Line the rows up in time order, learn on the earlier part and test on the part right after. Each round grows the training stretch further forward and tests on the next stretch. If you predict a value several days ahead, leave that many days empty between the end of training and the start of testing. The gap option of TimeSeriesSplit is that empty stretch.

# scikit-learn: wrap preprocessing and model together, pass the split as cv
from sklearn.model_selection import GroupKFold, LeaveOneGroupOut, TimeSeriesSplit, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier

model = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=1))
scores = cross_val_score(model, x, y, groups=person_ids, cv=GroupKFold(n_splits=5))   # group: person number
scores = cross_val_score(model, x, y, cv=TimeSeriesSplit(n_splits=5))                 # time: x in time order
scores = cross_val_score(model, x, y, groups=block_ids, cv=GroupKFold(n_splits=4))    # spatial blocks: zone number
scores = cross_val_score(model, x, y, groups=site_ids, cv=LeaveOneGroupOut())         # whole site (LOSO): site number
print(scores.mean(), scores.std())                                                    # mean and spread

Splitting data that has a location: spatial blocks and LOSO

Data on a map looks like its neighbours. The soil in the next cell and the crop in the next field are almost the same. Split at random and the cell right next to a test cell lands on the training side, so the model gets it right by remembering the place, not the rule. It is the same thing as one person sitting on both sides of grouped data. So the group becomes the place.

How to splitGroupQuestion it answers
Spatial blocksCut the map into large cells (zones) and put a whole zone on the training or the test sideDoes it work on an unseen zone of the same site?
Whole site (LOSO, leave-one-site-out)Put one whole site on the test side and learn from the other sites. Repeat once per siteDoes it work on a site it has never been to?

The two are also used together. One site is set aside for the final test (LOSO), and inside the remaining sites you split by zone to pick settings (spatial blocks). In some fields LOSO means leave-one-subject-out, where one person is left out. Both are "leave one group out"; only the group differs, a site or a person.

The data is made up: three sites sampled as 8 × 8 cells, 192 cells in all. Each cell has two numbers and a group (A or B). The group changes gently across a site, and the two numbers carry, besides the group's signal, a larger value that drifts slowly with position and a value that differs by site. The model is the same nearest-neighbour classifier as in the experiment above.

Try this. ① "At random" averages 89%. For 37 of the 64 test cells in round 1 the nearest training cell is in the same zone. ② Press "Spatial blocks": whole zones go to the test side and the mean drops to 77%, swinging from 65% to 90% between rounds. ③ "Whole site" averages 68%, with 73%, 70% and 61% by site. 117 of the 192 cells are group A, so always answering A already scores 61%. On a site it has never seen this model is only a little better than that, and the 89% from the random split hid it.

A zone has to be larger than the distance over which the data looks alike. If zones are small, neighbouring zones resemble each other and it still leaks. With few sites the LOSO score differs a lot from site to site, so report the per-site scores along with the mean.

6. Things to know

PropertyIn plain wordsIn the experiment
Trust it only on data never seenThe more the test data looks like the training data, the more the score puffs upRandom 94%, by person 67%
Split unit = the unit that is new in useA model for new people splits by person. A model for the future splits by time"Split by person"
A cross-validation score is the mean of round scoresIt takes the luck out of a single split. Report the spread (lowest and highest round) with it0.42 to 1, mean 0.67
Everything learned from data stays inside the training sideMeans, standard deviations, fill-in values, picked features: recompute them each round from the training side onlyFirst row of section 2
A test set wears out each time you lookThe more you fix things after looking at the test score, the more you fit the test data. Look once at the endLast row of section 2

Where it is used

Common questions

Why keep the validation set and the test set apart?

When you pick settings or models by looking at the validation score, what you pick leans toward that validation data. So the validation score comes out a bit too good. Measuring the final choice once on test data that played no part in picking gets you closer to the score on new data.

What k should I use?

5 or 10 are common. A larger k gives each round more training data, so each model is closer to one built on all the data, but you have to train k times. In deep learning, where one training run is expensive, people often hold out a single validation set instead of cross-validating. In scikit-learn, cross_val_score uses 5 folds unless you say otherwise.

If I cross-validate, can I skip the test set?

If you also picked settings by looking at the cross-validation score, that mean score leans toward your choice too. Measure the final score on a held-out test set, or use nested cross-validation: pick settings inside an inner cross-validation and get the score from an outer one.

Words

Plain words hereWhat books call it
Training, validation, test dataTraining set, validation set (dev set), test set
Holding part of the data backHold-out
Information slipping inData leakage. A column filled in only after the outcome is target leakage
k-fold cross-validation, fold, roundk-fold cross-validation, fold, split
Keeping class shares evenStratification, stratified k-fold
Splitting by groupGroup k-fold. One group at a time is leave-one-group-out
Spatial blocksspatial block cross-validation, spatial k-fold
Leaving a whole site outLOSO (leave-one-site-out); leaving a person out is leave-one-subject-out. LeaveOneGroupOut in scikit-learn
Nearby places look alikespatial autocorrelation
Leaving one out at a timeLeave-one-out (LOO)
Splitting by timeTime series split
Nearest neighbor classifier1-nearest neighbor (k-NN with k = 1)
SettingsHyperparameters
Cross-validation inside cross-validationNested cross-validation
Preprocessing and model wrapped as onePipeline

Sources

← Confusion matrix, precision, recall and F1Hyperparameter search: grid and random →