I need to create a class which takes in a random number generator (i.e. a numpy.random.RandomState
object) as a parameter. In the case this argument is not specified, I would like to assign it to the random generator that numpy uses when we run numpy.random.<random-method>
. How do I access this global generator? Currently I am doing this by just assigning the module object as the random generator (since they share methods / duck typing). However this causes issues when pickling (unable to pickle module object) and deep-copying. I would like to use the RandomState object behind numpy.random
PS: I'm using python-3.4
As well as what kazemakase suggests, we can take advantage of the fact that module-level functions like numpy.random.random
are really methods of a hidden numpy.random.RandomState
by pulling the __self__
directly from one of those methods:
numpy_default_rng = numpy.random.random.__self__
numpy.random
imports * from numpy.random.mtrand
, which is an extension module written in Cython. The source code shows that the global state is stored in the variable _rand
. This variable is not imported into the numpy.random
scope but you can get it directly from mtrand.
import numpy as np
from numpy.random.mtrand import _rand as global_randstate
np.random.seed(42)
print(np.random.rand())
# 0.3745401188473625
np.random.RandomState().seed(42) # Different object, does not influence global state
print(np.random.rand())
# 0.9507143064099162
global_randstate.seed(42) # this changes the global state
print(np.random.rand())
# 0.3745401188473625
I don't know how to access the global state. However, you can use a RandomState object and pass it along. Random distributions are attached to it, so you call them as methods.
Example:
import numpy as np
def computation(parameter, rs):
return parameter*np.sum(rs.uniform(size=5)-0.5)
my_state = np.random.RandomState(seed=3)
print(computation(3, my_state))
来源:https://stackoverflow.com/questions/41985484/how-to-access-numpy-default-global-random-number-generator