我正在播种随机数生成器以获得可重现的结果:
import random
SEED = 32412542
random.seed(SEED)
我想让它只为程序的一部分返回“不可重现”的随机值,如下所示:
import random
SEED = 32412542
random.seed(SEED)
my_list = [1, 2, 3, 4, 5]
res = random.sample(my_list, len(my_list)) # I would like result of this to be the same between runs of the program.
# Do some reproducible calculations, such as training neural network.
print(res) # E.g. prints [3, 2, 4, 1, 5]
# What to do here?
res = random.sample(my_list, len(my_list)) # I would like result of this to be different between runs.
# Do some non-reproducible calculations, such as picking neural network parameters randomly.
print(res) # Prints some random order.
res = random.sample(my_list, len(my_list)) # I would like result of this to be the same between runs of the program.
# Do some reproducible calculations, such as training neural network.
print(res) # E.g. prints [2, 3, 1, 4, 5]
到目前为止,我想到的是在我希望它变得不可重现之前不使用任何参数进行播种,然后使用 SEED
值重新播种:
import random
SEED = 32412542
random.seed(SEED)
my_list = [1, 2, 3, 4, 5]
res = random.sample(my_list, len(my_list))
print(res) # Prints: [3, 2, 4, 1, 5]
random.seed()
res = random.sample(my_list, len(my_list))
print(res) # Prints some random order.
random.seed(SEED)
res = random.sample(my_list, len(my_list))
print(res) # Prints: [3, 2, 4, 1, 5], so exactly what has been printed before.
问题是,重新播种后,会产生完全相同的一组随机值(显然 - 最终这就是使用特定值进行播种的目的),这是我不希望发生的情况。我想以某种方式恢复随机生成器之前的状态。这可能吗?
最佳答案
您无法使用random
函数来执行此操作,但可以通过创建Random
类的实例来执行此操作。 As the documentation states:
Class
Random
can also be subclassed if you want to use a different basic generator of your own devising: in that case, override therandom()
,seed()
,getstate()
, andsetstate()
methods. Optionally, a new generator can supply a getrandbits() method — this allows randrange() to produce selections over an arbitrarily large range.
示例:
>>> import random
>>> r = random.Random()
>>> r.randint(1, 1000)
545
>>> r.randint(1, 1000)
349
>>> r.randint(1, 1000)
745
>>> r.randint(1, 1000)
792
>>> state = r.getstate()
>>> r.randint(1, 1000)
52
>>> r.randint(1, 1000)
799
>>> r.randint(1, 1000)
586
>>> r.randint(1, 1000)
581
>>> r.setstate(state)
>>> r.randint(1,1000)
52
>>> r.randint(1,1000)
799
>>> r.randint(1,1000)
586
>>> r.randint(1,1000)
581
<小时/>
实际上you can even using the functions from the random
module ,我的错:
random.getstate()
Return an object capturing the current internal state of the generator. This object can be passed tosetstate()
to restore the state.
random.setstate(state)
state should have been obtained from a previous call togetstate()
, andsetstate()
restores the internal state of the generator to what it was at the timegetstate()
was called.
关于python - 如何 "stash"随机状态生成器状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58894758/