【发布时间】: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