【发布时间】:2019-11-17 04:20:18
【问题描述】:
我正在播种一个随机数生成器以获得可重现的结果:
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的实例,您应该能够.getstate()和.setstate() -
或者你使用两个“随机”对象,其中一个用种子初始化。
标签: python random random-seed