11

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?

2
  • 5
    Yes; if you want the same result every time you need to call seed in-between. It's already deterministic, but that doesn't mean you get the same result every time you call np.random. Commented Sep 27, 2015 at 15:39
  • 1
    This may also be useful for your purposes: Difference between np.random.seed() and np.random.RandomState() Commented Sep 27, 2015 at 18:15

1 Answer 1

12

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.