Train/Test Split: Why Models Need Unseen Data
A model that has seen the answers can look perfect without being useful, the same way a student who memorized last year's exam may still fail this year's. To find out how a model will behave on new data, you must test it on data it never saw during training. That ability to do well on unseen data is called generalization.
The split
The simplest approach is a holdout split:
- Shuffle the samples so the order of the file does not matter (data is often sorted by date or by class).
- Keep most of them, often 70 to 80 percent, as the training set.
- Set the rest aside as the test set, and do not look at it until the end.
The model learns only from the training set. Its score on the test set is your estimate of real-world performance.
In plain Python
The example shuffles twenty sample IDs with a fixed seed and splits them 75/25. A seed makes the "random" shuffle repeatable, so you and our test suite get the same split every time. In scikit-learn the same job is done by train_test_split(X, y, test_size=0.25, random_state=42).
Expected output
train: [2, 3, 5, 6, 7, 10, 11, 12, 13, 14, 15, 16, 18, 19, 20] test: [1, 4, 8, 9, 17] sizes: 15 5 overlap: set()
The last line checks the most important property of a split: no sample appears on both sides.
Validation data
Most projects compare several models or settings, such as how many neighbors a k-NN model should use. If you choose the setting with the best test score, the test set has quietly become part of training, and its score is no longer an honest estimate. The fix is a third set:
- Training set: fit the model.
- Validation set: compare models and settings.
- Test set: one final check of the chosen model.
Cross-validation is a more data-efficient version: split the training data into k parts, train k times, each time validating on a different part, and average the scores.
Pitfalls
- Not shuffling data that is sorted by class, which can leave a class missing from training.
- Duplicates across the split, such as the same customer in both sets, which make the test too easy.
- Time order: when predicting the future, train on the past and test on later data instead of shuffling.
- Class balance: with rare classes, use a stratified split so both sets keep the same proportions.
Summary
- Judge a model on data it did not train on.
- Shuffle with a seed, then hold out a test set; never tune on it.
- Use a validation set or cross-validation to choose between models.
Quiz: Train, test and validation data