best practices for seeding random and numpy.random in the same program

  • Last Update :
  • Techknowledgy :

Using the same arbitrary seed:

random.seed(42)
np.random.seed(42)

Using two different arbitrary seeds:

random.seed(271828)
np.random.seed(314159)

Using a random number from one RNG to seed the other:

random.seed(42)
np.random.seed(random.randint(0, 2 ** 32))

Suggestion : 2

Updated: April 7, 2020

import numpy as np
seed = 12345
rng = np.random.default_rng(seed) # can be called without a seed
rng.random()
import numpy as np

def stochastic_function(seed, high = 10):
   rng = np.random.default_rng(seed)
return rng.integers(high, size = 5)
import numpy as np
from joblib
import Parallel, delayed

def stochastic_function(seed, high = 10):
   rng = np.random.default_rng(seed)
return rng.integers(high, size = 5)

seed = 98765
# create the RNG that you want to pass around
rng = np.random.default_rng(seed)
# get the SeedSequence of the passed RNG
ss = rng.bit_generator._seed_seq
# create 5 initial independent states
child_states = ss.spawn(5)

# use 2 processes to run the stochastic_function 5 times with joblib
random_vector = Parallel(n_jobs = 2)(delayed(
   stochastic_function)(random_state) for random_state in child_states)
print(random_vector)

# rerun to check that we obtain the same outputs
random_vector = Parallel(n_jobs = 2)(delayed(
   stochastic_function)(random_state) for random_state in child_states)
print(random_vector)

Suggestion : 3

The best practice is to not reseed a BitGenerator, rather to recreate a new one. This method is here for legacy reasons. This example demonstrates best practice.,This is a convenience, legacy function.,Reseed a legacy MT19937 BitGenerator

>>> from numpy.random
import MT19937
   >>>
   from numpy.random
import RandomState, SeedSequence
   >>>
   rs = RandomState(MT19937(SeedSequence(123456789)))
# Later, you want to restart the stream
   >>>
   rs = RandomState(MT19937(SeedSequence(987654321)))