NumPy Random Seed Not Reproducible Fix
In this tutorial, you'll learn about NumPy Random Seed Not Reproducible Fix. We cover key concepts, practical examples, and best practices.
NumPy random seed appears to not work when you set the seed in a different process, use the legacy RandomState incorrectly, or expect the same results across different NumPy versions.
The Wrong Way
import numpy as np
for _ in range(3):
np.random.seed(42)
print(np.random.rand(3))
Output:
[0.37454012 0.95071431 0.73199394]
[0.37454012 0.95071431 0.73199394]
[0.37454012 0.95071431 0.73199394]
The seed is reset before each call, producing the same sequence every time.
The Right Way
import numpy as np
rng = np.random.default_rng(42)
print(rng.random(3))
print(rng.random(3))
Output:
[0.77395605 0.43887844 0.85859792]
[0.69736803 0.09417735 0.97562235]
Using the new Generator API with a SeedSequence gives reproducible but non-repeating results.
Step-by-Step Fix
1. Use the new Generator API
rng = np.random.default_rng(42)
a = rng.random(10)
b = rng.normal(0, 1, 10)
2. Set seed once at the top of your script
np.random.seed(42) # legacy API
# all subsequent calls use this seed
print(np.random.rand(3))
print(np.random.rand(3))
3. Save and restore the random state
state = np.random.get_state()
np.random.shuffle(data)
np.random.set_state(state) # restore for reproducibility
4. Use SeedSequence for complex seeding
ss = np.random.SeedSequence(42)
rng = np.random.default_rng(ss)
5. Create independent parallel streams
seed = 42
streams = np.random.SeedSequence(seed).spawn(4)
rngs = [np.random.default_rng(s) for s in streams]
Prevention Tips
- Use
np.random.default_rng(seed)instead ofnp.random.seed(). - Set the seed only once at the beginning of the script.
- Use
SeedSequencefor parallel or distributed random streams. - Save the random state with
get_state()for checkpointing. - Use integers for seeds, not floats or strings.
Common Mistakes with random seed
- Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists
These mistakes appear frequently in real-world NUMPY code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro