我正在学习隐马尔可夫模型及其对股票价格预测的实现。我正在尝试根据本文实现前向算法。
在这里,我找到了 Python 中前向算法的实现。
import pandas as pd
import numpy as np
V = np.array([0, 1, 1, 2, 0, 1, 2, 0, 1, 0, 2])
# Transition Probabilities
a = np.array(((0.54, 0.46), (0.49, 0.51)))
# Emission Probabilities
b = np.array(((0.16, 0.26, 0.58), (0.25, 0.28, 0.47)))
# # Equal Probabilities for the initial distribution
pi = np.array((0.5, 0.5))
def forward(V, a, b, pi):
alpha = np.zeros((V.shape[0], a.shape[0]))
alpha[0, :] = initial_distribution * b[:, V[0]]
for t in range(1, V.shape[0]):
for j in range(a.shape[0]):
alpha[t, j] = alpha[t - 1].dot(a[:, j]) * b[j, V[t]]
return alpha
alpha = forward(V, a, b, pi)
但在我看来,它不包括算法中的 (c) 和 (d) 步骤。所以我添加了它们:
def forward(V, a, b, pi):
p = 1
alpha = np.zeros((V.shape[0], a.shape[0]))
alpha[0, :] = pi * b[:, V[0]]
for t in range(1, V.shape[0]):
probability_of_observation = 0 #my code
for j in range(a.shape[0]):
alpha[t, j] = alpha[t - 1].dot(a[:, j]) * b[j, V[t]]
probability_of_observation += alpha[t, j] #my code
p = p * probability_of_observation #my code
return p #changed
p = forward(V, a, b, pi) #changed
我的代码是否与给定的算法一致?
