Sub topic 3
Splitting data into training and test sets
This chapter assumes you know basic Python, can read feature arrays and label arrays, and know that a supervised model learns a mapping from features to labels. It covers the simplest holdout method: set some rows aside before training, then use them to check the model.
What the split does
A model's score on the rows it trained on says little about new data. A flexible model can memorize those rows. To get an honest estimate, you divide the labeled data into two parts:
- The training set is the part the model learns from.
- The test set is the part you hide until you want to measure performance. The model never sees it during fitting.
The test score then estimates how the model will do on rows it has never seen.
Using train_test_split
scikit-learn provides train_test_split. It shuffles the rows, then cuts them into two parts. It returns four objects in a fixed order: training features, test features, training labels, test labels.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42
)
print(X_train.shape, X_test.shape)This prints (455, 30) (114, 30). The dataset has 569 rows, so test_size=0.2 puts about 20% of them in the test set.
Three arguments matter here:
test_size=0.2sets the fraction of rows held out. You can also pass an integer to set an exact row count.random_state=42fixes the shuffle, so every run produces the same split. Without it, your score changes from run to run and you cannot tell whether a code change helped.stratify=ykeeps the class proportions the same in both parts. This matters most when one class is rare, and a later chapter covers it in detail.
Working model
The split is a one-time decision about which rows count as evidence. Everything you do afterward follows from it:
- Split first, before any other step that looks at the data.
- Fit the model on
X_trainandy_trainonly. - Predict on
X_testand compare againsty_test.
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
model.fit(X_train, y_train)
print("Train accuracy:", model.score(X_train, y_train))
print("Test accuracy:", model.score(X_test, y_test))Train accuracy is usually equal to or higher than test accuracy. A large gap suggests the model fits noise in the training rows. The pipeline here keeps the scaler's statistics from coming from the test rows, which a later chapter explains.
Common errors
- Splitting after preprocessing. Scaling, imputing, or selecting features on the full dataset lets test-set information influence training. Split first.
- Unpacking in the wrong order. The return order is
X_train, X_test, y_train, y_test. WritingX_train, y_train, X_test, y_testruns without error but trains on the wrong arrays, or fails with a confusing shape error. - Splitting features and labels separately. Calling
train_test_splitonce onXand once onyonly stays aligned if both calls use the samerandom_state. Pass both arrays in a single call. - Re-splitting until the score looks good. Each new seed gives a different test set. Picking the seed with the best score makes the result optimistic.
- Reusing the test set for tuning. If you adjust the model after each test score, the test set becomes part of training in effect. The validation set, covered later, exists to prevent this.
Exercise
You call traintestsplit(X, y, testsize=0.3, randomstate=0) on a dataset of 1,000 rows. How many rows are in the training set, and what changes if you remove random_state?
Show answer
The training set has 700 rows and the test set has 300. Without random_state, the rows are shuffled differently on each run, so the membership of both sets, and therefore your scores, can change between runs.