【问题标题】:python3: normalize matrix of transition probabilitiespython3:归一化转移概率矩阵
【发布时间】:2020-03-28 13:08:20
【问题描述】:

我有一段从Generating Markov transition matrix in Python借来的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 库来做到这一点吗?

【问题讨论】:

    标签: python-3.x matrix probability normalization markov-chains


    【解决方案1】:
    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)
    

    【讨论】:

    • 感谢您的评论。你能解释一下第一个表达式中的 '[:, np.newaxis]' 是什么意思吗?
    • M.sum(axis=1) 返回一个一维数组,但是我们不能将一个矩阵除以一维数组,所以我们添加另一个维度,例如这里shape(3,)变成(3,1),和np.reshape(-1,1)一样
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-01
    • 1970-01-01
    • 2012-02-27
    • 1970-01-01
    • 2021-05-11
    • 1970-01-01
    相关资源
    最近更新 更多