Sub topic 7
Seeding random number generators
This chapter assumes you can write basic NumPy code and use Jupyter. It also assumes you know what "restart and run all" does, from the earlier chapters on hidden state. Here you will learn how to make random steps in an analysis repeatable. You will also learn what a seed does not guarantee.
Why random numbers break reproducibility
Many analyses use randomness: shuffling rows, splitting data into training and test sets, bootstrapping, simulation, and model initialization. A computer does not produce true randomness. It uses a pseudo-random number generator (PRNG), an algorithm that turns an internal state into a stream of numbers that look random.
The starting state comes from a seed. If you give the PRNG no seed, it takes one from the operating system, and every run gives different numbers. If you give it a fixed seed, every run starts from the same state and produces the same stream.
A fixed seed is not a trick to hide variation. It makes a run repeatable, so a reviewer can get your exact numbers and check your work. Whether the result is robust is a separate question, covered at the end of this chapter.
Use an explicit Generator
NumPy's recommended interface is the Generator. You create one from a seed and call methods on that object.
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)Every run of this cell prints the same five numbers. Put the seed in a named constant near the top of the notebook so it is easy to see, change, and record.
NumPy also has an older global interface: np.random.seed(42) followed by calls such as np.random.rand(). It still works, but it keeps one hidden generator shared by the whole process. Any library that calls the global functions advances the same state, so your numbers can change when an unrelated import or call changes. An explicit Generator object has no shared state, so only code that receives it can change it.
The state advances with every draw
A generator has a position in its stream. Each draw moves it forward. This is the same hidden-state problem as out-of-order cells, now applied to random numbers.
import numpy as np
rng = np.random.default_rng(1)
first = rng.normal(size=3)
second = rng.normal(size=3)
rng_again = np.random.default_rng(1)
replay = rng_again.normal(size=3)
print(np.allclose(first, replay)) # True
print(np.allclose(second, replay)) # FalseThe second batch differs from the first because the generator had already moved past the first three numbers. In a notebook this causes a common failure:
- You create
rngin cell 2. - You draw from it in cell 7.
- You re-run cell 7 by itself while exploring.
The numbers in cell 7 have now changed, because the generator advanced. A "restart and run all" gives the original numbers again, which is one more reason to rely on that check before you trust a result.
Two habits reduce this problem:
- Create the generator in the same cell as the code that uses it, or inside the function that needs it.
- Keep each random step independent of cell order, so a cell gives the same output however many times you run it.
Pass the generator into functions
A function that creates its own generator from a fixed seed hides a decision inside the code. A function that calls the global state depends on everything else that ran. A better design is to accept the generator, or a seed, as an argument.
import numpy as np
def bootstrap_means(values, n_resamples, rng):
"""Return the mean of n_resamples bootstrap samples of values."""
values = np.asarray(values)
means = np.empty(n_resamples)
for i in range(n_resamples):
resample = rng.choice(values, size=values.size, replace=True)
means[i] = resample.mean()
return means
data = [2.1, 2.5, 1.9, 3.0, 2.7, 2.2]
rng = np.random.default_rng(7)
means = bootstrap_means(data, n_resamples=1000, rng=rng)
low, high = np.percentile(means, [2.5, 97.5])
print(f"95% interval: {low:.2f} to {high:.2f}")The caller controls the randomness, and a test can pass a generator with a known seed. This also matters when you later move the function into a module, because the module does not need to know your seed.
Independent streams for independent jobs
Sometimes you need several random streams that must not overlap, for example one per simulation run or per worker process. Do not use SEED, SEED + 1, SEED + 2. Adjacent seeds are not guaranteed to give streams with good statistical independence. Use SeedSequence, which derives child seeds from one parent seed in a way designed to keep them independent.
import numpy as np
SEED = 20240601
parent = np.random.SeedSequence(SEED)
children = parent.spawn(3)
rngs = [np.random.default_rng(child) for child in children]
for i, g in enumerate(rngs):
print(i, g.integers(0, 100, size=4))One master seed still controls everything, and each job gets its own stream. If you run jobs in a process pool, create the children in the parent process and hand one to each worker. Do not let each worker seed itself from the clock.
Seed every library that draws random numbers
A NumPy seed does not control other libraries. Each source of randomness has its own state, and you must set each one you use.
| Source | How to seed | Note |
|---|---|---|
| NumPy | `np.random.default_rng(seed)` | Pass the generator to your code. |
| Python `random` | `random.Random(seed)` or `random.seed(seed)` | The instance form avoids shared global state. |
| scikit-learn | `random_state=seed` argument | Pass an integer to each estimator and splitter that accepts it. |
| PyTorch | `torch.manual_seed(seed)` | GPU operations may still vary unless you request deterministic algorithms. |
| Hash ordering | `PYTHONHASHSEED=0` environment variable | Set before Python starts. Affects iteration order of sets of strings. |
For scikit-learn, give an integer to every call that takes random_state. If you pass a shared RandomState object instead, the result depends on how many draws happened earlier, which brings back the order problem.
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
SEED = 20240601
X, y = make_classification(n_samples=500, n_features=10, random_state=SEED)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=SEED
)
model = RandomForestClassifier(n_estimators=100, random_state=SEED)
model.fit(X_train, y_train)
print("Test accuracy:", round(model.score(X_test, y_test), 3))The hash-ordering row is a subtle one. Python randomizes string hashes at startup, so iterating over a set of strings can give a different order on each run. If your code builds a list from a set, results can differ even with every PRNG seeded. Sort the items before use. That fixes the problem without environment settings.
What a seed does not guarantee
A seed makes the same code on the same setup repeat itself. It does not promise more than that:
- Library versions. NumPy states that
Generatorstreams may change between releases, for example when an algorithm improves. Record the NumPy version with your results, and pin it, as covered in the chapter on dependencies. - Hardware and parallelism. Floating-point sums done in a different order, on a different number of threads, or on a GPU can differ in the last digits. Multi-threaded and GPU code often needs extra settings, such as
torch.use_deterministic_algorithms(True), and may be slower. - Code changes. If you add or remove one draw before a random step, every later number shifts. Independent streams from
spawnlimit this effect, because a change in one job does not move another job's numbers.
A seed hides variation, so measure it
A single seed gives one outcome from a distribution of possible outcomes. If a model scores 0.91 with seed 20240601 and 0.86 with another, the headline number was luck. Fix the seed for repeatability, then separately check sensitivity by running the analysis under several seeds and reporting the spread.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
SEED = 20240601
X, y = make_classification(n_samples=500, n_features=10, random_state=SEED)
scores = []
for child in np.random.SeedSequence(SEED).spawn(5):
run_seed = int(child.generate_state(1)[0])
X_tr, X_te, y_tr, y_te = train_test_split(
X, y, test_size=0.2, random_state=run_seed
)
model = RandomForestClassifier(n_estimators=100, random_state=run_seed)
scores.append(model.fit(X_tr, y_tr).score(X_te, y_te))
print("Scores:", np.round(scores, 3))
print(f"Mean {np.mean(scores):.3f}, std {np.std(scores):.3f}")The five seeds are derived from one master seed, so this whole experiment is itself repeatable.
Record the seed
A seed is part of the input to the analysis. Write it down where the result is stored: in the notebook output, in a parameters cell, or in the run metadata file covered in a later chapter. A result file that says "accuracy 0.91" without its seed, package versions, and data hash cannot be checked by someone else.
Exercise
A notebook creates rng = np.random.default_rng(5) in cell 2. Cell 6 draws rng.normal(size=3). A colleague runs the whole notebook and gets values A. You re-run only cell 6 twice, then send your numbers B. Why might A and B differ, and what are two ways to fix the notebook?
Show answer
The generator advances with every draw. Re-running cell 6 without re-creating rng continues the stream from where it stopped, so the numbers change. Fix it by creating the generator in the same cell that uses it (or inside a function that takes a seed), or by passing rng into functions and always checking results with a restart and run all. Recording the seed alongside the results also helps.
Exercise
You need 4 parallel simulation jobs that must not share random numbers, all controlled by one seed. What do you use, and why not seeds SEED, SEED + 1, SEED + 2, SEED + 3?
Show answer
Use np.random.SeedSequence(SEED).spawn(4) and build one default_rng from each child. Spawning is designed to give independent streams. Adjacent integer seeds do not carry the same guarantee of independence.