我希望将状态更改应用于具有k个类别的大型分类矩阵(M),其中我知道k(T)中每个类别到另一个类别的转换概率
基本上,我希望能够有效地获取M中的每个元素,根据T中的概率模拟状态变化,并使用计算出的变化替换该元素。
我尝试了一些解决方案:
import numpy as np
def categorical_transition(mat, t_mat, k=4):
transformed_mat = mat.copy()
cat_counts = np.bincount(mat.reshape(-1,))
for i in range(k):
rand_vec = np.random.multinomial(1, t_mat[i], cat_counts[i])
choice = np.where(rand_vec)[1]
transformed_mat[mat == i] = choice
return transformed_mat
# load data
mat = np.random.choice(4, (16000, 256))
t_mat = np.random.random((4, 4))
# normalize transition matrix
for i in range(t_mat.shape[0]):
t_mat[i] = t_mat[i] / t_mat[i].sum()
transformed_mat = categorical_transition(mat, t_mat)
此方法有效,但速度较慢,我希望您能以更有效的方式提出建议
答案 0 :(得分:1)
始终提供您到目前为止尝试过的所有实施方式
例如,我尝试了一种简单的实现,描述为here.,具体取决于您有多少个内核,它应该比解决方案快20-80倍。
实施
@nb.njit(parallel=True)
def categorical_transition_nb(mat_in, t_mat):
mat=np.reshape(mat_in,-1)
transformed_mat = np.empty_like(mat)
for i in nb.prange(mat.shape[0]):
rand_number=np.random.rand()
probabilities=t_mat[mat[i],:]
if rand_number<probabilities[0]:
transformed_mat[i]=0
else:
for j in range(1,probabilities.shape[0]):
if rand_number>=probabilities[j-1] and rand_number<probabilities[j]:
transformed_mat[i]=j
return transformed_mat.reshape(mat_in.shape)
时间
import numpy as np
import numba as nb
# load data
mat = np.random.choice(4, (16_000,256))
t_mat = np.random.random((4, 4))
# normalize transition matrix
for i in range(t_mat.shape[0]):
t_mat[i] = t_mat[i] / t_mat[i].sum()
t_mat_2=np.cumsum(t_mat,axis=1)
%timeit transformed_mat_2 = categorical_transition_nb(mat, t_mat_2)
21.7 ms ± 1.85 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
答案 1 :(得分:0)
这是一种使示例速度提高5倍的方法
context!!
样品运行:
import numpy as np
def categorical_transition(mat, t_mat, k=4):
transformed_mat = mat.copy()
cat_counts = np.bincount(mat.reshape(-1,))
for i in range(k):
rand_vec = np.random.multinomial(1, t_mat[i], cat_counts[i])
choice = np.where(rand_vec)[1]
transformed_mat[mat == i] = choice
return transformed_mat
def pp(mat,t_mat):
ps = t_mat.cumsum(1)
ps /= ps[:,-1:]
return (np.random.random(mat.shape+(1,))<ps[mat]).argmax(-1)
# load data
mat = np.random.choice(4, (16000, 256))
t_mat = np.random.random((4, 4))
# normalize transition matrix
for i in range(t_mat.shape[0]):
t_mat[i] = t_mat[i] / t_mat[i].sum()
transformed_mat = categorical_transition(mat, t_mat)
transformed_mat_pp = pp(mat, t_mat)
# check correctness
from pprint import pprint
np.set_printoptions(3)
cnts = np.bincount(mat.ravel())
pprint([[np.bincount(tm[mat==i])/cnts[i] for tm in (transformed_mat,transformed_mat_pp)] + [t_mat[i]] for i in range(4)])
from timeit import timeit
print('OP',timeit(lambda:categorical_transition(mat, t_mat),number=10)*100,'ms')
print('pp',timeit(lambda:pp(mat, t_mat),number=10)*100,'ms')