【问题标题】:Why does numpy.random.Generator.choice gives different results even if given fixed seed?为什么 numpy.random.Generator.choice 即使给定固定种子也会给出不同的结果?
【发布时间】:2020-06-22 15:13:58
【问题描述】:

代码很简单:

import numpy
rng = numpy.random.default_rng(0)
control = rng.choice([0,1],p=[0.5,0.5])
for i in range(100):
    print(control == rng.choice([0,1],p=[0.5,0.5]))
# Not only True gets printed

可能我遗漏了一些东西,但我理解这一点的方式是 rng.choice,使用完全相同的参数运行,如果它被播种,应该总是返回相同的东西。 我错过了什么?

【问题讨论】:

    标签: python numpy random-seed numpy-random


    【解决方案1】:

    我想你可能误解了种子的用法。以下代码应始终输出True

    import numpy
    rng = numpy.random.default_rng(0)
    control = rng.choice([0,1],p=[0.5,0.5])
    for i in range(100):
        rng = numpy.random.default_rng(0)
        print(control == rng.choice([0,1],p=[0.5,0.5]))
    # Always True
    

    当我们使用相同的种子时,我们可以得到相同的随机数序列。这意味着:

    import numpy
    rng = numpy.random.default_rng(0)
    out = [rng.choice([0, 1], p=[0.5, 0.5]) for _ in range(10)] 
    

    out 每次运行时都应该相同,但out 中的值不同。

    【讨论】:

    • 你说得对,我误解了种子的作用(或者更准确地说,选择的工作原理)。这么简单的功能,你以为不用多解释,我来了。我担心p=[0.5,0.5] 会影响结果,这对我的工作不利。
    • 我以为我明白了,但我意识到我仍然得到奇怪的结果,这在上面的例子中并不明显。我问了new, more specific question,你愿意看看吗?
    【解决方案2】:

    据我了解随机数生成,每次使用相同的种子运行程序时,您应该得到相同的 100 个输出,但由于您从正​​态分布中采样,因此每个样本的结果应该不同。

    因此,每次运行此程序时,您应该始终得到相同的真假序列。

    我已经尝试过了,似乎至少可以做到这一点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-09
      • 1970-01-01
      • 1970-01-01
      • 2019-02-22
      • 2020-10-13
      • 2014-02-01
      • 2021-08-26
      • 1970-01-01
      相关资源
      最近更新 更多