Sub topic 5
Holding out data with train_test_split
This chapter assumes you can fit a LinearRegression and call predict, and that you know NumPy array shapes. By the end you will split data correctly and understand why the split matters.
Why hold out data
A model fitted on a dataset will usually score better on that dataset than on new data. It has already seen the answers. To estimate how it will behave on unseen data, set aside part of your data before fitting. You never fit on this held-out part. You use it once, at the end, to measure error.
- Training set: the rows used by
fit. - Test set: the rows used only for evaluation.
The basic call
train_test_split shuffles the rows and returns four arrays in a fixed order: X_train, X_test, y_train, y_test.
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
rng = np.random.default_rng(0)
X = rng.uniform(0, 10, size=(200, 1))
y = 3.0 * X[:, 0] + 2.0 + rng.normal(0, 1.0, size=200)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0
)
print(X_train.shape, X_test.shape)
model = LinearRegression().fit(X_train, y_train)
print("train R2:", model.score(X_train, y_train))
print("test R2:", model.score(X_test, y_test))With 200 rows and test_size=0.25, the shapes are (150, 1) and (50, 1). Both R-squared values should be close here because the data is simple and the model matches it. On harder problems, a large gap between them signals overfitting.
The arguments that matter
| Argument | Effect |
|---|---|
| `test_size` | Fraction (0.25) or row count (50) for the test set. The default is 0.25 if you also omit `train_size`. |
| `random_state` | Fixes the shuffle so the split is reproducible. |
| `shuffle` | Defaults to `True`. Set it to `False` for ordered data such as time series. |
| `stratify` | Keeps class proportions equal in both parts. It is meant for classification labels, not continuous targets. |
Common errors
- Omitting
random_state. Every run gives a different split, so your metrics change and you cannot compare results between runs. - Fitting anything on the full data first. If you compute a mean, scale features, or select features before splitting, information from the test rows leaks into training. Split first, then fit every step on the training part only. The pipelines chapter shows how to enforce this.
- Evaluating repeatedly on the test set. If you tweak the model after each test score, the test set becomes part of your tuning and its score is optimistic. Tune with cross-validation on the training data and touch the test set once.
- Shuffling time-ordered data. Random splits let the model train on the future and predict the past. Use
shuffle=Falseor a time-aware splitter. - Swapping the return order. The order is
X_train, X_test, y_train, y_test, not train pair then test pair.
Exercise
You standardize all of X with StandardScaler, then call traintestsplit, then fit and score a model. Why is the test score unreliable, and what is the correct order?
Show answer
The scaler computed its mean and standard deviation using test rows, so test information leaked into training. Split first, fit the scaler on Xtrain only, then use that fitted scaler to transform both Xtrain and X_test.