NumPy random seed produces different random numbers

I run the following code:

np.random.RandomState(3) idx1 = np.random.choice(range(20),(5,)) idx2 = np.random.choice(range(20),(5,)) np.random.RandomState(3) idx1S = np.random.choice(range(20),(5,)) idx2S = np.random.choice(range(20),(5,)) 

The output I get is the following:

 idx1: array([ 2, 19, 19, 9, 4]) idx1S: array([ 2, 19, 19, 9, 4]) idx2: array([ 9, 2, 7, 10, 6]) idx2S: array([ 5, 16, 9, 11, 15]) 

idx1 and idx1S, but idx2 and idx2S do not match. I expect that as soon as I sow a random number generator and repeat the same sequence of commands - it should produce the same sequence of random numbers. Is that not so? Or is there something else I'm missing?

+5
source share
2 answers

You mislead RandomState with seed . Your first line creates an object that can then be used as your random source. For example, we do

 >>> rnd = np.random.RandomState(3) >>> rnd <mtrand.RandomState object at 0xb17e18cc> 

and then

 >>> rnd.choice(range(20), (5,)) array([10, 3, 8, 0, 19]) >>> rnd.choice(range(20), (5,)) array([10, 11, 9, 10, 6]) >>> rnd = np.random.RandomState(3) >>> rnd.choice(range(20), (5,)) array([10, 3, 8, 0, 19]) >>> rnd.choice(range(20), (5,)) array([10, 11, 9, 10, 6]) 

[I donโ€™t understand why your idx1 and idx1S agree - but you have not actually published stand-alone decrypted text, so I suspect a user error.]

If you want to influence the global state, use seed :

 >>> np.random.seed(3) >>> np.random.choice(range(20),(5,)) array([10, 3, 8, 0, 19]) >>> np.random.choice(range(20),(5,)) array([10, 11, 9, 10, 6]) >>> np.random.seed(3) >>> np.random.choice(range(20),(5,)) array([10, 3, 8, 0, 19]) >>> np.random.choice(range(20),(5,)) array([10, 11, 9, 10, 6]) 

Using a specific RandomState object may seem less convenient at first, but it makes it a lot easier when you want to set up various entropy streams that you can set up.

+9
source

I think you should use the RandomState class as follows:

 In [21]: r=np.random.RandomState(3) In [22]: r.choice(range(20),(5,)) Out[22]: array([10, 3, 8, 0, 19]) In [23]: r.choice(range(20),(5,)) Out[23]: array([10, 11, 9, 10, 6]) In [24]: r=np.random.RandomState(3) In [25]: r.choice(range(20),(5,)) Out[25]: array([10, 3, 8, 0, 19]) In [26]: r.choice(range(20),(5,)) Out[26]: array([10, 11, 9, 10, 6]) 

Basically you make an r instance for RandomState and use it further. As you can see, re-siding gives the same results.

+6
source

Source: https://habr.com/ru/post/1216373/


All Articles