10

I have read the documentation but I still find difficult to understand the difference between the use of

numpy.random.RandomState(0) 

or

numpy.random.seed(0)

Don't they both ensure that the process through which the random values are selected is the same and consistent across runs?

user
  • 2,015
  • 6
  • 22
  • 39

1 Answers1

12

numpy.random.seed(0) resets the state of the existing global RandomState instance that underlies the functions in the numpy.random namespace.

numpy.random.RandomState(0) returns a new seeded RandomState instance but otherwise does not change anything. You have to use the returned RandomState instance to get consistent pseudorandom numbers. If you use the functions in the numpy.random namespace, you will not get consistent pseudorandom numbers because they are pulling from a different RandomState instance than the one you just created.

If you care about reproducibility, it is highly preferable to structure your code to pass around RandomState instances. Global state sucks. C.f. Consistenly create same random numpy array

Community
  • 1
  • 1
Robert Kern
  • 13,118
  • 3
  • 35
  • 32