Issue
I am using rng = np.random.default_rng(seed=None)
for testing purposes following documentation.
My program is a scientific code, so it is good to have some random values to test it, but if I found a problem with the code's result, I would like to get the seed back and try again to find the problem. Is there any way to do that?
Things like this question does not seem to work with a Generator
:
AttributeError: 'numpy.random._generator.Generator' object has no attribute 'get_state'
Of course I can always try a set of predefined seeds, but that is not what I want.
Solution
Use __getstate__
, __setstate__
and forget about seed
... it's just a parameter for default_rng
!
# old instance
rng = np.random.default_rng(seed=None)
s_old = rng.__getstate__()
# new instance
rng = np.random.default_rng(seed=123123) # seed=anything, also None
s_new = rng.__getstate__()
print(s_old == s_new)
#False
# update "seed"
rng.__setstate__(s_old) # pass the old "seed"
s_recovered = rng.__getstate__()
print(s_old == s_recovered)
#True
Then when you call methods to generate random numbers you will be able to replicate the randomness.
Alternative of the dunder methods
# get the state
s_old = rng.bit_generator.state
and
# set the state of the new instance of rng
rng.bit_generator.state = s_old
Answered By - cards
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.