作者:wgol992015 | 来源:互联网 | 2023-05-16 20:12
参考李航《统计学习基础的》的公式推导
PI = np.array([0.2, 0.4, 0.4])
A = np.array([[0.5, 0.2, 0.3], [0.3, 0.5, 0.2], [0.2, 0.3, 0.5]])
B = np.array([[0.5, 0.5], [0.4, 0.6], [0.7, 0.3]])
O = [1, 2, 1] # 观测序列
def viterbi(PI, A, B, O): # 维特比算法
T = len(O) # 观测序列的数目
N = len(PI) # 所有可能的状态个数
deta = PI * B[:, O[0] - 1] # 初始
pusai = np.zeros((T, N))
seq = np.zeros(T) # 最优状态序列
print deta, pusai[0]
for t in range(1, T):
tmp = [(deta * A[:, i]).tolist() for i in range(3)]
pusai[t] = np.argmax(tmp, axis=1).tolist()
deta = [max(deta * A[:, i]) for i in range(N)] * B[:, O[t] - 1]
print deta, pusai[t]
i = np.argmax(deta) # 从最后一个开始回溯
seq[-1] = int(i)
pusai = np.mat(pusai)
for t in range(T - 1, 0, -1):
i = pusai[t, i]
seq[t - 1] = i
return seq