Intermediate: machine learning · Evaluating models · topic 27 of 62 · 30 min
Train, validation and test sets
Explanation
Why hold data back?
A student who memorises last year's question paper may score 100% on it and still fail a new paper. A model can do the same: it can memorise its training examples. The only fair test is on examples it never saw while learning. So before training, we put some data aside and do not touch it until the end.
The three sets
| Set | Used for | Typical share |
|---|---|---|
| Training | Fitting the model's weights | 60–80% |
| Validation | Choosing between models and settings (tuning) | 10–20% |
| Test | One final, honest estimate of performance | 10–20% |
If you tune settings by looking at the test score again and again, the test set slowly becomes part of training, and its score becomes optimistic. That is why the validation set exists. With small datasets, cross-validation (topic 6) replaces a fixed validation set.
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y
)Shuffle, but not for time
Random splitting assumes the rows are independent. For time series, like daily sales or stock prices, a random split lets the model "see the future": it trains on next week and is tested on last week. For time data, split by time instead: train on the past (for example, January to September) and test on the later period (October to December). This matches how the model will be used.
Data leakage
Leakage means the training data contains information that would not be available at prediction time, or that comes from the test set. The model then scores brilliantly in testing and fails in real use. It is one of the most common and expensive mistakes in data science.
- Target leakage: a feature is a consequence of the label. Using "refund_issued" to predict "complaint_filed" is cheating.
- Preprocessing leakage: scaling or filling missing values using statistics from ALL the data, including the test set. Fix: fit the scaler on the training set only, then apply it to the test set.
- Duplicate leakage: the same customer or the same photo appears in both training and test sets. Fix: split by customer id (group split).
- Time leakage: using future information, such as next month's average, as a feature.
Common mistakes
- No fixed random_state, so every run gives a different split and nobody can reproduce results.
- Not stratifying a rare class, so the test set ends up with almost no positive cases.
- Peeking at the test set during EDA and feature design. Fix: split early and explore only the training data.
- A test score that is "too good to be true". Treat it as a leakage alarm, not a celebration.
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Train, validation and test sets · 1/7
A model must be judged on data it has never seen. So we split the data first.
Prefer a video by a teacher? Find free videos on “train validation test split data leakage machine learning explained” on YouTube ↗
In real life: A churn model that was too good
A telecom analyst builds a model to predict which customers will leave and gets 99% accuracy. Suspicious, she checks the features and finds "days_since_port_out_request": a customer only has a value there if they have already asked to switch to another network. The feature leaked the answer. After removing it and splitting by time, the honest accuracy is 81%, which still beats the baseline and is what the business can actually expect.
Practice (0/3 done)
Write split_indices(n, test_frac, seed) that shuffles the indices 0..n−1 with random.Random(seed).shuffle, puts the FIRST int(n × test_frac) shuffled indices in the test set and the rest in the training set, and returns (train, test) with each list sorted. The same seed must always give the same split.
For time-series data, write time_split(dates, cutoff) where dates are strings like "2025-03-14" (ISO format, so text comparison works). Return (train_idx, test_idx): indices with a date BEFORE the cutoff go to train, the rest (on or after the cutoff) to test, both in original order.
A hospital wants to predict whether a patient will be readmitted within 30 days. The columns are: age, diagnosis, length_of_stay, number_of_previous_visits, discharge_summary_word_count, readmission_ward_number. Which column leaks the answer, how would you split the data, and why?
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Confusion matrix, accuracy, precision, recall and F1Evaluating models · same module
- Thresholds, ROC-AUC and imbalanced classesEvaluating models · same module
- Regression metrics: MAE, MSE, RMSE and R²Evaluating models · same module
- Feature selection, leakage and pipelinesClustering, dimensionality reduction and feature engineering
- Scaling and transforming numbersClustering, dimensionality reduction and feature engineering
- Project: quiz game with negative markingPython Programming · Projects: put it all together
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
What is the test set for?
Answer: One final, honest estimate on unseen data
Use it once at the end; tuning belongs to validation.
Why use stratify=y when only 3% of rows are positive?
Answer: So both sets keep about 3% positives instead of the test set having almost none by chance
Stratifying keeps class shares the same in each split.
You predict next month's sales. Which split is right?
Answer: Train on earlier months, test on later months
Time order must be respected so the model never sees the future.
You scale features using the mean and standard deviation of the WHOLE dataset before splitting. What is the problem?
Answer: Test-set information leaks into training
Fit preprocessing on the training set only, then apply it to the test set.
A model scores 99.8% on the test set for a hard real-world task. What should you do first?
Answer: Look for leakage
Scores that are too good usually mean the answer leaked into the features.
You pick the top 20 features using the whole dataset, then run cross-validation. What is wrong?Related
Answer: Feature selection saw the validation folds, so the CV score is optimistic
Selection is part of training and must happen inside the folds.
In 5-fold cross-validation, how many times is the model trained?Related
Which model does NOT need feature scaling?Related
Answer: Random forest
Trees split one feature at a time on thresholds.
With +4 and -1 marking, what is the score for 10 correct, 5 wrong and 5 skipped?Related
Answer: 35
10 × 4 = 40, minus 5 × 1 = 5, gives 35. Skipped questions add nothing.
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 5 more topics in “Evaluating models” before its exam: Confusion matrix, accuracy, precision, recall and F1, Thresholds, ROC-AUC and imbalanced classes, Regression metrics: MAE, MSE, RMSE and R², Overfitting, underfitting and regularisation, Cross-validation and tuning hyperparameters.
- Module 6 exam: Evaluating models · 12 questions · 25 min, without help. 6 topics of this module still to finish first.
- Then the next module, k-NN, decision trees and ensembles. 62 topics left in the course before the final exam.