设P是一个数组,其中每行总和为1.如何生成矩阵A
我怎么能在Numpy或Scipy中做到这一点?
我可以使用for循环来做,但这显然很慢。有没有办法使用Numpy来提高效率?还是Numba?
这跟随维基百科。
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.]])
好的,使用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]]