7

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.

kujaw
  • 313
  • 1
  • 3
  • 18
  • 1
    ...so where did you read that? What's the problem with `np.random.seed`? – jonrsharpe Sep 08 '15 at 15:59
  • 1
    In [this question](http://stackoverflow.com/questions/5836335/consistenly-create-same-random-numpy-array). Look at the second answer and also at [this comment](http://stackoverflow.com/questions/5836335/consistenly-create-same-random-numpy-array#comment6702590_5836372) – kujaw Sep 08 '15 at 16:03
  • What did you try? What output did you get that makes you think it didn't work? – Robert Kern Sep 08 '15 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 – kujaw Sep 08 '15 at 19:00

1 Answers1

17

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.)

DSM
  • 342,061
  • 65
  • 592
  • 494
  • 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. – kujaw Sep 08 '15 at 19:06
  • What happens if I use `R` without passing any seed? It is the same of using always a random seed? – AleB Oct 08 '20 at 09:16