【问题标题】:random.choices() in pythonpython中的random.choices()
【发布时间】:2019-10-17 01:27:45
【问题描述】:

我想确认一下

a = [random.choices([0,1],weights=[0.2,0.8],k=1) for i in range(0,10)] 

在概率上与

做同样的事情
a = random.choices([0,1],weights=[0.2,0.8],k=10) 

特别是,我希望双方都能从集合 {0,1} 中以 0.2 的概率和 1 的概率 0.8 进行 10 次独立抽签。这是对的吗?

谢谢!

【问题讨论】:

  • 您认为有什么特别的原因吗?文档看起来很清楚。
  • 如果您有特定原因认为行为可能不同,我们可以针对该原因给出更有用的答案,而不是仅仅说“是”并期望您和未来的读者信任我们。
  • 谢谢大家。我之所以这么问,是因为我使用这种方法进行了大约 360 次绘制,并观察到了一个非常不可能的结果:在数据按预期生成的假设下,大约是 1/3000。所以我只是想确保这种方法不会以某种方式影响抽签的独立性。

标签: python random


【解决方案1】:

documentation 似乎表明两者在概率上是相同的,并且在运行以下实验后:

from collections import defaultdict
import pprint
import random

results1 = defaultdict(int)
results2 = defaultdict(int)

for _ in range(10000):
    a = [random.choices([0,1],weights=[0.2,0.8],k=1) for i in range(0,10)]
    for sublist in a:
        for n in sublist:
            results1[n] += 1

for _ in range(10000):
    a = random.choices([0,1],weights=[0.2,0.8],k=10)
    for n in a:
        results2[n] += 1


print('first way 0s: {}'.format(results1[0]))
print('second way 0s: {}'.format(results2[0]))
print('first way 1s: {}'.format(results1[1]))
print('second way 1s: {}'.format(results2[1]))

我看到这两种方法的结果非常相似。

【讨论】:

    【解决方案2】:

    正如其他人所提到的,documentation 在这方面很清楚,您可以通过在每次调用之前设置种子来进一步验证,例如:

    import random
    
    random.seed(42)
    print([random.choices([0, 1], weights=[0.2, 0.8], k=1)[0] for i in range(0, 10)])
    
    random.seed(42)
    print(random.choices([0, 1], weights=[0.2, 0.8], k=10))
    

    输出

    [1, 0, 1, 1, 1, 1, 1, 0, 1, 0]
    [1, 0, 1, 1, 1, 1, 1, 0, 1, 0]
    

    进一步设置一次,确实会导致不同的结果,正如人们所期望的那样:

    random.seed(42)
    print([random.choices([0, 1], weights=[0.2, 0.8], k=1)[0] for i in range(0, 10)])
    print(random.choices([0, 1], weights=[0.2, 0.8], k=10))
    

    输出

    [1, 0, 1, 1, 1, 1, 1, 0, 1, 0]
    [1, 1, 0, 0, 1, 1, 1, 1, 1, 0]
    

    【讨论】:

      猜你喜欢
      • 2021-11-18
      • 2019-08-21
      • 2019-04-12
      • 2022-11-27
      • 2020-10-10
      • 2021-01-17
      • 2021-08-24
      • 2022-11-29
      • 2020-05-02
      相关资源
      最近更新 更多