问题描述
我遇到的问题如下
我有一个带有3个值的一维整数列表(或np.array)
I have a 1-D list of integers (or np.array) with 3 values
l = [0,1,2]
我有一个二维概率列表(为简单起见,我们将使用两行)
I have a 2-D list of probabilities (for simplicity, we'll use two rows)
P =
[[0.8, 0.1, 0.1],
[0.3, 0.3, 0.4]]
我想要的是numpy.random.choice(a=l, p=P)
,其中P(概率分布)中的每一行都应用于l.因此,我希望从带有概率的[0,1,2]中抽取一个随机样本. dist. [0.8,0.1,0.1]首先,然后是概率. dist. [0.3,0.3,0.4]接下来,给我两个输出.
What I want is numpy.random.choice(a=l, p=P)
, where each row in P (probability distribution) is applied to l. So, I want a random sample to be drawn from [0,1,2] with prob. dist. [0.8, 0.1, 0.1] first, then with prob. dist. [0.3, 0.3, 0.4] next, to give me two outputs.
=====更新======
===== Update ======
我可以用于循环或列表理解,但是我正在寻找一种快速/矢量化的解决方案.
I can use for loops or list comprehension, but I am looking for a fast/vectorized solution.
推荐答案
这是一种方法.
以下是几率:
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)
生成一组均匀分布的样本...
Generate a set of uniformly distributed samples...
In [163]: u = np.random.rand(len(c), 1)
...然后查看它们在c
中适合"的位置:
...and then see where they "fit" in c
:
In [164]: choices = (u < c).argmax(axis=1)
In [165]: choices
Out[165]: array([1, 2, 2])
这篇关于如何将numpy random.choice应用于概率值矩阵(矢量化解决方案)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!