Sub topic 5
Setting aside a test set
This chapter assumes you can load the California housing data into a DataFrame, as in the previous chapters, and that you know what features and a target are. It covers the first modeling step: holding back a portion of the data so you can judge the final model honestly.
Why hold data back
A model fitted to data will always look good on that same data. A flexible model can memorize its training rows and still fail on new houses. To estimate how it behaves on houses it has never seen, you keep some rows out of training entirely. These held-out rows are the test set. You touch them once, at the very end of the project.
The rest of the data is the training set. You use it for every choice: scaling, model selection, cross-validation and tuning.
Splitting with scikit-learn
First separate the features from the target. Then call train_test_split, which shuffles the rows and cuts them into two parts.
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
housing = fetch_california_housing(as_frame=True)
df = housing.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("Train:", X_train.shape, y_train.shape)
print("Test: ", X_test.shape, y_test.shape)The dataset has 20,640 rows, so the output shows 16,512 training rows and 4,128 test rows. The two parameters you set matter:
test_size=0.2puts 20% of the rows in the test set. A common range is 10% to 30%. A larger test set gives a steadier final estimate but leaves less data for training.random_state=42fixes the shuffle. Without it, every run produces a different split, and your scores change for reasons unrelated to your model.
The number 42 has no special meaning. Any fixed integer works, and you should keep it the same throughout the project.
What the split looks like
Common errors
Most split mistakes come from a few habits.
| Mistake | Why it hurts | Fix |
|---|---|---|
| Omitting `random_state` | Results change on every run, so you cannot compare models | Set it once and reuse it |
| Exploring or scaling the full dataset before splitting | Test information influences training decisions | Split first, then work on the training set only |
| Re-splitting after a bad test score | You are now tuning to the test set | Keep the split fixed |
| Splitting `X` and `y` in separate calls | Rows no longer match their targets | Pass both to one `train_test_split` call |
| Checking the test score after every change | The test set becomes part of model selection | Use cross-validation on the training set instead |
The next chapters build on this: you will see how information can leak across the split, and how cross-validation lets you compare models without spending the test set.
Check the split
A quick sanity check confirms that the split is sensible. The target should have a similar distribution in both parts.
print(y_train.describe())
print(y_test.describe())The means and standard deviations should be close. If they differ a lot, the split may be unlucky, which is rare with this many rows.
Exercise
You split the data, train a model, and get a poor test score. You change the random_state to 7 and re-split, hoping for a better score. What is wrong with this approach?
Show answer
The test set is now being used to make a decision. Trying different splits until the test score looks good selects the split that flatters the model, so the final score no longer estimates performance on new data. Keep the split fixed and improve the model using cross-validation on the training set.
Exercise
With 20,640 rows and test_size=0.25, how many rows go to the training set?
Show answer
15,480. The test set gets 0.25 × 20,640 = 5,160 rows, and the training set gets the remaining 15,480.