前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >维特比算法

维特比算法

作者头像
ke1th
发布2019-05-26 12:25:01
4260
发布2019-05-26 12:25:01
举报

统计学习方法 (李航) 维特比算法例题 的代码实现, (HMM 预测)

代码语言:javascript
复制
import numpy as np

num_hidden_states = 3
num_observations = 2 # 红, 黑
obs_map = {'红': 0, '白': 1}
# matrix[t-1, t] ===> t-1 --> t
transition_matrix = np.array([[.5, .2, .3],
                              [.3, .5, .2],
                              [.2, .3, .5]])

# state --> obs, prob
observation_matrix = np.array([[.5, .5],
                               [.4, .6],
                               [.7, .3]])

pi = np.array([.2, .4, .4])

# 红-->0, 白-->1
observation_sequence = ['红', '白', '红']

# viterbi
# initialize P(h1, o1) = p(h1) * p(o1|h1)
delta = pi * observation_matrix[:, obs_map[observation_sequence[0]]]
psi = np.zeros(shape=[len(observation_sequence), num_hidden_states],
               dtype=np.uint32)

for i in range(1, len(observation_sequence)):
    delta = np.reshape(delta, newshape=[-1, 1])
    P = delta * transition_matrix * np.reshape(
        observation_matrix[:, obs_map[observation_sequence[i]]],
        newshape=[1, -1])
    delta = np.max(P, axis=0)
    psi[i] = np.argmax(P, axis=0)

last_state = np.argmax(delta.reshape(-1))

# state 为 0, 1, 2, 所以打印出来是 2-->2-->2, 书中是 3-->3-->3
for t in reversed(range(len(observation_sequence))):
    print(last_state, end='-->')
    last_state = psi[t, last_state]
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018年04月08日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档