Best way to revert to a random seed after temporarily fixing it?

霸气de小男生 提交于 2020-05-15 03:54:24

问题


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.

(You can't get the current seed according to this post)


回答1:


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)])

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)



回答2:


Another way to do this

  • You could generate random seeds for each loop respectively, but you would get the same seed value after the first iteration if you generate them inside the loop.
  • To avoid the seeds in each loop from being all the same, just generate different seeds outside the loop beforehand.
import numpy as np

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

n_loop = 4
max_rand_int = 1000*n_loop # i think this is enough
seeds = np.random.randint(max_rand_int, size=n_loop) # make list of seeds
for i in range(n_loop):
    print("Random number:", np.random.randint(10))
    test()
    seed = seeds[i]
    np.random.seed(seed)


来源:https://stackoverflow.com/questions/52544935/best-way-to-revert-to-a-random-seed-after-temporarily-fixing-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!