Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
537 views
in Technique[技术] by (71.8m points)

python - How can I retrieve the current seed of NumPy's random number generator?

The following imports NumPy and sets the seed.

import numpy as np
np.random.seed(42)

However, I'm not interested in setting the seed but more in reading it. random.get_state() does not seem to contain the seed. The documentation doesn't show an obvious answer.

How do I retrieve the current seed used by numpy.random, assuming I did not set it manually?

I want to use the current seed to carry over for the next iteration of a process.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The short answer is that you simply can't (at least not in general).

The Mersenne Twister RNG used by numpy has 219937-1 possible internal states, whereas a single 64 bit integer has only 264 possible values. It's therefore impossible to map every RNG state to a unique integer seed.

You can get and set the internal state of the RNG directly using np.random.get_state and np.random.set_state. The output of get_state is a tuple whose second element is a (624,) array of 32 bit integers. This array has more than enough bits to represent every possible internal state of the RNG (2624 * 32 > 219937-1).

The tuple returned by get_state can be used much like a seed in order to create reproducible sequences of random numbers. For example:

import numpy as np

# randomly initialize the RNG from some platform-dependent source of entropy
np.random.seed(None)

# get the initial state of the RNG
st0 = np.random.get_state()

# draw some random numbers
print(np.random.randint(0, 100, 10))
# [ 8 76 76 33 77 26  3  1 68 21]

# set the state back to what it was originally
np.random.set_state(st0)

# draw again
print(np.random.randint(0, 100, 10))
# [ 8 76 76 33 77 26  3  1 68 21]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...