根据概率权重随机返回一个值 [英] Returning a value at random based on a probability weights
问题描述
可能的重复:
random.choice 的加权版本
为了简单起见,我们假设一个函数接受 4 个输入:2 个名称和它们各自的偏差/权重",我该如何编写函数使其返回 a
或 b
随机但仍将这些权重考虑到随机结果中.
Let's say for simplicity a function takes in 4 inputs: 2 names and their respective 'bias/weights', how can I write a function such that it returns either a
or b
at random but still considers those weights into the random outcome.
a = 'x'
b = 'y'
p_a = 10
p_b = 90
def myRand(a, p_a, b, p_b):
return 'x' 10% of the time, 'y' 90% of time
到目前为止我所做的
import random
def myRand(a, p_a, b, p_b):
probs = [a]*p_a + [b]*p_b
return random.choice(probs)
有人可以指出为什么这是不正确的或不是最佳答案吗?我的理由是我假设每个元素被选中的概率相同,所以结果应该仍然有利于 10:90.或者我们可以在使用 random.choice()
之前对数组进行洗牌?
Can someone point why this is an incorrect or not the best answer? My justification is that I'm assuming every element has the same probability of being picked so the outcome should still favor 10:90. Or maybe we can shuffle the array before using random.choice()
?
有没有更好的方法来做到这一点?也许我在这里遗漏了一些明显的东西,或者这是正确的吗?
Is there a better way to do this? Maybe I'm missing something obvious here or is this correct?
谢谢
推荐答案
我修改了该函数以接受任意数量的输入和加权概率,因此如果以后您决定要使用两个以上的输入,您可以.
I've modified the function to accept an arbitrary number of inputs and weighted probabilities so if later on you decide you want to use more than two inputs, you can.
import random
def myRand(i, w):
r = random.uniform(0, sum(w))
# loop through a list of inputs and max cutoff values, returning
# the first value for which the random num r is less than the cutoff value
for n,v in map(None, i,[sum(w[:x+1]) for x in range(len(w))]):
if r < v:
return n
示例用法:
inputs = ['e', 'f', 'g', 'h']
weights = [10, 30, 50, 10]
print myRand(inputs, weights)
这篇关于根据概率权重随机返回一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!