如何使用Python从多个分类分发中进行采样

问题描述 投票:0回答:2

设P是一个数组,其中每行总和为1.如何生成矩阵A

  • A具有与P相同的维度,并且A_ {ij}等于1,概率为P_ {ij}
  • A每行中只有一个条目等于1,所有其他条目为零

我怎么能在Numpy或Scipy中做到这一点?

我可以使用for循环来做,但这显然很慢。有没有办法使用Numpy来提高效率?还是Numba?

python numpy random montecarlo
2个回答
0
投票

这跟随维基百科。

import numpy.random as rnd
import numpy as np

A_as_numbers = np.argmax(np.log(P) + rnd.gumbel(size=P.shape), axis=1)
A_one_hot = np.eye(P.shape[1])[A_as_numbers].reshape(P.shape)

测试它:

P = np.matrix([[1/4, 1/4, 1/4, 1/4], [1/3,1/3,1/6,1/6]])

拿到:

array([[ 1.,  0.,  0.,  0.],
       [ 0.,  1.,  0.,  0.]])

0
投票

好的,使用2d扩展选项

import numpy as np

def f(P):
    a = np.zeros(4, dtype=np.int64)
    q = np.random.choice(4, size=1, replace=True, p=P)
    a[q] = 1
    return a

P = np.array([[1/4, 1/4, 1/4, 1/4],
              [1/3,1/3,1/6,1/6]])

r = np.apply_along_axis(f, 1, P)
print(r)

[[0 0 0 1] [0 0 1 0]]

[[1 0 0 0] [0 1 0 0]]

© www.soinside.com 2019 - 2024. All rights reserved.