How to create a deterministic random number generator with a numpy seed?

As I understand it, the syntax

In[88]: np.random.seed(seed=0) In[89]: np.random.rand(5) < 0.8 Out[89]: array([ True, True, True, True, True], dtype=bool) In[90]: np.random.rand(5) < 0.8 Out[90]: array([ True, True, False, False, True], dtype=bool) 

However, when I run rand() , I get different results. Is there something I am missing with the seed function?

+5
source share
1 answer

Think of a generator:

 def gen(start): while True: start += 1 yield start 

This will continuously give the next number from the number you insert into the generator. With seeds, this is almost the same concept. I am trying to set a variable in which data will be generated, and the position inside which is saved. Put it in practice:

 >>> generator = gen(5) >>> generator.next() 6 >>> generator.next() 7 

If you want to restart, you also need to restart the generator:

 >>> generator = gen(5) >>> generator.next() 6 

Same idea with numpy object. If you want to get the same results over time, you need to restart the generator with the same arguments.

 >>> np.random.seed(seed=0) >>> np.random.rand(5) < 0.8 array([ True, True, True, True, True], dtype=bool) >>> np.random.rand(5) < 0.8 array([ True, True, False, False, True], dtype=bool) >>> np.random.seed(seed=0) # reset the generator! >>> np.random.rand(5) < 0.8 array([ True, True, True, True, True], dtype=bool) 
+6
source

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


All Articles