admin管理员组文章数量:1435859
I have a non-negative normalized vector p
. I would like to sample an index from the index set of the vector. The probability getting sample k
is p[k]
. Using np.random.choice
function, I can write the following code.
p = [0.2, 0.3, 0.1, 0.3, 0.1]
indices = np.arange(len(p))
k = np.random.choice(indices, p=p)
My question is, how can I generalize this code for multi-dimensional arrays? For example, given three dimensional non-negative normalized IxJxK tensor p = np.random.rand(I,J,K)
how can I sample the index (i,j,k) with the probability p[i,j,k]
?
I have a non-negative normalized vector p
. I would like to sample an index from the index set of the vector. The probability getting sample k
is p[k]
. Using np.random.choice
function, I can write the following code.
p = [0.2, 0.3, 0.1, 0.3, 0.1]
indices = np.arange(len(p))
k = np.random.choice(indices, p=p)
My question is, how can I generalize this code for multi-dimensional arrays? For example, given three dimensional non-negative normalized IxJxK tensor p = np.random.rand(I,J,K)
how can I sample the index (i,j,k) with the probability p[i,j,k]
?
1 Answer
Reset to default 2Suppose that x
is a probability matrix:
x = np.random.random((3, 4, 5))
x /= np.sum(x)
You can use flatten(x)
and np.random.choice()
to get values in the range 0..3x4x5 with the associated probabilities:
flat = x.flatten()
temp = np.random.choice(np.arange(len(flat)), 10, p=flat)
print(temp)
You can now convert the indices in temp
into indices in the original array:
np.unravel_index(temp, x.shape))
Note that this will return a tuple of three numpy arrays, with the first array being the first index, the second element being the second index, and so on.
本文标签: Sampling from joint probability mass function in pythonStack Overflow
版权声明:本文标题:Sampling from joint probability mass function in python - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745667821a2669387.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论