Sub topic 5
Holding out data with train_test_split
This chapter assumes you can build a feature matrix X with shape (n_samples, n_features) and a label vector y with shape (n_samples,). It also assumes you know the difference between classification and regression targets. Here you will learn how to hold back part of the data so you can measure how well a model handles samples it has never seen.
Why hold out data
A model can memorize its training samples. If you score it on those same samples, the result tells you nothing about new data. The fix is to split the data once, before any fitting. You train on one part and evaluate on the other, called the test set.
Calling train_test_split
train_test_split takes X and y and returns four arrays. The order is always X_train, X_test, y_train, y_test.
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0, stratify=y
)
print(X_train.shape, X_test.shape) # (112, 4) (38, 4)
print(y_train.shape, y_test.shape) # (112,) (38,)The function shuffles the rows and then cuts them. Rows of X and y stay aligned, so sample i in X_train still matches label i in y_train.
The main arguments
| Argument | Meaning |
|---|---|
| `test_size` | Fraction (such as `0.25`) or absolute count of samples in the test set. The default is `0.25` when `train_size` is also unset. |
| `train_size` | Fraction or count for the training set. Usually you set only one of the two sizes. |
| `random_state` | An integer seed. The same seed gives the same split on every run. |
| `shuffle` | Shuffle rows before splitting. The default is `True`. |
| `stratify` | An array of labels. The split keeps each class in the same proportion in both parts. |
Reproducibility and stratification
Without random_state, each run produces a different split, so scores change between runs. Set an integer while you develop so results can be compared.
With classification targets, a random split can leave a rare class underrepresented in the test set. Passing stratify=y avoids that. The Iris dataset has 50 samples per class, so a stratified 38-sample test set contains about 12 or 13 of each class.
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
X, y = load_iris(return_X_y=True)
_, _, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0, stratify=y
)
print(np.bincount(y_train)) # [37 38 37]
print(np.bincount(y_test)) # [13 12 13]Stratification applies to classification labels. Do not pass a continuous regression target as stratify.
Common errors
- Splitting after preprocessing. If you scale or encode the full dataset first, statistics from the test rows leak into training. Split first, then fit transformers on the training part only. A later chapter covers this in detail.
- Splitting
Xandyseparately. Two separate calls shuffle differently and break the row alignment. Pass both arrays in one call. - Reading too much into one split. A small test set gives a noisy score. Cross-validation, covered later, averages over several splits.
- Evaluating on the test set repeatedly while tuning. Each peek makes the test score less honest. Keep the test set for the final check.
- Ordered data with
shuffle=False. If rows are sorted by class or by time, an unshuffled split can put whole classes in only one part. Useshuffle=Falseonly when row order matters, such as time series.
Exercise
You call train_test_split(X, y, test_size=0.2) twice and get different test sets each time. Which argument fixes this, and what should you add if y is a classification label with a rare class?
Show answer
Set random_state to an integer, for example random_state=42, so the shuffle is repeatable. Add stratify=y so the rare class appears in both the training and test sets in the same proportion as in the full data.
Exercise
A colleague runs StandardScaler().fit_transform(X) on the whole dataset and then calls train_test_split. What is wrong with this order?
Show answer
The scaler computed its mean and variance using the test rows too, so information from the test set leaks into training. The split should come first, and the scaler should be fit on X_train only.