A model that only ever sees the data it learned from can look perfect while being useless on anything new. To find out how well it really works, you hide part of your data during training and test the model on it afterwards. This is the train-test split, the first step of almost every machine learning project. This lesson shows how to do it with scikit-learn and why details such as stratify and random_state matter.
In this lesson you will learn
- Why a model must be tested on unseen data
- Splitting data with
train_test_split - Keeping class balance with
stratify - Making results repeatable with
random_state - When you also need a validation set
Features, Labels and the Split
In supervised learning the data has two parts. Features, written X, are the inputs, such as the four flower measurements in the classic Iris dataset. Labels, written y, are the answers to predict, such as the species. The split keeps rows together, so each flower’s measurements stay with its species.
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
X, y = load_iris(return_X_y=True)
print("All data:", X.shape, y.shape)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y
)
print("Training set:", X_train.shape)
print("Test set: ", X_test.shape)
# stratify=y keeps the same share of each class in both parts
import numpy as np
print("Class counts in train:", np.bincount(y_train))
print("Class counts in test: ", np.bincount(y_test))
Output
All data: (150, 4) (150,)
Training set: (120, 4)
Test set: (30, 4)
Class counts in train: [40 40 40]
Class counts in test: [10 10 10]
test_size=0.2sends 20% of the rows to the test set: 30 of the 150 flowers.- The rows are shuffled before splitting. Without shuffling, data sorted by class could leave one species entirely out of the training set.
stratify=ykeeps the same proportion of each class in both parts: exactly 40/40/40 and 10/10/10 here. This matters most when one class is rare.random_state=42fixes the shuffle, so you get the same split every run. Any number works; what matters is that it stays the same while you compare models.
Training and Testing a Model
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y
)
model = DecisionTreeClassifier(random_state=0)
model.fit(X_train, y_train)
print("Accuracy on training data:", model.score(X_train, y_train))
print("Accuracy on test data: ", round(model.score(X_test, y_test), 3))
# Validation set: split the training part again
X_tr, X_val, y_tr, y_val = train_test_split(
X_train, y_train, test_size=0.25, random_state=42, stratify=y_train
)
print("Train / validation / test sizes:", len(X_tr), len(X_val), len(X_test))
Output
Accuracy on training data: 1.0
Accuracy on test data: 0.967
Train / validation / test sizes: 90 30 30
- Every scikit-learn model follows the same pattern: create it, call
fit(X_train, y_train)to learn, thenpredict()orscore()on new data. - The tree scores 100% on its own training data, which proves little: it may simply have memorised it. The test score, 96.7%, is the honest estimate of performance on new flowers.
- A big gap between training and test scores is the warning sign of overfitting.
- When you try many models or settings, you need a third part, the validation set, for choosing between them. The test set is then used only once, at the very end. Splitting the training part again, as shown, gives a 60/20/20 split.
How Big Should the Test Set Be?
| Dataset size | Typical split | Note |
|---|---|---|
| A few hundred rows | 70/30 or 80/20 | Prefer cross-validation for model choice |
| Thousands of rows | 80/20 | The common default |
| Millions of rows | 98/1/1 | 1% is already a large test set |
Data Leakage
Data leakage happens when information from the test set sneaks into training, giving scores that are too good to be true. Classic causes are scaling or filling missing values using the whole dataset before splitting, and having the same customer or patient in both parts. Always split first, then fit any preprocessing on the training part only. Pipelines make this automatic.
Time-based data, such as daily sales, should not be shuffled at all. Train on the past and test on the most recent period, because that is how the model will be used.
Common Mistakes
- Reporting training accuracy as if it showed real-world performance.
- Tuning on the test set by checking it after every change, which quietly turns it into training data.
- Forgetting
stratifyon imbalanced data, leaving very few rare cases in the test set. - Preprocessing before splitting, which leaks test information.
Practice Exercises
Exercise 1. Split the Iris data 70/30 with stratification and print the test-set size.
Show answer
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=0, stratify=y
)
print(len(X_test)) # 45
Exercise 2. Run the split with three different random_state values and compare the test accuracy. Why does it change?
Show answer
Each value produces a different set of 30 test flowers. With such a small test set, a single hard flower moves accuracy by more than 3 percentage points. That variation is why cross-validation, which averages over several splits, gives a more reliable estimate.
Frequently Asked Questions
What does random_state=42 mean?
It is just a seed for the random shuffle. The number 42 is a popular joke from a science-fiction novel and has no special effect; any fixed integer makes the split repeatable.
What is the difference between a validation set and a test set?
The validation set is used repeatedly while you choose models and settings. The test set is used once, at the end, to report the final performance on truly unseen data.
Summary
- Always measure a model on data it did not learn from.
train_test_splitshuffles and splits; usestratifyfor classification andrandom_statefor repeatability.- Use a validation set or cross-validation for choices, and the test set once at the end.
- Split before any preprocessing to avoid data leakage.
Next: Linear Regression.
