gpt4 book ai didi

python - 随机加权选择

转载 作者:太空狗 更新时间:2023-10-29 17:18:44 26 4
gpt4 key购买 nike

我有这样的数据:

d = (
(701, 1, 0.2),
(701, 2, 0.3),
(701, 3, 0.5),
(702, 1, 0.2),
(702, 2, 0.3),
(703, 3, 0.5)
)

其中 (701, 1, 0.2) = (id1, id2, priority)

如果我知道 id1,是否有一种使用优先级选择 id2 的漂亮方法?

Func(701) 应该返回:
1 - 在 20% 的情况下
2 - 30%
3 - 50%

百分比当然是粗略的

最佳答案

因此为每个 ID1 生成一个累积分布函数:

cdfs = defaultdict()
for id1,id2,val in d:
prevtotal = cdfs[id1][-1][0]
newtotal = prevtotal + val
cdfs[id1].append( (newtotal,id2) )

所以你会有

cdfs = { 701 : [ (0.2,1), (0.5,2), (1.0,3) ], 
702 : [ (0.2,1), (0.5,2) ],
703 : [ (0.5,3) ] }

然后生成一个随机数,在列表中搜索。

def func(id1):
max = cdfs[id1][-1][0]
rand = random.random()*max
for upper,id2 in cdfs[id1]:
if upper>rand:
return id2
return None

关于python - 随机加权选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2073235/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com