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 basic NumPy shapes. Here you will learn why a model needs data it never trained on, how train_test_split creates that data, and which options change the split in ways that matter.
Why a model needs held-out data
A fitted model can be scored on the rows it learned from, but that score is optimistic. Ordinary least squares picks coefficients that minimize error on the training rows. The error there says little about how the model will do on new rows.
A held-out test set fixes this. You set some rows aside, fit on the rest, and score on the rows the model has not seen. That score estimates how the model will behave in use. It is an estimate, not a guarantee, and it is only honest if the test rows play no part in fitting.
The basic call
train_test_split takes any number of arrays with the same first dimension. It shuffles the row indices, cuts them into two groups, and returns two pieces for each input array: train first, then test.
import numpy as np
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)
print(y_train.shape, y_test.shape)This prints (150, 1) (50, 1) and then (150,) (50,). The order of the returned values is X_train, X_test, y_train, y_test. Mixing up this order is a common bug, and it often raises no error when the shapes happen to match.
Rows stay aligned across the arrays. Row i of X_test is paired with row i of y_test. You can also pass a DataFrame and a Series. The outputs keep their pandas type and their original index labels, which helps when you trace a bad prediction back to its source row.
Choosing the size
You control the sizes with test_size or train_size. Each accepts a float (a fraction) or an integer (a row count).
| Argument | Meaning | Example |
|---|---|---|
| `test_size=0.25` | Fraction of rows in the test set | 50 of 200 rows |
| `test_size=40` | Exact number of test rows | 40 rows |
| `train_size=0.8` | Fraction of rows in the training set | 160 of 200 rows |
| neither given | Test fraction defaults to 0.25 | 50 of 200 rows |
If you give only one, the other is the complement. When a fraction does not divide evenly, scikit-learn rounds the test size up and gives the training set the remainder.
There is no universal best ratio. A smaller test set leaves more data for fitting but makes the test score noisier. With 50 test rows, one extreme row can move RMSE noticeably. Common choices are 0.2 to 0.3. With very small datasets, a single split is unreliable, and cross-validation (a later chapter) is the better tool.
Reproducibility and split variance
Without random_state, every call shuffles differently, so your scores change between runs. Setting an integer makes the split repeatable.
The split itself is a source of variation. The next example scores the same model on five different splits of the diabetes dataset.
from sklearn.datasets import load_diabetes
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
X, y = load_diabetes(return_X_y=True)
for seed in range(5):
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=seed
)
model = LinearRegression().fit(X_train, y_train)
print(seed, round(model.score(X_test, y_test), 3))The five R-squared values will differ, sometimes by several hundredths. Nothing about the model changed. Only the rows in the test set changed. When you compare two models, use the same random_state for both. Even then, treat a small gap between them as possibly noise.
Split before you preprocess
Any step that learns from data counts as fitting. StandardScaler learns a mean and standard deviation. If you fit it on the full dataset and then split, statistics from the test rows have influenced the training features. This is data leakage. The effect is often small for a scaler, but the habit is risky because it grows worse with steps like feature selection or imputation.
The correct order is to split first, fit the scaler on the training rows only, and then apply it to both parts.
from sklearn.datasets import load_diabetes
from sklearn.linear_model import Ridge
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
X, y = load_diabetes(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=0
)
scaler = StandardScaler()
X_train_s = scaler.fit_transform(X_train) # learns from train only
X_test_s = scaler.transform(X_test) # reuses train statistics
model = Ridge(alpha=1.0).fit(X_train_s, y_train)
print("test R2:", model.score(X_test_s, y_test))Note transform on the test set, not fit_transform. Calling fit_transform on X_test would fit a second scaler on test data, so train and test features would be on different scales. A Pipeline does this bookkeeping for you, and a later chapter covers it.
When a random shuffle is wrong
Shuffling assumes that rows are independent and that the future looks like the past in distribution. Several situations break that assumption.
Time-ordered data
If rows are ordered in time and you want to predict future values, a shuffled split lets the model train on rows that come after some test rows. The score then looks better than real forecasting would be. Disable shuffling so the test set is the latest block of rows.
import numpy as np
from sklearn.model_selection import train_test_split
t = np.arange(100)
X = t.reshape(-1, 1)
y = 0.5 * t + np.random.default_rng(0).normal(0, 1.0, size=100)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, shuffle=False
)
print("train t:", X_train.min(), "to", X_train.max())
print("test t:", X_test.min(), "to", X_test.max())This prints training times 0 to 79 and test times 80 to 99. For repeated time-aware evaluation, look at TimeSeriesSplit.
Grouped rows
If several rows come from the same patient, house, or customer, a random split puts some of that entity's rows in training and others in test. The model can then recognize the entity instead of learning a general pattern. Use GroupShuffleSplit or GroupKFold so each group lands entirely on one side.
Stratifying a continuous target
The stratify argument keeps class proportions equal in both parts, but it needs discrete labels. A regression target is continuous, so passing it directly raises an error. A workaround is to bin the target into quantiles and stratify on the bins. This is useful when the target is skewed and a plain split might leave the test set without any large values.
import pandas as pd
from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split
X, y = load_diabetes(return_X_y=True)
bins = pd.qcut(y, q=5, labels=False)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=0, stratify=bins
)
print("train mean:", y_train.mean())
print("test mean:", y_test.mean())The bins are only used to guide the split. The model still trains on the raw y.
Common mistakes
- Fitting a scaler, encoder, or imputer before splitting.
- Evaluating on the training set and reporting that number as performance.
- Reusing the test set repeatedly to choose between models or settings. Each look at the test score leaks a little information. Tune with cross-validation on the training portion and score the test set once.
- Forgetting
random_state, then being unable to reproduce a result. - Splitting grouped or time-ordered data with a plain shuffle.
Exercise
You have 1,000 rows of monthly sales, ordered by date, and you want to forecast next month's sales with LinearRegression. A teammate calls traintestsplit(X, y, testsize=0.2, randomstate=0) and reports a high R-squared. Name the problem, and give the call you would use instead along with the sizes of the resulting sets.
Show answer
The default shuffle mixes past and future rows, so the model trains on months that come after some test months. This makes the score look better than a real forecast would be. Use traintestsplit(X, y, test_size=0.2, shuffle=False), which gives 800 training rows (the earliest months) and 200 test rows (the latest months). For several time-aware evaluations, TimeSeriesSplit is another option.
Exercise
A scaler is fit with fittransform on the full X, and then traintest_split is called. Why is this a problem, and what is the correct order of operations?
Show answer
The scaler's mean and standard deviation include information from the test rows, so the test set has influenced the training features (data leakage). Split first, call fittransform on Xtrain only, and call transform on X_test using the training statistics.