Consistently create same random numpy array Consistently create same random numpy array numpy numpy

Consistently create same random numpy array


Create your own instance of numpy.random.RandomState() with your chosen seed. Do not use numpy.random.seed() except to work around inflexible libraries that do not let you pass around your own RandomState instance.

[~]|1> from numpy.random import RandomState[~]|2> prng = RandomState(1234567890)[~]|3> prng.randint(-1, 2, size=10)array([ 1,  1, -1,  0,  0, -1,  1,  0, -1, -1])[~]|4> prng2 = RandomState(1234567890)[~]|5> prng2.randint(-1, 2, size=10)array([ 1,  1, -1,  0,  0, -1,  1,  0, -1, -1])


Simply seed the random number generator with a fixed value, e.g.

numpy.random.seed(42)

This way, you'll always get the same random number sequence.

This function will seed the global default random number generator, and any call to a function in numpy.random will use and alter its state. This is fine for many simple use cases, but it's a form of global state with all the problems global state brings. For a cleaner solution, see Robert Kern's answer below.


If you are using other functions relying on a random state, you can't just set and overall seed, but should instead create a function to generate your random list of number and set the seed as a parameter of the function. This will not disturb any other random generators in the code:

# Random statesdef get_states(random_state, low, high, size):    rs = np.random.RandomState(random_state)    states = rs.randint(low=low, high=high, size=size)    return states# Call functionstates = get_states(random_state=42, low=2, high=28347, size=25)