如何应用numpy随机.选择一个矩阵的概率值(矢量化解决方案)



我遇到的问题如下

我有一个1-D的整数列表(或np.array)有3个值

l = [0,1,2]

我有一个二维概率列表(为简单起见,我们将使用两行)

P = 
[[0.8, 0.1, 0.1],
 [0.3, 0.3, 0.4]]

我想要的是numpy.random.choice(a=l, p=P),其中p(概率分布)中的每一行都应用于1。因此,我想用probb从[0,1,2]中随机抽取一个样本。Dist .[0.8, 0.1, 0.1]先,再用prob。Dist .[0.3, 0.3, 0.4]接下来,给我两个输出。

=====更新======

我可以使用for循环或列表推导,但我正在寻找一个快速/矢量化的解决方案。

有一个办法。

这是概率数组:

In [161]: p
Out[161]: 
array([[ 0.8 ,  0.1 ,  0.1 ],
       [ 0.3 ,  0.3 ,  0.4 ],
       [ 0.25,  0.5 ,  0.25]])

c保持累积分布:

In [162]: c = p.cumsum(axis=1)

生成一组均匀分布的样本…

In [163]: u = np.random.rand(len(c), 1)

…然后看看它们"适合"在c:

In [164]: choices = (u < c).argmax(axis=1)
In [165]: choices
Out[165]: array([1, 2, 2])

这个问题相当老了,但可能有一个更优雅的解决方案:https://numpy.org/doc/stable/reference/random/generated/numpy.random.Generator.multinomial.html

(我调整了原始输入以作为DataFrame工作)。

# Define the list of choices
choices = ["a", "b", "c"]
# Define the DataFrame of probability distributions
# (In each row, the probabilities of a, b and c can be different)
df_probabilities = pd.DataFrame(data=[[0.8, 0.1, 0.1],
                                      [0.3, 0.3, 0.4]],
                                columns=choices)
print(df)
     a    b    c
0  0.8  0.1  0.1
1  0.3  0.3  0.4
# Generate a DataFrame of selections. In each row, a 1 denotes
# which choice was selected
rng = np.random.default_rng(42)
df_selections = pd.DataFrame(
    data=rng.multinomial(n=1, pvals=df_probabilities),
    columns=choices)
print(df_selections)
   a  b  c
0  1  0  0
1  0  1  0
# Finally, reduce the DataFrame to one column (actually pd.Series)
# with the selected choice
df_result = df_selections.idxmax(axis=1)
print(df_result)
0    a
1    b
dtype: object

相关内容

最新更新