统计学习方法第10章隐马尔可夫模型Viterbi算法例10.3代码实践

统计学习方法第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
 

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值