How to access numpy default random number generator

I need to create a class that takes a random number generator (i.e., a numpy.random.RandomState object) as a parameter. In case this argument is not specified, I would like to assign it to a random generator that uses numpy when running numpy.random.<random-method> . How to access this global generator? I am currently doing this by simply assigning the module object as a random generator (as they share methods / duck typing). However, this causes problems during etching (inability to reveal the module object) and deep copying. I would like to use a RandomState object for numpy.random

PS: I am using python-3.4

+5
source share
3 answers

Like what kazemakase offers, we can take advantage of the fact that module level functions such as numpy.random.random are really methods of hidden numpy.random.RandomState , pulling __self__ directly from one of these methods:

 numpy_default_rng = numpy.random.random.__self__ 
+2
source

numpy.random import * from numpy.random.mtrand , which is an extension module written in Cython. The source code shows that the global state is stored in the _rand variable. This variable is not imported into the numpy.random , 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 
+2
source

I do not know how to access the global state. However, you can use the RandomState object and pass it. Random distributions are attached to it, so you name 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)) 
0
source

Source: https://habr.com/ru/post/1263695/


All Articles