编程语言
首页 > 编程语言> > python – 如何检索NumPy随机数生成器的当前种子?

python – 如何检索NumPy随机数生成器的当前种子?

作者:互联网

以下导入NumPy并设置种子.

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

但是,我对设置种子并不感兴趣,而是更多地阅读它. random.get_state()似乎不包含种子. documentation没有显示出明显的答案.

我如何检索numpy.random使用的当前种子,假设我没有手动设置它?

我想使用当前种子来继承进程的下一次迭代.

解决方法:

简短的回答是你根本不能(至少不是一般).

numpy使用的Mersenne Twister RNG具有219937-1个可能的内部状态,而单个64位整数仅具有264个可能的值.因此,不可能将每个RNG状态映射到唯一的整数种子.

您可以使用np.random.get_statenp.random.set_state直接获取和设置RNG的内部状态.get_state的输出是一个元组,其第二个元素是一个32位整数的(624)数组.该阵列具有足够多的比特来表示RNG的每个可能的内部状态(2624 * 32> 219937-1).

get_state返回的元组可以像种子一样使用,以便创建可重现的随机数序列.例如:

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]

标签:random-seed,python,numpy,random,mersenne-twister
来源: https://codeday.me/bug/20191004/1852336.html