Sub topic 5
Holding out data with train_test_split
This chapter assumes you can read NumPy array shapes and know what fit, predict and score do on an estimator. It covers why a model needs data it never trained on, how train_test_split produces that data, and which arguments change the result.
Why hold out data
A model's accuracy on the rows it trained on says little about how it will behave on new rows. A flexible model can memorize its training set and score near-perfectly there while failing on anything else. To estimate performance on unseen data, you set some rows aside before training and use them only for a final measurement.
The held-out part is the test set. The remaining rows are the training set. sklearn.model_selection.train_test_split makes this division in one call.
The basic call
train_test_split takes any number of arrays that have the same number of rows. It returns two pieces for each array, in the order train, test.
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)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
print(X_train.shape, X_test.shape) # (112, 4) (38, 4)
print(y_train.shape, y_test.shape) # (112,) (38,)
print(np.array_equal(
X_train, train_test_split(X, y, random_state=0)[0]
)) # TrueThe output order is the most common source of confusion. With input (X, y) you get X_train, X_test, y_train, y_test, not X_train, y_train, X_test, y_test. If you swap two names, you will usually get a shape error at fit, but when X and y happen to have compatible shapes you can get a silently wrong model.
With no size arguments, the test set gets 25% of the rows. Iris has 150 rows, so the test set is 38 rows. The function rounds the test size up and the train size down.
The arguments that matter
| Argument | Default | What it does |
|---|---|---|
| `test_size` | 0.25 if `train_size` is also unset | A float is a fraction of rows. An int is an absolute row count. |
| `train_size` | complement of `test_size` | Same meaning, for the training side. You rarely need both. |
| `random_state` | `None` | Seed for the shuffle. An int makes the split repeatable. |
| `shuffle` | `True` | Whether to shuffle rows before splitting. |
| `stratify` | `None` | An array of labels. The split keeps their class proportions in both parts. |
Sizes
A float between 0 and 1 is a proportion. An integer is a number of rows. Setting test_size=0.2 and test_size=30 on 150 rows gives a test set of 30 rows either way. Giving a size that leaves no rows on one side raises a ValueError.
Repeatability with random_state
Without random_state, each run produces a different split, so your score changes from run to run. Pass an integer while developing so that results can be compared and bugs reproduced. The specific integer does not matter, but you should not tune it to get a flattering score. A score that depends on which seed you picked is a sign that the test set is small or noisy.
Stratification
A random split can distort class proportions, especially when the data is imbalanced or small. If 20% of your rows are positives, a random 20-row test set may contain two positives or eight. Passing stratify=y forces both parts to keep the original proportions as closely as possible.
import numpy as np
from sklearn.model_selection import train_test_split
y = np.array([0] * 80 + [1] * 20)
X = np.arange(200).reshape(100, 2)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=0, stratify=y
)
print(np.bincount(y_train)) # [64 16]
print(np.bincount(y_test)) # [16 4]Both parts are 80% zeros and 20% ones. Stratification applies to classification labels. For a continuous regression target, you would have to bin the target first and stratify on the bins.
Splitting DataFrames and several arrays
train_test_split accepts pandas objects, NumPy arrays, lists and sparse matrices. A DataFrame comes back as a DataFrame and a Series as a Series, with the original index labels attached to the surviving rows.
import pandas as pd
from sklearn.model_selection import train_test_split
df = pd.DataFrame({
"age": [22, 35, 47, 52, 28, 41, 60, 33],
"income": [30, 52, 61, 70, 38, 58, 75, 49],
"bought": [0, 1, 1, 0, 0, 1, 1, 0],
})
X = df[["age", "income"]]
y = df["bought"]
weights = pd.Series([1, 1, 2, 1, 1, 2, 1, 1], name="weight")
X_train, X_test, y_train, y_test, w_train, w_test = train_test_split(
X, y, weights, test_size=0.25, random_state=1
)
print(type(X_train).__name__, X_train.shape) # DataFrame (6, 2)
print(len(y_test), len(w_test)) # 2 2
print(X_train.index.equals(y_train.index)) # TrueAll arrays are shuffled with the same permutation, so row i of X_train still matches row i of y_train and w_train. This alignment is the reason to pass everything to one call. If you split X and y in two separate calls without the same random_state, the rows no longer correspond.
When not to shuffle
Shuffling assumes rows are independent and identically distributed. For time series, that assumption fails. If you shuffle, the model trains on Tuesday and Thursday and is tested on Wednesday, which tells you nothing about forecasting next week. Use shuffle=False to take the first part as training and the last part as test.
import numpy as np
from sklearn.model_selection import train_test_split
X = np.arange(10).reshape(-1, 1)
y = np.arange(10)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, shuffle=False
)
print(X_train.ravel()) # [0 1 2 3 4 5 6]
print(X_test.ravel()) # [7 8 9]stratify cannot be combined with shuffle=False. For repeated evaluation of time-ordered data, TimeSeriesSplit is the better tool.
Common errors
- Splitting after preprocessing. If you scale or encode the full dataset and then split, statistics from the test rows have influenced the training data. Split first, then fit transformers on the training part only. The data leakage chapter covers this in detail.
- Reusing the test set for decisions. If you compare ten models on the test set and keep the best, the test score is now optimistic. Choose models with cross-validation on the training set, and look at the test set once at the end.
- Forgetting
random_statein comparisons. Two models evaluated on different random splits are not comparable. Fix the seed, or better, evaluate both on the same split. - A test set too small to trust. With 20 test rows, one prediction changes accuracy by 5 points. Check the size of the test set before reading much into small differences.
- Mismatched row counts. Arrays of different lengths raise
ValueError: Found input variables with inconsistent numbers of samples. CheckX.shape[0] == y.shape[0].
A complete example
The following script uses the whole workflow from this chapter: a stratified, seeded split, then fit and score on the held-out part.
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
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
)
model = LogisticRegression(max_iter=200)
model.fit(X_train, y_train)
print(f"train accuracy: {model.score(X_train, y_train):.3f}")
print(f"test accuracy: {model.score(X_test, y_test):.3f}")Train accuracy is usually equal to or higher than test accuracy. A large gap, such as 100% on training and 70% on test, indicates overfitting. Similar low scores on both indicate underfitting.
Exercise
You have a dataset with 1,000 rows where only 30 rows belong to the positive class. You call train_test_split(X, y, test_size=0.2, random_state=42) and the test set ends up with 9 positives, while another colleague's run ends up with 4. What argument would make the splits consistent in class balance, and roughly how many positives should each test set contain?
Show answer
Pass stratify=y. The test set has 200 rows, and 3% of them are positive, so each stratified split puts about 6 positives in the test set (and 24 in the training set).
Exercise
A teammate writes X_train, y_train, X_test, y_test = train_test_split(X, y) and then calls model.fit(X_train, y_train). What goes wrong, and what is the correct unpacking order?
Show answer
The function returns X_train, X_test, y_train, y_test. In the teammate's code, y_train actually holds X_test and X_test holds y_train, so fit receives a feature matrix as its labels (usually raising a shape or label error). The correct line is X_train, X_test, y_train, y_test = train_test_split(X, y).