如何将numpy seed恢复到原来的状态?

2024-05-16 02:45:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个函数,可以做一些随机的事情

我想输入种子,所以对于相同的种子,输出将是相同的

但是在乞讨的时候开始播种,就像这样:

def generate_random_number(seed):
    np.random.seed(seed)

    magics = np.random.random(1)
    more_magics = ...

    return magics, more_magics

将导致调用此方法后,种子被破坏

有没有办法“保存”当前种子状态并在以后恢复

所以它看起来像这样:

def generate_random_number_without_ruining_for_others(seed):
    old_seed = np.random.get_seed()
    np.random.seed(seed)

    magics = np.random.random(1)
    more_magics = ...
    
    np.random.seed(old_seed)
    return magics, more_magics

当然,命令:np.random.get_seed()是一个组合函数。。有这样的东西吗? 或者是在不破坏每个人的随机状态的情况下生成“随机”(最多种子输入)输出的替代方法

(实际的随机过程在实践中要复杂得多,它在循环中生成矩阵,因此为了简单起见,我想坚持使用启动种子的格式)


Tags: 方法函数numbergetreturn状态defmore
1条回答
网友
1楼 · 发布于 2024-05-16 02:45:05

好的,您不能重置默认的随机生成器。实际上seed的文档说不要使用它:

This is a convenience, legacy function.

The best practice is to not reseed a BitGenerator, rather to
recreate a new one. This method is here for legacy reasons.
This example demonstrates best practice.

>>> from numpy.random import MT19937
>>> from numpy.random import RandomState, SeedSequence
>>> rs = RandomState(MT19937(SeedSequence(123456789)))

基于此,您可以构建自己的随机引擎并保存随机状态。以下是一个例子:

import numpy as np
rs = np.random.RandomState(np.random.MT19937(np.random.SeedSequence(123456789)))

savedState = rs.get_state()    # Save the state

v1 = rs.randint(0, 100, 7)     # array([28, 72, 18, 84,  6, 78, 92])
v2 = rs.randint(0, 100, 7)     # array([60, 91,  4, 29, 43, 68, 52])

rs.set_state(savedState)       # Reset the state

v3 = rs.randint(0, 100, 7)     # array([28, 72, 18, 84,  6, 78, 92])
v4 = rs.randint(0, 100, 7)     # array([60, 91,  4, 29, 43, 68, 52])

assert(np.array_equal(v1, v3)) # True
assert(np.array_equal(v2, v4)) # True

相关问题 更多 >