HMM study: Viterbi 算法的Python简单实现

# viterbi algorithm(pi,A,B)

import numpy as np
# -*- codeing:utf-8 -*-
__author__ = 'Vera'

Hmm_ob= [0, 1,2]
Hmm_hdn=['runny', 'rainy']
A=np.array([[0.7, 0.3], [0.4, 0.6]])
B=np.array([[0.1, 0.4, 0.5], [0.6, 0.3, 0.1]])
Hmm_pi=[0.6, 0.4]
real_ob= [0, 1, 2,1,0,0,2,1,1,2]


def HMM_compute (obser):
    N=len(obser) # N means the time
    max_sita=np.zeros((len(Hmm_hdn),len(obser)))#This is the max seta for each state
    # Each max state should come from some
    max_index = np.zeros((len(Hmm_hdn),len(obser)),dtype=int)
    path=np.array(len(obser),dtype=int)
    prob=np.zeros(len(Hmm_pi))
    for i in range(len(Hmm_hdn)):
        max_sita[i][0]=Hmm_pi[i]*B[i][obser[0]]
        max_index[i][0]=i

    for k in range(1,N):
        for i in range(len(Hmm_pi)):
            for j in range(len(Hmm_hdn)):
                prob[j]=max_sita[j][k-1]*A[j][i]*B[i][obser[k]]
            a=np.where(prob == np.max(prob))
            max_sita[i][k]=np.max(prob)
            max_index[i][k]=a[0]
# get path
    path=np.zeros(N)
    a = np.where(max_sita[:,N-1] == np.max(max_sita[:,N-1]))
    path[N - 1] = a[0]
    for i in range(N - 1):
        aa = int(path[N - 1 - i])
        path[N - 2 - i] = max_index[aa][N - 1 - i]

    return path

aaa=HMM_compute(real_ob)
for i in range(len(aaa)):
    print(Hmm_hdn[int(aaa[i])])

参考了部分代码,但是找不到了。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值