Create the same random NumPy array sequentially

I'm waiting for another developer to finish work on code that will return an array of np form (100,2000) with values ​​-1, 0 or 1.

At the same time, I want to randomly create an array with the same characteristics so that I can get an advantage in my development and testing. The fact is that I want this randomly created array to be the same every time, so that I do not check the array, which constantly changes its value each time I restart my process.

I can create my array in this way, but is there any way to create it so that it is the same every time. I can pickle an object and open it, but I don’t know if there is another way.

r = np.random.randint(3, size=(100, 2000)) - 1 
+84
python numpy random
Apr 29 '11 at 19:10
source share
4 answers

Just run a fixed value random number generator like

 numpy.random.seed(42) 

This way, you will always get the same sequence of random numbers.

+78
Apr 29 '11 at 19:12
source share

Create your own instance of numpy.random.RandomState() with the seed of your choice. Do not use numpy.random.seed() , except for working with inflexible libraries that do not allow you to pass your own instance of RandomState .

 [~] |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]) 
+174
Apr 29 2018-11-21T00:
source share

If you use other functions that rely on a random state, you cannot just set a common seed, but instead you must create a function to generate your random list of numbers and set the seed as a parameter to the function. This will not interfere with other random code generators:

 # Random states def 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 function states = get_states(random_state=42, low=2, high=28347, size=25) 
+3
Nov 08 '17 at 9:38 on
source share

It is important to understand what the seed of the random number generator is and when / how it is installed in your code (see, for example, here for a good explanation of the mathematical meaning of the seed).

To do this, you need to set the initial value by doing:

 random_state = np.random.RandomState(seed=your_favorite_seed_value) 

Then it is important to generate random numbers from random_state, and not from np.random. Those. you should do:

 random_state.randint(...) 

instead

 np.random.randint(...) 

which will create a new instance of RandomState () and basically use your computer's internal clock to set the seed.

+1
Feb 03 '19 at 19:19
source share



All Articles