小编Nad*_*sha的帖子

马尔可夫转移概率矩阵在 Python 中的实现

我正在尝试计算序列的一步、两步转移概率矩阵,如下所示:

sample = [1,1,2,2,1,3,2,1,2,3,1,2,3,1,2,3,1,2,1,2]
import numpy as np

def onestep_transition_matrix(transitions):
    n = 3 #number of states

    M = [[0]*n for _ in range(n)]

    for (i,j) in zip(transitions,transitions[1:]):
        M[i-1][j-1] += 1

    #now convert to probabilities:
    for row in M:
        s = sum(row)
        if s > 0:
            row[:] = [f/s for f in row]
    return M

one_step_array = np.array(onestep_transition_matrix(sample))
Run Code Online (Sandbox Code Playgroud)

我的问题,我们如何计算两步转移矩阵。因为当我手动计算矩阵时,它如下所示:

two_step_array = array([[1/7,3/7,3/7],
                       [4/7,2/7,1/7],
                       [1/4,3/4,0]])
Run Code Online (Sandbox Code Playgroud)

然而。np.dot(one_step_array,one_step_arrary) 给了我一个不同的结果,如下所示:

array([[0.43080357, 0.23214286, 0.33705357],
   [0.43622449, 0.44897959, 0.11479592],
   [0.20089286, 0.59821429, 0.20089286]])
Run Code Online (Sandbox Code Playgroud)

请让我知道哪个是正确的。

python numpy matrix markov scipy

2
推荐指数
1
解决办法
3050
查看次数

标签 统计

markov ×1

matrix ×1

numpy ×1

python ×1

scipy ×1