python3:标准化转移概率矩阵

python3: normalize matrix of transition probabilities

我有一个 Python 代码部分借自 :

# xstates is a dictionary
# n - is the matrix size
def prob(xstates, n):
    # we want to do smoothing, so create matrix of all 1s
    M = [[1] * n for _ in range(n)]

    # populate matrix by (row, column)
    for key, val in xstates.items():
        (row, col) = key
        M[row][col] = val

    # and finally calculate probabilities
    for row in M:
        s = sum(row)
        if s > 0:
            row[:] = [f/s for f in row]

    return M

xstates 这里以字典的形式出现,例如:

{(2, 2): 387, (1, 2): 25, (0, 1): 15, (2, 1): 12, (3, 2): 5, (2, 3): 5, (6, 2): 4, (5, 6): 4, (4, 2): 2, (0, 2): 1}

其中 (1, 2) 表示状态 1 过渡到状态 2,与其他状态类似。

此函数生成转移概率矩阵,一行中所有元素的总和为1。现在我需要对值进行归一化。我该怎么做?我可以使用 numpy 图书馆吗?

import numpy as np
M = np.random.random([3,2])
print(M)

行总和为 1

M = M / M.sum(axis=1)[:, np.newaxis]
print(M)

列总和为 1

M = M / M.sum(axis=0)[np.newaxis,:]
print(M)