Sub topic 5
Setting aside a test set
This chapter covers the first modeling decision in the project: which rows the model may learn from and which rows it may never see until the end. It assumes you can load the California housing data into a pandas DataFrame, as in the previous chapters, and that you know what features and a target are. Basic familiarity with NumPy-style indexing helps.
Why a test set exists
A model is useful only if it works on houses it has not seen. If you score a model on the same rows it was trained on, the score tells you how well it memorized those rows. Flexible models such as gradient boosting can memorize a lot, so a training score can look excellent while performance on new houses is poor.
The fix is to hold out part of the data before any modeling starts. The held-out part is the test set. It plays the role of future data. You use it once, at the end, to estimate how the finished model will behave on new houses.
This gives two groups of rows with two different jobs:
- Training set: everything you look at, fit, compare and tune on.
- Test set: locked away until the final evaluation chapter.
Splitting with train_test_split
scikit-learn provides train_test_split for this. You pass it the features and the target, and it returns four objects. The order matters: training features, test features, training target, test target.
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
df = fetch_california_housing(as_frame=True).frame
X = df.drop(columns="MedHouseVal")
y = df["MedHouseVal"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
print("Full: ", X.shape)
print("Train: ", X_train.shape)
print("Test: ", X_test.shape)
print("Same row order in X and y:", (X_train.index == y_train.index).all())The dataset has 20,640 rows, so test_size=0.2 gives 16,512 training rows and 4,128 test rows. The last line confirms that features and target were split together. train_test_split shuffles one shared set of row positions and applies it to every array you pass, so each row of X_train still lines up with its value in y_train. Because the inputs are pandas objects, the original index labels are kept, which lets you trace any row back to the full DataFrame.
The arguments that matter
| Argument | What it does | Practical advice |
|---|---|---|
| `test_size` | Fraction (or row count) held out | 0.2 is a common default. Use less when data is plentiful and more when you need a precise final estimate. |
| `random_state` | Seed for the shuffle | Always set it. Without it, every run produces a different split. |
| `shuffle` | Shuffle rows before splitting (default `True`) | Keep it on for independent rows such as houses. Turn it off only for ordered data, discussed below. |
| `stratify` | Keep the proportions of a label the same in both parts | Needs discrete labels. Useful for classification, and for regression after binning a variable. |
Choosing the test size
There is a trade-off. A larger test set gives a more stable final estimate. A smaller training set gives a model with less to learn from. With 20,640 rows, 4,128 test rows is enough for a stable estimate. On a dataset with 500 rows, an 80/20 split leaves only 100 test rows, and the final score would be noisy. In that case you rely more on cross-validation, which later chapters cover.
Why fix the seed
The split is random, so a different seed means different houses in each part. That changes every number you compute afterwards. The next snippet shows how much the test set itself varies between seeds.
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
df = fetch_california_housing(as_frame=True).frame
X = df.drop(columns="MedHouseVal")
y = df["MedHouseVal"]
for seed in range(5):
_, _, _, y_test = train_test_split(X, y, test_size=0.2, random_state=seed)
print(f"seed={seed} mean test target = {y_test.mean():.4f}")The five means differ slightly. If you compared two models on different seeds, you could not tell whether a score difference came from the models or from the luck of the split. A fixed random_state=42 keeps the comparison fair and makes the project reproducible. The value 42 has no special meaning. What matters is that you pick one and keep it.
Checking that the split is representative
A random split is usually representative when there are thousands of rows, but you can verify it cheaply by comparing the target distribution in each part.
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
df = fetch_california_housing(as_frame=True).frame
X = df.drop(columns="MedHouseVal")
y = df["MedHouseVal"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
summary = {"train": y_train.describe(), "test": y_test.describe()}
for name, stats in summary.items():
print(name)
print(stats.round(3))
print()The count, mean, spread and quartiles should be close. If they differ a lot, something is wrong with the split, or the dataset is small enough that chance matters.
Stratifying a regression split
stratify expects class labels, and the house value is continuous. If you want both parts to contain the same mix of low-, middle- and high-income areas, you can bin one important variable and stratify on the bins. Median income is a natural choice, because it is strongly related to house value.
import pandas as pd
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
df = fetch_california_housing(as_frame=True).frame
X = df.drop(columns="MedHouseVal")
y = df["MedHouseVal"]
income_bins = pd.qcut(X["MedInc"], q=5, labels=False)
X_train_s, X_test_s, y_train_s, y_test_s = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=income_bins
)
print("Train income-bin shares:")
print(income_bins.loc[X_train_s.index].value_counts(normalize=True).sort_index())
print("Test income-bin shares:")
print(income_bins.loc[X_test_s.index].value_counts(normalize=True).sort_index())Each bin holds about 20% of the rows in both parts. The bins exist only to guide the split. They are not added to X as a feature. This project continues with the plain random split from the previous section, because with 20,640 rows the two approaches give similar results. Stratifying matters most when the dataset is small or when an important group is rare.
When a random split is the wrong choice
train_test_split assumes that rows are independent and that future data looks like past data. Check both assumptions on your own projects.
- Time-ordered data. If you predict next month's sales from earlier months, a shuffled split lets the model train on the future. Split by date instead: train on the earlier rows and test on the later ones, with
shuffle=Falseor an explicit date cutoff. - Grouped rows. If one customer, one patient or one building appears in many rows, a random split puts some of their rows in training and others in test. The model then recognizes the group instead of generalizing. Use
GroupShuffleSplitorGroupKFoldso each group lands entirely on one side. - Duplicates. Exact duplicate rows can end up on both sides and inflate the score. Remove them before splitting.
The California housing rows are census block groups, which are areas rather than individual houses. They are close to independent for the purposes of this project. Neighboring areas are still similar to each other, so the test score is somewhat more optimistic than it would be for an entirely new region. Keep that in mind when you interpret the final result.
Common mistakes
- Transforming before splitting. Fitting a scaler or filling missing values on the whole DataFrame, then splitting, lets statistics from the test rows shape the training data. Split first. The next chapters explain this in detail as data leakage, and the pipeline chapter shows the safe pattern.
- Splitting more than once. Calling
train_test_splitagain later, with another seed or on a modified DataFrame, can move former test rows into training. Create the split once, near the top of the script, and reuse the four variables. - Splitting features and target separately. Two separate calls with
shuffle=Trueand no shared seed shuffle the rows differently, and the pairs no longer match. Always passXandyto the same call. - Looking at the test set while modeling. Plotting it, computing correlations on it, or checking scores "just once" during development all feed information from it back into your choices. Use cross-validation on the training set for every comparison.
- Reusing the test set repeatedly. Each time you evaluate on it and then change the model, the test set becomes part of the tuning. After many rounds, its score no longer estimates performance on new data.
What comes next
From here on, the variables X_train, y_train, X_test and y_test are fixed. The baseline model, the Ridge model, cross-validation and grid search all work with the training pair only. The test pair stays untouched until the final evaluation chapter.
Exercise
You split the housing data with traintestsplit(X, y, testsize=0.2) and no randomstate. Your Ridge model scores a cross-validated MAE of 0.53 today. Tomorrow you rerun the script and get 0.55, with no code changes. Give the likely cause, the fix, and why the fix matters for comparing two models.
Show answer
Without randomstate, each run shuffles the rows differently, so the training and test sets contain different houses and every downstream score shifts. The fix is to pass a fixed integer, for example randomstate=42, so the split is identical on every run. This matters for comparisons because a score difference between two models is only meaningful if both were trained and evaluated on the same data. With a changing split you cannot tell whether a difference comes from the models or from the luck of the split.
Exercise
A colleague scales all 20,640 rows with StandardScaler and then calls traintestsplit on the scaled data. What goes wrong, and what is the correct order?
Show answer
The scaler computed its mean and standard deviation using test rows, so information about the test set influenced the training features. This is data leakage and makes the test score slightly optimistic. The correct order is to split first, fit the scaler on the training rows only, and then apply that fitted scaler to the test rows. Putting the scaler and the model in a pipeline does this automatically.