我想知道Python中加权随机的方法。
1:10%,2:10%,3:10%,4:50%,5:20%
然后,我选择不重复的随机数。我应该如何编码?通常,我们将在下面进行编码:
Python
from random import *
sample(range(1,6),1)
答案 0 :(得分: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]
答案 1 :(得分:0)
如果您确实想要样本版本,则可以相应地准备范围:
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)]
对我来说,使用不带替换的“样本”和“加权”是很奇怪的-因为您将更改每个连续数字的权重,因为您已从范围中删除了可用数字(按感觉,我的猜测是后面的数学告诉我事实并非如此。
答案 2 :(得分:0)
尝试一下:
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)