临时修复后恢复随机种子的最佳方法是什么? [英] Best way to revert to a random seed after temporarily fixing it?

查看:63
本文介绍了临时修复后恢复随机种子的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是取消种子"随机数生成器的唯一方法:

Is this the only way to 'unseed' the random number generator:

np.random.seed(int(time.time()))

如果您希望某个循环中的某些代码与每个循环中希望随机的其他代码可重复(例如测试),那么在设置种子后如何将其重置"为随机数生成器?

If you have some code that you want to be repeatable (e.g. a test) in a loop with other code that you want to be random each loop, how do you 'reset' the seed to random number generator after setting it?

以下代码说明了该问题:

The following code illustrates the issue:

import numpy as np

def test():
    np.random.seed(2)
    print("Repeatable test:", [np.random.randint(10) for i in range(3)])

for i in range(4):
    print("Random number:", np.random.randint(10))
    test()

Random number: 8
Repeatable test: [8, 8, 6]
Random number: 2
Repeatable test: [8, 8, 6]
Random number: 2
Repeatable test: [8, 8, 6]
Random number: 2
Repeatable test: [8, 8, 6]

期望的结果:我希望随机数在每个循环中都是随机的.

Desired result: I want random number to be random each loop.

如果这是导入时间模块的唯一方法,我很高兴,但是我认为可能会有一种更简单,更强大的方法.

I am happy to import the time module if this is the only way to do it but I thought there might be a simpler, more robust way.

(您不能根据推荐答案

您走错了路.与其尝试取消numpy.random使用的全局RNG的种子,不如使用

You're going down the wrong path. Instead of trying to unseed the global RNG used by numpy.random, use a separate RNG for the parts that need to be repeatable. This RNG can have a completely independent state from the numpy.random default RNG:

def test():
    rng = numpy.random.RandomState(2)
    print("Repeatable test:", [rng.randint(10) for i in range(3)])


尽管从技术上讲可以保存和恢复全局numpy.random RNG的状态,但这是一个非常专业的操作,很少是一个好主意.例如,如果您要调试一段代码,并且想要在向后跳转代码后倒带"随机状态,则可能会很有用,尽管您需要提前保存状态,并且它不会倒带任何其他随机数生成器:


While it is technically possible to save and restore the state of the global numpy.random RNG, it is a very specialized operation and rarely a good idea. It may be useful, for example, if you're debugging a piece of code and you want to "rewind" the random state after jumping backward through the code, though you need to save the state in advance, and it won't rewind any other random number generators:

# Don't abuse this.
state = numpy.random.get_state()
do_stuff()
numpy.random.set_state(state)

这篇关于临时修复后恢复随机种子的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