Sub topic 4
Making splits reproducible
This chapter assumes you can run Python and have used train_test_split from the previous chapter. You should also know that a split divides rows into training and test parts.
Why a split must be repeatable
train_test_split shuffles rows before cutting them. Without a fixed starting point for the shuffle, each run gives a different split. Your score then changes between runs, and you cannot tell whether a model change or a different split caused the difference.
A reproducible split means the same code and data always give the same rows in each part. This lets you compare experiments, debug a result, and let a colleague rerun your work.
Fixing the shuffle with random_state
Computers produce "random" numbers from a starting value called a seed. The same seed gives the same sequence. In scikit-learn, the random_state argument sets that seed. Any integer works.
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)
a = train_test_split(X, y, test_size=0.2, random_state=42)
b = train_test_split(X, y, test_size=0.2, random_state=42)
c = train_test_split(X, y, test_size=0.2)
print("same seed, same test rows:", np.array_equal(a[1], b[1]))
print("no seed, same test rows: ", np.array_equal(a[1], c[1]))The first line prints True. The second almost always prints False, because c used a fresh shuffle.
What reproducibility depends on
A seed only fixes the shuffle. The split stays identical only if these also stay the same:
- The data. If rows are added, removed or reordered, the same seed gives a different split.
- The arguments. Changing
test_sizeorstratifychanges which rows land where. - The library version. Rarely, a new scikit-learn release changes how a split is computed. Record your versions.
Models have their own randomness. Many estimators, such as random forests, take a separate random_state. Setting it on the split does not set it on the model.
Treating the seed as a source of variation
A fixed seed gives a repeatable split, not a representative one. A single split can be lucky or unlucky, especially on small datasets. You can see how much a score depends on the split by repeating the experiment with several seeds.
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
scores = []
for seed in range(10):
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=seed
)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
model.fit(X_train, y_train)
scores.append(model.score(X_test, y_test))
print("min:", min(scores), "max:", max(scores))The gap between the minimum and maximum shows how much a single split can mislead you. A wide gap means one test score is weak evidence. Cross-validation, covered later, handles this more systematically.
Common mistakes
- Picking the seed that scores best. Trying seeds until the test score looks good turns the test set into a tuning target. Choose a seed once, before you look at results.
- Changing the seed between experiments. If model A uses seed 1 and model B uses seed 2, you are comparing models on different data. Use the same split for every model you compare.
- Splitting in several places. If two scripts each call
train_test_split, keep the arguments identical. A safer option is to split once and save the row indices or the resulting files. - Assuming a seed protects you from shifted data. Reloading a dataset in a different row order silently changes the split.
Exercise
You run train_test_split(X, y, test_size=0.2, random_state=7) today. Next week a colleague adds 50 new rows to the end of X and y and reruns the same line. Will the test set contain the same rows as before? Why or why not?
Show answer
No. The seed fixes the shuffle only for a dataset of a given size. With 50 more rows, the shuffle and the cut points change, so rows move between training and test. Save the original indices, or use a stable identifier for each row, if you need the old split to survive data updates.