大佬教程收集整理的这篇文章主要介绍了生成总和有限的随机权重数,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要生成一个由 [0,4] 之间的 8 个整数组成的随机列表,权重总和应为 12。
像这样:
from random import choices
while True:
lst = choices(population=[0,1,2,3,4],weights=[0.20,0.30,0.15,0.05],k=8)
if sum(lst) == 12:
print(lst)
break
有更聪明的方法来做到这一点吗?
Severin 的解决方案很简单,对于大部分参数空间应该很快,但在分布的边缘可能会变慢。例如,生成 30 个总和为 100 的值可能需要几秒钟,直到它随机偶然发现一个有效的解决方案
以下代码确保它仅从有效值中采样,因此具有更具确定性的运行时:
def sample_values(population,k,total,*,weights=None):
if weights is None:
# weights not probabilities,so no need to sum to 1
weights = [1] * len(population)
# ensure population is a sorted list,with weights in consistant order
population,weights = zip(*sorted(zip(population,weights)))
population = list(population)
weights = list(weights)
result = []
for _ in range(k):
# population values that would take us past the running total should be excluded
while population[-1] > total:
del population[-1]
del weights[-1]
# maintain k as the number of remaining items
k -= 1
# remove anything where just using it and then maximal values wouldn't get us to the total
remain_lim = total - max(population) * k
while population[0] < remain_lim:
del population[0]
del weights[0]
# sample next value
n,= choices(population,weights)
result.append(n)
# maintain total as the remaining total
total -= n
return result
对 tee
的第一次调用确实需要 strict=True
from Python 3.10,但我认为您还没有使用它而忽略了它
以上可以例如用作:
sample_values(range(5),8,12,weights=[0.20,0.30,0.15,0.05])
并在 ~12µs 内运行,这与 Severin 的 multinomial
解决方案相当,后者对这些参数需要 ~18µs。
您可以从 multinomial 中采样,它会自动获得正确的总和,并拒绝超出范围的值
同样,Python 3.9.1,Windows 10 x64
import numpy as np
rng = np.random.default_rng()
def smpl(rng):
while True:
q = rng.multinomial(12,[1./8.]*8)
if np.any(q > 4):
continue
return q
以上是大佬教程为你收集整理的生成总和有限的随机权重数全部内容,希望文章能够帮你解决生成总和有限的随机权重数所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。