如何使用 numpy 有效地查找转换矩阵中的状态变化?

How to efficiently lookup state changes in a transition matrix with numpy?

我正在用马尔可夫链做一些工作,我需要从给定一系列状态变化的转移矩阵中查找转移概率。如何在 numpy 中有效地做到这一点?

例如:

import numpy as np

#here is the sequence that I need to look up in the transition matrix
sequence = [0, 1, 0, 1, 1]

#the transition matrix that gives the probability to change between each 
of the states
transition_matrix = np.array([[0.2, 0.8], [0.6, 0.4]])

#desired output
result = [0.8, 0.6, 0.8, 0.4]

所以结果就是在转移矩阵中查找的概率值。当状态很多,序列很长时,如何高效地做到这一点?

谢谢。

只需使用zip:

result = []
for (step, next_step) in zip(sequence[:-1], sequence[1:]):
    result.append(transition_matrix[step][next_step])

结果:

[0.8, 0.6, 0.8, 0.4]