我正在播种一个随机数生成器,以产生可重复的结果:
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
类的实例来执行此操作。如文档所述:
类
Random
也可以,如果你想用你自己设计的不同的基本发电机子类:在这种情况下,覆盖random()
,seed()
,getstate()
,和setstate()
方法。可选地,新的生成器可以提供getrandbits()方法-这允许randrange()产生任意大范围内的选择。
例:
>>> 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
实际上,您甚至可以使用random
模块中的功能,这很糟糕:
random.getstate()
返回一个捕获生成器当前内部状态的对象。可以传递该对象setstate()
以恢复状态。
random.setstate(state)
状态应该已经从先前对的调用中获得getstate()
,并将setstate()
生成器的内部状态恢复到调用时的状态getstate()
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句