Sub topic 4
Making splits reproducible
This chapter covers how random_state controls a split and how to make a split repeatable across runs, machines and growing datasets. It assumes you can run Python and scikit-learn, and that you know what train_test_split returns (see the earlier chapter on splitting data into training and test sets).
Why a split must be repeatable
A random split decides which rows the model learns from and which rows judge it. If that choice changes on every run, three problems follow:
- You cannot tell whether a score changed because you improved the model or because the test rows changed.
- You cannot reproduce a result you reported, so a colleague (or you, next month) gets a different number.
- You cannot debug. A bug that appears only on certain test rows is gone on the next run.
The fix is to make the randomness deterministic, so the same inputs always give the same split.
How `random_state` works
Computers produce random-looking numbers with a pseudo-random number generator. It starts from a number called a seed and produces a fixed sequence from it. The same seed gives the same sequence. train_test_split shuffles row positions using such a generator, so fixing the seed fixes the shuffle.
The random_state argument accepts three kinds of values:
| Value | Behavior |
|---|---|
| An integer, such as `42` | The same split every call, given the same data and library version. |
| `None` (the default) | Draws from NumPy's global generator. The split differs between runs unless you seeded that global generator yourself. |
| A `numpy.random.RandomState` instance | The instance advances with every call, so repeated calls give different splits. The whole sequence of splits is repeatable if you create the instance from a fixed seed. |
To see this, split row positions instead of the data itself. The returned indices are easy to compare.
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)
positions = np.arange(len(y))
def test_indices(seed):
_, test_idx = train_test_split(
positions, test_size=0.2, stratify=y, random_state=seed
)
return test_idx
print("same seed: ", np.array_equal(test_indices(42), test_indices(42)))
print("different seed:", np.array_equal(test_indices(42), test_indices(7)))
print("seed=None: ", np.array_equal(test_indices(None), test_indices(None)))The first line prints True. The second prints False. The third almost always prints False, because each unseeded call draws fresh numbers.
Seed the call, not just the process
You may see np.random.seed(0) at the top of a script. With random_state=None, scikit-learn does draw from NumPy's global generator, so that line affects the split. It is a fragile way to get repeatability, though. Any other code that draws a random number first (a data augmentation step, a different model, a shuffled print order) moves the global generator and changes your split. Passing an integer to random_state ties the split to that one call and nothing else.
Seed every randomized component, not only the split. A random forest, a stochastic gradient method and StratifiedKFold(shuffle=True) each take their own random_state. A fixed split with an unseeded model still gives a different score each run.
What an integer seed does not guarantee
An integer seed makes the shuffle repeatable, but the split also depends on the input. Three things can change the split even with random_state=42:
- Row order. The generator shuffles positions, not row contents. If a query returns rows in a different order tomorrow, position 17 is now a different row, and the test set changes.
- Dataset size. Adding or removing rows changes the shuffle. Most old rows will land in a different side of the split.
- Library versions. Scikit-learn and NumPy may change how they draw numbers between releases. Record versions alongside results.
For a fixed file that never changes, an integer seed is enough. For data that is refreshed, reordered or growing, you need one of the two techniques below.
Persisting the split
The most direct approach is to save the indices (or IDs) of each side once and reload them later.
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)
positions = np.arange(len(y))
train_idx, test_idx = train_test_split(
positions, test_size=0.2, stratify=y, random_state=42
)
np.savez("split_v1.npz", train=train_idx, test=test_idx)
saved = np.load("split_v1.npz")
X_train, y_train = X[saved["train"]], y[saved["train"]]
X_test, y_test = X[saved["test"]], y[saved["test"]]
print(X_train.shape, X_test.shape)Saved positions are only valid for the same row order. If your table has a stable identifier column, such as a customer ID, save those IDs instead of positions, and select rows by ID. Store the split file with the project, next to the code that uses it.
Hash-based splits for growing datasets
If new records arrive over time, re-running a seeded shuffle moves old records between sides. A record that was in training last month could end up in the test set now, which breaks the rule that the test set stays untouched. A better rule assigns each record to a side from its own ID, so the assignment never depends on the other rows.
import hashlib
def bucket(record_id, salt="split-v1"):
"""Map an ID to a stable number in [0, 1]."""
digest = hashlib.sha256(f"{salt}:{record_id}".encode()).hexdigest()
return int(digest[:8], 16) / 0xFFFFFFFF
def is_test(record_id, test_fraction=0.2, salt="split-v1"):
return bucket(record_id, salt) < test_fraction
ids = [f"user-{i}" for i in range(1000)]
test_ids = {i for i in ids if is_test(i)}
print("test size:", len(test_ids))
ids_later = ids + [f"user-{i}" for i in range(1000, 1200)]
test_later = {i for i in ids_later if is_test(i)}
print("old test rows still in test:", test_ids <= test_later)The last line prints True, because each record's side depends only on its own ID and the salt. The test size lands near 200 but is not exactly 200, since the split is by probability, not by count.
This approach has trade-offs:
- The split sizes are approximate, not exact.
- It cannot stratify. Class proportions in each side match the data only on average, which matters for small or imbalanced datasets.
- Changing the salt gives a completely new split, so treat the salt as part of the split's version.
Seed variance: do not shop for seeds
A single split is one random draw. Its score is partly a property of the model and partly luck about which rows landed in the test set. The next code measures how big that luck is.
import numpy as np
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(f"mean={np.mean(scores):.3f} std={np.std(scores):.3f} "
f"min={min(scores):.3f} max={max(scores):.3f}")Expect the minimum and maximum to differ by a few percentage points on this 569-row dataset. That spread is the noise level of a single split.
This leads to a common mistake: trying seeds until the test score looks good, then keeping that seed. This is a form of tuning on the test set. The reported score no longer estimates performance on new data, because you picked the split that flattered the model.
Follow these rules instead:
- Choose a seed once, before looking at any scores. Any integer works, and 42 has no special property.
- Do not change the seed in response to results.
- When you compare two models, use the same split for both. Differences smaller than the seed-to-seed spread are not evidence that one model is better.
- If the spread is large relative to the differences you care about, use repeated or cross-validated evaluation, covered in the cross-validation chapter, and report the mean and spread.
Common errors
- Leaving
random_stateunset in a notebook. The result looks fine once, and the next run reports a different number. - Re-splitting in every cell. If one cell splits and a later cell splits again with a different seed, the "test" rows in the second cell may have been in training in the first. Split once, then reuse the variables or the saved indices.
- Splitting after the data has been re-sorted. Sorting or deduplicating before the split changes positions, and therefore the split.
- Assuming equal seeds across tools. The same integer in scikit-learn, PyTorch and another library produces unrelated shuffles. A split made in one tool is not recreated by passing the same number to another. Save the indices.
- Treating the seed as a hyperparameter. See the previous section.
Exercise
A teammate reports 94% test accuracy using train_test_split(X, y, test_size=0.2, random_state=3) on a dataset that gets about 500 new rows every week. Re-running the same code a month later gives a different accuracy, even though the seed is the same. Give two reasons and a fix.
Show answer
With new rows added, the dataset size and row order differ, so the seeded shuffle assigns rows to the train and test sides differently. The library version may also have changed. Both reasons mean the split itself changed. A fix is to assign each row to a side from a stable ID with a salted hash (or to store the train and test IDs from the first split and reuse them), so old rows keep their side and only new rows are assigned. Also check whether the seed of the model itself is fixed, and ask whether seed 3 was picked because it gave a high score.