Skip to main content
 首页 » 编程设计

python之随机选择多选选项

2025年05月04日9jirigala

我想从一组选项中选择多个项目。每个选项都有自己的一组被选中或未被选中的概率。

狐狸例子:
选择,"is",“否”
“九月”,0.90,0.10
"十月", 0.25, 0.75
"十一月", 0.45, 0.55
"十二月", 0.50, 0.50

“yes”表示选项被选中,“no”表示未选中。因此,对于第一卷,选择可能是 ["September", "December"],对于第二卷,选择可能是 ["September", "October", "November"] 等等。

它类似于复选框选择,其中选择或不选择一个选项独立于其他选项。

我可以通过 numpy.random.choice 循环进入每个给定的选择来做到这一点。但我想知道是否有更优雅/更高效的方式来做到这一点?

这是我做的

choices = { 
    "September":0.90, 
    "October":0.25, 
    "November":0.45, 
    "December":0.50 
} 
 
resp = [] 
for ch, pr in choices: 
    pick = 1 
    probs = [pr, 1-pr] 
    select = ["yes", "no"] 
    choose = numpy.random.choice(select, pick, probs) 
    if "yes" in choose[0]: 
        resp.append(ch) 

谢谢。

请您参考如下方法:

您可以使用 numpy.random.uniform 函数生成区间 [0,1] 中的样本。通过将这些与 choices 中的概率进行比较,您可以创建具有指定概率的随机样本。由于自动广播,每一列都与 choices 中的相应概率进行比较。

这样你就可以创建一个维度为 (n_rolls, n_choices) 的矩阵,其中 n_rolls 是你想要重复的次数(这可以是 1 如果你只需要一个样本),n_choices 是不同选择的数量。

import numpy 
from collections import OrderedDict 
 
choices = OrderedDict() 
choices["September"] = 0.90 
choices["October"] = 0.25 
choices["November"] = 0.45 
choices["December"] = 0.50 
 
n_rolls = 5 
probs = numpy.random.uniform(size=(n_rolls, len(choices))) 
samples = probs < choices.values() 

结果将是一个 bool 数组,其中每一列对应于 choices 中的一个选项,每一行包含一次尝试。由于我们使用了 OrderedDict,结果将按照您输入字典数据的方式排序。

>>> samples 
array([[False, False, False, False], 
       [ True,  True,  True, False], 
       [ True, False, False, False], 
       [ True, False,  True,  True], 
       [ True, False,  True, False]], dtype=bool) 

作为测试:让我们找出 n_rolls=1000000 的每一列的概率:

>>> numpy.mean(samples, axis=0) 
array([ 0.899713,  0.249405,  0.449437,  0.499881]) 

要将此结果转换为您指定的列表,您可以结合使用 numpy.where 和 numpy.choose:

res = numpy.choose(numpy.where(samples[0, :]), choices.keys()) 
 
print samples[0,:],'\n',res 
[ True False  True  True]  
[['September' 'November' 'December']] 

不幸的是,这部分只适用于单行,所以如果你有多个卷,你需要循环执行最后一步。