维比特算法实际是用动态规划解马尔可夫模型的预测问题,即用动态规划求最大概率问题·,这时一条路径对于着一个状态序列。
算法如下:
def viterbi(i,n,t):
if t==0:
return p[i]*b[i,o[0]],''
max_d=[]
for j in range(n):
max_d.append(viterbi(j,n,t-1)[0]*a[j,i])
m=max_d.index(max(max_d))
return max(max_d)*b[i,o[t]],str(viterbi(m,n,t-1)[1])+str(m+1)
测试代码:
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=[0,1,0,1]
p=[0.2,0.4,0.4]
print(viterbi(0,3,3))
print(viterbi(1,3,3))
print(viterbi(2,3,3))
输出结果:
(0.0018899999999999998, '321')
(0.0030239999999999993, '322')
(0.0022049999999999995, '333')