Sub topic 3
Splitting data into training and test sets
This chapter covers how to divide a labeled dataset into a training part and a test part with scikit-learn's train_test_split. It assumes you know basic Python, can work with arrays or tables of features and labels, and know that a supervised model learns a mapping from features to labels. The previous chapters explained why held-out data is needed. Here you will see the mechanics, what the function returns, and the mistakes that cause trouble.
What the split does
A split divides your rows into two groups that do not overlap:
- The training set is the data the model learns from. Every fitting step uses only these rows.
- The test set is the data you hold back. The model never sees it during fitting. You score the finished model on it to estimate how it will do on new data.
Each row keeps its features and its label together. A row is either in the training set or in the test set, never both.
The basic call
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)The dataset has 569 rows and 30 features. The call prints (455, 30) (114, 30).
Four details of this call matter:
- The return order is fixed. You get
X_train, X_test, y_train, y_test. The function returns a train/test pair for each array you pass in, in the order you passed them. Mixing up the names is a common bug, and it often runs without error. test_size=0.2means 20% of rows go to the test set. A float between 0 and 1 is a fraction. An integer is an exact row count.stratify=ykeeps class proportions the same in both parts. The details are covered in a later chapter. Here it is enough to know that it is optional and applies to classification labels.random_state=42fixes the shuffle. Without it, each run gives a different split. Reproducibility also has its own chapter.
How sizes are computed
You can give test_size, train_size, both, or neither.
| You pass | Result |
|---|---|
| Only `test_size` | Training set gets the remaining rows |
| Only `train_size` | Test set gets the remaining rows |
| Both | Both are used. They may sum to less than the dataset, and the unused rows are dropped |
| Neither | `test_size` defaults to 0.25 |
When a fraction does not divide evenly, the test size is rounded up and the training size is rounded down. With 569 rows and test_size=0.2, the exact test count is 113.8. It rounds up to 114, and the training set gets the other 455 rows.
If you set train_size and test_size as integers that add up to more than the number of rows, scikit-learn raises a ValueError. The same happens if the fractions add up to more than 1.
Splitting more than two arrays
train_test_split accepts any number of arrays or tables, as long as they all have the same number of rows. Each one is split with the same row assignment. This is how you keep extra per-row information aligned with the features:
import numpy as np
from sklearn.model_selection import train_test_split
X = np.arange(20).reshape(10, 2)
y = np.array([0, 1] * 5)
row_ids = np.arange(100, 110)
X_tr, X_te, y_tr, y_te, id_tr, id_te = train_test_split(
X, y, row_ids, test_size=0.3, random_state=0
)
print(len(X_tr), len(X_te))
print(id_te)The output shows 7 training rows and 3 test rows. id_te holds the IDs of the three test rows, in the shuffled order they were chosen. Because the IDs were split in the same call, id_te[i] still belongs to X_te[i] and y_te[i].
Do not split X and y in two separate calls with a shared random_state and assume they stay aligned. It often works, but it breaks as soon as you add stratify, change one array's length, or drop rows from one of them. One call with all arrays is safer.
Pandas input
If you pass DataFrames or Series, the outputs are also DataFrames or Series. Their index labels are kept from the original data:
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
data = load_breast_cancer(as_frame=True)
X, y = data.data, data.target
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
print(type(X_train).__name__)
print(len(X_train.index.intersection(X_test.index)))
print(X_train.index.equals(y_train.index))This prints DataFrame, then 0 (no row appears in both parts), then True (features and labels still line up by index).
Because the index is preserved, you can trace any test row back to the original table with X_test.index. After a split the index is no longer 0, 1, 2, ... in order. Code that uses positions (iloc) and code that uses labels (loc) will now give different results, so use the one you mean.
Shuffling and when to turn it off
By default shuffle=True. The rows are randomly permuted before the cut, so the test set is a random sample of the whole dataset.
This default matters because many datasets are stored in an order that carries meaning. A file sorted by class, by date, or by customer would give a biased split if you simply took the last 20% of rows. A test set made of only one class tells you almost nothing.
Setting shuffle=False takes the first rows for training and the last rows for the test set. You only want this when order is part of the problem, for example when you must train on the past and test on the future. Even then, TimeSeriesSplit and date-based cuts are usually clearer. Time-ordered data is covered in a later chapter.
Two rules follow from this:
shuffle=Falsecannot be combined withstratify. Stratified splitting needs random sampling, and scikit-learn raises aValueErrorif you try.random_statehas no effect whenshuffle=False, because nothing is random.
Common errors
- Fitting on the full dataset first. Any step that learns from data, such as scaling, imputing missing values or selecting features, must see only the training rows. Applying it to all rows before splitting lets test-set information leak into training. The data leakage chapter covers this and the fix.
- Splitting after oversampling or duplicating rows. If you duplicate minority-class rows and then split, copies of the same row land in both parts. Split first, then resample the training part only.
- Looking at the test score and then changing the model. Each time you adjust something because of the test result, the test set stops being an honest estimate. A separate validation set exists for this purpose, and it is the subject of an upcoming chapter.
- Mismatched lengths. If
Xandyhave different numbers of rows, the call raisesValueError: Found input variables with inconsistent numbers of samples. Checklen(X) == len(y)after any filtering step. - Tiny test sets. With a handful of test rows, one extra mistake changes the score by several points. A single split of a small dataset gives a noisy estimate. How to size the parts is covered in the next chapters, and cross-validation helps when data is scarce.
- Wrong variable names. Writing
X_train, y_train, X_test, y_test = ...runs without complaint if the shapes happen to fit, but it silently assigns the wrong arrays. Keep the standard order.
A quick sanity check after splitting
A few lines after every split catch most problems early:
import numpy as np
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
)
assert len(X_train) + len(X_test) == len(X)
assert len(X_train) == len(y_train) and len(X_test) == len(y_test)
print("class share, full: ", np.bincount(y) / len(y))
print("class share, train:", np.bincount(y_train) / len(y_train))
print("class share, test: ", np.bincount(y_test) / len(y_test))The first two lines check that no rows were lost and that features and labels still match in length. The three printed rows show whether class shares in the parts resemble the whole dataset. With stratify=y they are nearly identical. Without it, they can drift, especially in small or imbalanced data.
Summary
train_test_split shuffles your rows, cuts them into two non-overlapping parts, and returns a train/test pair for each array you pass in. You control the sizes with test_size or train_size, the randomness with random_state, and the class balance with stratify. Turn off shuffling only when order matters, and remember that it rules out stratification. Fit every learning step on the training part only, and treat the test part as a final check on a finished model.
Exercise
A DataFrame has 1,000 rows. You call traintestsplit(X, y, testsize=0.3, randomstate=1). How many rows are in each part? Then say what happens if you add shuffle=False together with stratify=y.
Show answer
The training set has 700 rows and the test set has 300 rows. Adding shuffle=False together with stratify=y raises a ValueError, because stratified splitting requires random shuffling.
Exercise
A colleague splits X and y in two separate calls to traintestsplit, both with random_state=42, and then trains on the results. Why is this risky, and what is the safer way?
Show answer
The two calls only stay aligned if the arrays have the same length and no other option, such as stratify, changes how rows are chosen. Any change to one call can silently pair features with the wrong labels. The safer way is a single call, traintestsplit(X, y, ...), which assigns each row to a part once and returns aligned results.