Hold Out Data the Model Never Sees

A prediction model is only useful if it gets new cases right, cases it has never seen. The only honest way to find out is to set some rows aside before training, so the model never learns from them, and to measure it on those rows afterwards. Doing this well takes three things: cutting the table into parts with separate jobs, keeping the share of each answer the same in every part, and fixing the randomness so the split comes out the same on every run.

The goal is new examples, not the old ones

A model learns from a table of past examples, each with its known answer. What we want from it is generalization: right answers for examples that were not in that table, such as next month's customers. The past examples are only the material it learns from.

This is why a score on the rows the model learned from says very little. Imagine a "model" that simply stores every row it was shown together with its answer, and looks the answer up when asked. On its own rows it is never wrong: 100% right. On a new row it has nothing to look up, so it cannot predict anything useful. Real models do not memorize this crudely, but most of them can fit the rows they were trained on more closely than they will fit new rows, so their score on those rows is too optimistic.

  • Rows it learned from
  • a score here can look perfect
  • Model
  • Rows it has never seen
  • the score that matters

New examples do not exist yet when you build the model, so you borrow some from the past. You hide part of your table before training, and the model never learns from it. Those held-out rows play the role of the future: the model's score on them estimates how it will do on examples it has never seen.

True or false?

If a model is right on 99% of the rows it was trained on, it will be right on about 99% of new rows.

False. A model can fit its own training rows much better than new ones; a lookup table that stores every row scores 100% on them and is useless on new rows. Only rows it never learned from can show how it does on new examples.

Held-out rows must be set aside before the model learns anything, not picked out afterwards.

True. Their value comes from the model never having seen them. A row the model learned from cannot act as a new example any more.

Training, validation and test: three parts, three jobs

Measuring is not the only thing you do with held-out rows. While building a model you also make choices: which kind of model to use, how large to let it grow, which columns to give it. Each choice is made by trying the options and keeping the one that scores best. That comparison needs held-out rows too, and it uses them up in a way that is easy to miss.

Suppose you try twenty settings and keep the one with the best score on some held-out rows. Part of why it won is that it happens to fit those particular rows well, including patterns that are in them only by chance. Its score on them is now a little too good, because you picked it for being good on exactly those rows. What you learned from those rows has leaked into your choice. So the rows you compare choices on cannot also give the final, honest number. The usual answer is to cut the table into three parts:

  • The training part is what the model learns from. It is usually the largest part, because more examples help the model find the pattern.
  • The validation part is for comparing choices. You train each option on the training part, score it on the validation part, and keep the best.
  • The test part is for one final measurement. You score the finished model on it once, at the end, and no choice is ever made by looking at it. That is what keeps its score an honest estimate for new data.
  • All rows
  • Training part the model learns
  • Validation part compare choices
  • Test part one final score
  • Model
  • All rows to Training part
  • All rows to Validation part
  • All rows to Test part
  • Training part to Model: learn from
  • Model to Validation part: score each choice
  • Model to Test part: score once, at the end
PartIts jobHow often it is scoredMay it decide a choice?
Trainingthe model learns from itnot used to judge the modelno
Validationcompare options and pick oneas often as you likeyes, that is its job
Testthe final, honest estimateonce, at the very endnever

A common choice is 60% of the rows for training, 20% for validation and 20% for test. The exact shares are a trade-off: every row held out is a row the model cannot learn from, and a small held-out part gives a score that depends a lot on which rows happened to land in it.

The rule for the test part is strict. The model never learns from it, and you never change anything because of its score. If you look at the test score, dislike it and adjust the model, the test part has become a second validation part, and you no longer have an honest number. For the same reason the split comes first, before any other work on the data, so that nothing learned from the test rows can reach the model in some other way.

True or false?

Choosing the best of several settings by their test scores is fine, as long as the model never trained on the test rows.

False. Picking by test score makes the test rows decide a choice, so the winner's test score is too optimistic. Choices are made on the validation part; the test part is scored once at the end.

Scoring many options on the validation part makes the best validation score slightly too optimistic.

True. The winner was picked partly for fitting those validation rows well. That is exactly why a separate test part, untouched by any choice, gives the final number.

Making three parts with train_test_split

In scikit-learn the function train_test_split from sklearn.model_selection cuts a table into two random parts. It shuffles the rows, then puts one share into the first part and the rest into the second. Given the feature columns X and the label column y, it returns four pieces in this order: training features, test features, training labels, test labels. Each label stays with its own row of features, and a pandas table that goes in comes out as a pandas table.

One call gives two parts, so three parts take two calls. The first call holds out 20% of all rows as the test part. The second call splits the remaining 80% into training and validation. A validation share of 0.25 of what is left is 20% of all the rows, because \( 0.25 \times 80\% = 20\% \).

Two calls: 60% training, 20% validation, 20% test
from sklearn.model_selection import train_test_split

# First call: hold out 20% of all rows as the test part.
X_rest, X_test, y_rest, y_test = train_test_split(
    X, y, test_size=0.2, stratify=y, random_state=0
)

# Second call: split the other 80% into training and validation.
# 0.25 of the remaining 80% is 20% of all rows.
X_train, X_val, y_train, y_val = train_test_split(
    X_rest, y_rest, test_size=0.25, stratify=y_rest, random_state=0
)

