8

I'd like my script to create the same array of numbers each time I run the script. Earlier I was using np.random.seed(). For example:

np.random.seed(1)
X = np.random.random((3,2))

I've read that instead of np.random.seed() there should be used RandomState. But I have no idea how to use it, tried some combinations but none worked.

4
  • 1
    ...so where did you read that? What's the problem with np.random.seed? Commented Sep 8, 2015 at 15:59
  • 1
    In this question. Look at the second answer and also at this comment Commented Sep 8, 2015 at 16:03
  • What did you try? What output did you get that makes you think it didn't work? Commented Sep 8, 2015 at 17:21
  • @RobertKern Something like: np.random.RandomState(1) np.random.random((3,2)) I just want to know how to use this RandomState, I'm still new to programming, Python and especially NumPy Commented Sep 8, 2015 at 19:00

1 Answer 1

18

It's true that it's sometimes advantageous to make sure you get your entropy from a specific (non-global) stream. Basically, all you have to do is to make a RandomState object and then use its methods instead of using numpy's random functions. For example, instead of

>>> np.random.seed(3)
>>> np.random.rand()
0.5507979025745755
>>> np.random.randint(10**3, 10**4)
7400

You could write

>>> R = np.random.RandomState(3)
>>> R
<mtrand.RandomState object at 0x7f79b3315f28>
>>> R.rand()
0.5507979025745755
>>> R.randint(10**3, 10**4)
7400

So all you need to do is make R and then use R. instead of np.random. -- pretty simple. And you can pass R around as you want, and have multiple random streams (if you want a certain process to be the same while another changes, etc.)

Sign up to request clarification or add additional context in comments.

2 Comments

Great, this is what I was looking for. I've tried to use RandomState in the same way as random.seed, to combine RandomState with numpy functions and it was wrong. Now I understand how to deal with it. Thank you very much.
What happens if I use R without passing any seed? It is the same of using always a random seed?

Your Answer

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