统计学习方法第10章隐马尔可夫模型Viterbi算法例10.3代码实践
from numpy import *
def calcNextFunc(alpha,feat,A,B,O,n):
nextAlpha=mat(zeros((n,1)))
Idict={}
for i in range(n):
midMatr=multiply(alpha,A[:,i].T).tolist()[0] #计算书上对应的公式10.46等式的右边
#print(midMatr)
value=max(midMatr)
#print(value)
nextAlpha[i]=value
Idict[i+1]=midMatr.index(value)+1 #这个字典对应每个状态的最优路径
nextAlpha=multiply(nextAlpha,B[:,V.index(O[feat])]).T #这个计算10.45的矩阵
return nextAlpha,Idict
#为了迎合书上对最优路径的列的定义这里都在列的相应索引上加1
def calcResult(alpha,Idict,m):
IList=[]
alphaList=alpha.tolist()[0]
maxIndex=alphaList.index(max(alphaList))+1
IList.append(maxIndex)
for i in range(m-1,0,-1):
maxIndex=Idict[i][maxIndex]
IList.append(maxIndex)
return IList
def viterbi(V,A,B,Pi,O):
m=len(O)
n=shape(Pi)[1]
Idict={}
alpha=multiply(Pi,B[:,V.index(O[0])].T)
for i in range(1,m):
alpha,subDict=calcNextFunc(alpha,i,A,B,O,n)
Idict[i]=subDict
return calcResult(alpha,Idict,m)
V=['红','白']
A=mat([[0.5,0.2,0.3],[0.3,0.5,0.2],[0.2,0.3,0.5]])
B=mat([[0.5,0.5],[0.4,0.6],[0.7,0.3]])
Pi=mat([0.2,0.4,0.4])
O=['红','白','红']
print(viterbi(V,A,B,Pi,O))
结果如下:
[3, 3, 3]
好像算法略显复杂,数据结构没学好可能就会这样吧0.0
made by zcl at CUMT
I know I can because I have a heart that beats