Sub topic 7
Seeding random number generators
This chapter assumes you can write basic Python, run Jupyter notebooks, and have NumPy installed. It covers why random results change between runs and how to make them repeatable.
Why randomness breaks reproducibility
Many analyses use random numbers. Examples include train/test splits, bootstrap resampling, simulations, and model initialization. A random number generator (RNG) is an algorithm that produces a sequence of numbers that looks random. The sequence is fully determined by its starting value, called the seed.
If you do not set a seed, the library picks one from the operating system. Each run then gives different numbers, and a colleague who reruns your notebook gets different results from yours.
Seeding does not remove randomness. It makes the sequence repeatable. The same seed, library version, and sequence of calls produce the same numbers.
Use an explicit Generator
NumPy has two interfaces. The older one uses global state through np.random.seed() and functions such as np.random.normal(). The current recommended one creates a Generator object. Prefer the Generator, because the state lives in a variable you can see and pass around. Other cells or libraries cannot change it by accident.
import numpy as np
SEED = 20240601
rng = np.random.default_rng(SEED)
sample = rng.normal(loc=0.0, scale=1.0, size=5)
print(sample)Run this cell twice in a fresh kernel and you get the same five numbers. Put the seed in a named constant near the top of the notebook so readers can find it.
The hidden-state trap
A Generator advances every time you draw from it. If you run a cell that draws numbers twice, the second run gives different values, because the generator has moved on. This is hidden state, covered earlier in this tutorial.
The fix is to create the generator in a cell that runs once, then use "Restart and run all" to check the whole notebook. Every cell then draws in the same order each time.
Pass the generator to functions
Do not call a seeding function inside every helper. Create one generator and hand it to the code that needs it.
import numpy as np
def bootstrap_mean(values, n_resamples, rng):
means = []
for _ in range(n_resamples):
resample = rng.choice(values, size=len(values), replace=True)
means.append(resample.mean())
return np.array(means)
rng = np.random.default_rng(20240601)
data = rng.normal(10, 2, size=100)
means = bootstrap_mean(data, 1000, rng)
print(means.mean())Because rng is an argument, the function has no hidden dependency on global state. It also stays easy to test.
Seeds in other libraries
Each library keeps its own random state. Seeding NumPy does not seed the others.
| Library | How to seed |
|---|---|
| Python `random` | `random.seed(SEED)` |
| NumPy (legacy) | `np.random.seed(SEED)` |
| NumPy (current) | `np.random.default_rng(SEED)` |
| scikit-learn | `random_state=SEED` argument on estimators and splitters |
| PyTorch | `torch.manual_seed(SEED)` |
For scikit-learn, pass random_state explicitly, for example train_test_split(X, y, random_state=SEED). If you pass an integer, the result is repeatable. If you leave it unset, it uses global NumPy state.
Common errors
- Seeding once at the top, then rerunning cells out of order.
- Seeding NumPy but forgetting
random_statein scikit-learn. - Assuming a seed gives identical results across library versions. Algorithms can change between releases, so pin versions as well.
- Using parallel workers that share one seed. Each worker then produces the same numbers. Use
rng.spawn()ornp.random.SeedSequence(SEED).spawn(n)to create independent child generators. - Reporting one seeded run as if it were the only answer. Check that your conclusion holds across several seeds.
Exercise
You seed NumPy at the top of a notebook, but your scikit-learn train/test split still changes between runs. What is the likely cause, and how do you fix it?
Show answer
scikit-learn does not use your Generator unless you pass it a seed. Add random_state=SEED to the splitter, for example train_test_split(X, y, random_state=SEED).
Exercise
A cell that draws rng.normal(size=3) gives different values each time you rerun it, even though the seed is fixed. Why, and what check confirms the notebook is repeatable?
Show answer
The generator advances with every draw, so a rerun continues from a later point in the sequence. Use Restart and run all. Each cell then runs once, in order, from a freshly seeded generator.