【问题标题】:In python, how should i Weighted-random coding?在python中,我应该如何加权随机编码?
【发布时间】:2018-10-28 10:56:10
【问题描述】:

我想知道Python中加权随机的方法。

1:10%、2:10%、3:10%、4:50%、5:20%

然后我选择不重复的随机数。我应该如何编码?一般来说,我们会在下面写代码:

Python

from random import *
sample(range(1,6),1)

【问题讨论】:

标签: python python-3.x


【解决方案1】:

您应该查看 random.choices (https://docs.python.org/3/library/random.html#random.choices),如果您使用的是 python 3.6 或更新版本,您可以定义权重

例子:

import random
choices = [1,2,3,4,5]
random.choices(choices, weights=[10,10,10,50,20], k=20)

输出:

[3, 5, 2, 4, 4, 4, 5, 3, 5, 4, 5, 4, 5, 4, 2, 4, 5, 2, 4, 4]

【讨论】:

  • 是不是没有重复?
【解决方案2】:

试试这个:

from numpy.random import choice
list_of_candidates = [1,2,5,4,12]
number_of_items_to_pick = 120 
p = [0.1, 0, 0.3, 0.6, 0]
choice(list_of_candidates, number_of_items_to_pick, p=probability_distribution)

【讨论】:

    【解决方案3】:

    如果您真的想要一个示例版本,您可以相应地准备范围:

    nums = [1,2,3,4,5]
    w = [10,10,10,50,20] # total of 100%
    
    d = [x for y in ( [n]*i for n,i in zip(nums,w)) for x in y]
    a_sample = random.sample(d,k=5)
    print(a_sample)
    print(d)
    

    输出:

    # 5 samples
    [4, 2, 3, 1, 4]
    
    # the whole sample input:
    [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 
     4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 
     4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 
     5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
    

    如果您只需要 1 个号码,您可以使用 random.choices - 它仅限于 1 个号码,因为它的绘图可以替换。

    import random
    from collections import Counter
    
    # draw and count 10k to show distribution works
    print(Counter( random.choices([1,2,3,4,5], weights=[10,10,10,50,20], k=10000)).most_common())
    

    输出:

    [(4, 5019), (5, 2073), (3, 1031), (1, 978), (2, 899)]
    

    使用没有替换的“样本”和“加权”(对我来说)很奇怪 - 因为您会更改每个连续数字的权重,因为您从范围中删除了可用数字(这是凭感觉 - 我的猜测是背后的数学告诉我不是这样)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-24
      • 2012-10-14
      • 1970-01-01
      • 1970-01-01
      • 2011-09-19
      • 1970-01-01
      • 2022-07-06
      • 1970-01-01
      相关资源
      最近更新 更多