test_size is the share that goes into the second part (if you give neither size, it is 0.25). The other two arguments, stratify and random_state, are not needed to make the call work, and by default they are off. They are what make the split fair and repeatable, and the next two sections explain each one.

Stratified splitting: the same share of each answer in every part

A random split is fair on average, but any one split can be unlucky. Take a small table of 20 customers in which 4 left (20%), and draw 5 of them at random as a held-out part. The part should hold one customer who left, but often it holds none, and sometimes two or more. A part with no one who left cannot tell you anything about how well the model finds them.

  • All 20 rows
  • 4 left: 20%
  • Stratified part
  • 1 of 5 left: 20%
  • An unlucky random part
  • 0 of 5 left: 0%

That unlucky draw is not rare: when 5 of these 20 rows are drawn at random, about 28% of the draws contain no one who left. Stratified splitting removes the luck. It splits each answer separately: the rows with answer "left" are divided in the requested shares, the rows with answer "stayed" are divided in the same shares, and the pieces are joined. Every part then holds close to the same share of each answer as the whole table. Close, not always exactly, because a part holds whole rows: 20% of 7 rows is not a whole number of rows.

It matters most when one answer is rare. If half the rows have each answer, a random part of a few hundred rows will land near half and half anyway. If only 5% of 1,000 rows have the rare answer, a random 100-row part should hold 5 of them but can easily hold 2 or 9, a share of 2% or 9% instead of 5%. Scores measured on such a part are then partly about luck. With stratification every part gets its 5%, so training, validation and test all describe the same problem.

In train_test_split stratification is off unless you ask for it. You pass the labels of the rows being split as stratify: stratify=y in the first call, stratify=y_rest in the second, since the second call splits only the remaining rows. Stratifying needs the rows shuffled, which is the default.

To see that it worked, count the answers in each part. The pandas method value_counts(normalize=True) on a label column lists each distinct answer with its share of the rows, the shares adding up to 1. Run it on y, y_train, y_val and y_test, and the shares should agree closely.

Check the share of each answer in every part
for name, labels in [("all", y), ("train", y_train), ("validation", y_val), ("test", y_test)]:
    print(name, labels.value_counts(normalize=True).round(3).to_dict())

Each line prints one part's name and a dictionary of answer and share, rounded to three decimals. With a stratified split the four dictionaries agree to about the second decimal; without it, the small parts can drift away from the whole.

True or false?

`train_test_split` keeps the share of each answer the same in both parts by default.

False. By default `stratify` is `None` and the split is purely random. You have to pass the labels, for example `stratify=y`.

Stratification matters more when 3% of the rows have one answer than when the answers are split half and half.

True. With a rare answer, a few rows more or less in a part change its share a lot, and a small part may hold almost none. Balanced answers barely move.

With stratification, every part has exactly the same share of each answer, to every decimal.

False. Parts hold whole rows, so the shares are kept approximately: as close as whole numbers of rows allow.

A random seed makes the split repeatable

The shuffle before a split comes from a random number generator. A computer's generator is not truly random: it computes a long sequence of numbers that look random, starting from a number called the seed. The same seed always produces the same sequence, so the same shuffle, so the same split.

In scikit-learn the seed is the argument random_state. Its default, None, takes the numbers from a shared generator that keeps moving, so every call and every run of the script gives a different split. Pass an integer, such as random_state=0, and the call gives the same split every time.

  • Split: random_state=0
  • Same shuffle
  • Same three parts
  • Model: random_state=0
  • Same model
  • Same scores
  • Split: random_state=0 to Same shuffle
  • Same shuffle to Same three parts
  • Same three parts to Same scores
  • Model: random_state=0 to Same model
  • Same model to Same scores

The split is the first step of everything that follows. Which rows land in training decides what the model learns, and which rows land in validation and test decides its scores. Without a seed, every run would print slightly different numbers, and you could not tell whether a change you made helped or whether the rows simply fell differently this time. With a seed, a number that changes between runs changed because of something you did.

Three points keep the seed honest:

  • The number itself has no meaning. Any integer from 0 to \( 2^{32} - 1 \) works; 0 and 42 are only popular choices. What matters is that it stays the same.
  • Every random step needs its own seed, not only the split. Some models and other tools also use random numbers, and each of them takes its own random_state. scikit-learn advises passing it to each one rather than setting one global seed at the top of the script.
  • A seed makes a result repeatable, not true. A different seed gives a different split and slightly different scores. Never try seeds until the scores look good: that is choosing by luck, just like choosing by the test score.

True or false?

Without `random_state`, `train_test_split` gives a different split each time the script runs.

True. The default `None` draws from a shared generator that keeps moving, so the shuffle, and with it the split, changes from run to run.

`random_state=42` gives a better split than `random_state=0`.

False. Any integer gives one fixed, equally random split. 42 is only a popular habit; the point is to keep the same seed, not to pick a special one.

Once the split has a seed, every result after it is repeatable, whatever else the script does.

False. Other random steps, such as some models, use random numbers of their own and need their own `random_state` too.