HMM 隐马尔科夫 Python 代码

 1 import numpy as np
 2 # -*- codeing:utf-8 -*-
 3 __author__ = 'youfei'
 4 
 5 #   隐状态
 6 hidden_state = ['sunny', 'rainy']
 7 
 8 #   观测序列
 9 obsevition = ['walk', 'shop', 'clean']
10 
11 
12 #   根据观测序列、发射概率、状态转移矩阵、发射概率
13 #   返回最佳路径
14 def compute(obs, states, start_p, trans_p, emit_p):
15     #   max_p(3*2)每一列存储第一列不同隐状态的最大概率
16     max_p = np.zeros((len(obs), len(states)))
17 
18     #   path(2*3)每一行存储上max_p对应列的路径
19     path = np.zeros((len(states), len(obs)))
20 
21     #   初始化
22     for i in range(len(states)):
23         max_p[0][i] = start_p[i] * emit_p[i][obs[0]]
24         path[i][0] = i
25 
26     for t in range(1, len(obs)):
27         newpath = np.zeros((len(states), len(obs)))
28         for y in range(len(states)):
29             prob = -1
30             for y0 in range(len(states)):
31                 nprob = max_p[t-1][y0] * trans_p[y0][y] * emit_p[y][obs[t]]
32                 if nprob > prob:
33                     prob = nprob
34                     state = y0
35                     #   记录路径
36                     max_p[t][y] = prob
37                     for m in range(t):
38                         newpath[y][m] = path[state][m]
39                     newpath[y][t] = y
40 
41         path = newpath
42 
43     max_prob = -1
44     path_state = 0
45     #   返回最大概率的路径
46     for y in range(len(states)):
47         if max_p[len(obs)-1][y] > max_prob:
48             max_prob = max_p[len(obs)-1][y]
49             path_state = y
50 
51     return path[path_state]
52 
53 
54 state_s = [0, 1]
55 obser = [0, 1, 2]
56 
57 #   初始状态,测试集中,0.6概率观测序列以sunny开始
58 start_probability = [0.6, 0.4]
59 
60 #   转移概率,0.7:sunny下一天sunny的概率
61 transititon_probability = np.array([[0.7, 0.3], [0.4, 0.6]])
62 
63 #   发射概率,0.4:sunny在0.4概率下为shop
64 emission_probability = np.array([[0.1, 0.4, 0.5], [0.6, 0.3, 0.1]])
65 
66 result = compute(obser, state_s, start_probability, transititon_probability, emission_probability)
67 
68 for k in range(len(result)):
69     print(hidden_state[int(result[k])])

 

posted @ 2018-09-26 09:26  cup_leo  阅读(797)  评论(0编辑  收藏  举报