gpt4 book ai didi

python - 后向算法隐马尔可夫模型,第 0 个索引(终止步骤)产生错误结果

转载 作者:行者123 更新时间:2023-12-01 07:25:42 25 4
gpt4 key购买 nike

我正在 PyTorch 中实现向后 HMM 算法。我用过这个link作为引用。此链接包含所使用的数值示例的结果(我正在尝试实现该示例并将生成的结果与其进行比较)。 第 3 页,第 2 节。后向概率,有一个包含计算结果的表格。

这是我的代码:

# Initial Transition matrix as shown in page 2 of above link
A = np.array([[0.6, 0.4], [0.3, 0.7]])
A = torch.from_numpy(A)
# Initial State Probability (page 2)
pi = np.array([0.8, 0.2])
pi = torch.from_numpy(pi)
# Output probabilities (page 2)
emission_matrix = np.array([[0.3, 0.4, 0.3, 0.3], [0.4, 0.3, 0.3, 0.3]])
emission_matrix = torch.from_numpy(emission_matrix)
# Initialize empty 2x4 matrix (dimensions of emission matrix)
backward = torch.zeros(emission_matrix.shape, dtype=torch.float64)

# Backward algorithm
def _backward(emission_matrix):
# Initialization: A(i, j) * B(T, i) * B(Ot+1, j) , where B(Ot+1, j) = 1
backward[:, -1] = torch.matmul(A, emission_matrix[:, -1])
# I reversed the emission matrix so as to start from the last column
rev_emission_mat = torch.flip(emission_matrix[:, :-1], [1])
# I transposed the reversed emission matrix such that each iterable in the for
# loop is the observation sequence probability
T_rev_emission_mat = torch.transpose(rev_emission_mat, 1, 0)
# This step is so that I assign a reverse index enumeration to each iterable in the
# emission matrix starts from time T to 0, rather than the opposite
zipped_cols = list(zip(range(len(T_rev_emission_mat)-1, -1, -1), T_rev_emission_mat))

for i, obs_prob in zipped_cols:
# Induction: Σ A(i, j) * B(j)(Ot+1) * β(t+1, j)
if i != 0:
backward[:, i] = torch.matmul(A * obs_prob, backward[:, i+1])
# Termination: Σ π(i) * bi * β(1, i)
backward[:, 0] = torch.matmul(pi * obs_prob, backward[:, 1])

# run backward algorithm
_backward(emission_matrix)
# check results, backward is an all zero matrix that was initialized above
print(backward)
>>> tensor([[0.0102, 0.0324, 0.0900, 0.3000],
[0.0102, 0.0297, 0.0900, 0.3000]], dtype=torch.float64)

如您所见,第 0 个索引与上一个 link 第 3 页的结果不匹配。我做错了什么?如果有什么我可以澄清的,请告诉我。提前致谢!

最佳答案

backward[:, 0] = pi * obs_prob * backward[:, 1]

关于python - 后向算法隐马尔可夫模型,第 0 个索引(终止步骤)产生错误结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57466547/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com