How to use random.RandomState

kujaw picture kujaw · Sep 8, 2015 · Viewed 7.2k times · Source

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.

Answer

DSM picture DSM · Sep 8, 2015

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