如何获取NumPy随机数生成器的当前种子? [英] How can I retrieve the current seed of NumPy's random number generator?
问题描述
以下代码导入NumPy并设置种子.
The following imports NumPy and sets the seed.
import numpy as np
np.random.seed(42)
但是,我对设置种子不感兴趣,但对阅读它更感兴趣. random.get_state()
似乎不包含种子. 文档没有明显的答案.
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.
假设没有手动设置,如何检索numpy.random
使用的当前种子?
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.
推荐答案
简短的答案是,您根本做不到(至少通常不是这样).
The short answer is that you simply can't (at least not in general).
numpy使用的 Mersenne Twister RNG具有2 19937 - 1个可能的内部状态,而单个64位整数只有2 64 个可能的值.因此,不可能将每个RNG状态映射到唯一的整数种子.
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.
您可以直接使用 np.random.set_state
. get_state
的输出是一个元组,其第二个元素是32位整数的(624,)
数组.该数组具有足够多的位来表示RNG的每个可能的内部状态(2 624 * 32 > 2 19937 -1).
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).
get_state
返回的元组可以像种子一样使用,以创建可重现的随机数序列.例如:
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]
这篇关于如何获取NumPy随机数生成器的当前种子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!