Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a deterministic Random number generator with numpy seed?

As I understand the syntax is

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 the rand(), I get different results. Is there something I am missing with the seed function?

like image 560
unj2 Avatar asked Sep 27 '15 15:09

unj2


People also ask

Is random seed deterministic?

So yes, it is deterministic.

Can NumPy generate random numbers?

Generate Random Number NumPy offers the random module to work with random numbers.

How do I randomly generate a random seed in Python?

Python Random seed() Method The random number generator needs a number to start with (a seed value), to be able to generate a random number. By default the random number generator uses the current system time. Use the seed() method to customize the start number of the random number generator.


Video Answer


1 Answers

Think of a generator:

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

That will continuously give the next number from the number you insert to the generator. With seeds, it's nearly the same concept. I try to set a variable in which to generate data from, and the position in within that is still saved. Let's put this into practice:

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

If you want to restart, you need to restart the generator as well:

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

The same idea with the numpy object. If you want 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)
like image 98
Zizouz212 Avatar answered Sep 29 '22 21:09

Zizouz212