[关闭]
@nrailgun 2016-05-08T21:29:06.000000Z 字数 1573 阅读 1694

Viterbi 算法

程序设计


HMM:
At time t, observation yt, there is corresponding state xi.

Recurrence equation:

v1,k=P(y1k)×πk

vt,k=argmaxxS(P(ytk)×ax,k×vt1,x))

贴一个网上看到的代码:

  1. # -*- coding:utf-8 -*-
  2. # Filename: viterbi.py
  3. # Author:hankcs
  4. # Date: 2014-05-13 下午8:51
  5. states = ('Rainy', 'Sunny')
  6. observations = ('walk', 'shop', 'clean')
  7. start_probability = {'Rainy': 0.6, 'Sunny': 0.4}
  8. transition_probability = {
  9. 'Rainy' : {'Rainy': 0.7, 'Sunny': 0.3},
  10. 'Sunny' : {'Rainy': 0.4, 'Sunny': 0.6},
  11. }
  12. emission_probability = {
  13. 'Rainy' : {'walk': 0.1, 'shop': 0.4, 'clean': 0.5},
  14. 'Sunny' : {'walk': 0.6, 'shop': 0.3, 'clean': 0.1},
  15. }
  16. # 打印路径概率表
  17. def print_dptable(V):
  18. print " ",
  19. for i in range(len(V)): print "%7d" % i,
  20. print
  21. for y in V[0].keys():
  22. print "%.5s: " % y,
  23. for t in range(len(V)):
  24. print "%.7s" % ("%f" % V[t][y]),
  25. print
  26. def viterbi(obs, states, start_p, trans_p, emit_p):
  27. """
  28. :param obs:观测序列
  29. :param states:隐状态
  30. :param start_p:初始概率(隐状态)
  31. :param trans_p:转移概率(隐状态)
  32. :param emit_p: 发射概率 (隐状态表现为显状态的概率)
  33. :return:
  34. """
  35. # 路径概率表 V[时间][隐状态] = 概率
  36. V = [{}]
  37. # 一个中间变量,代表当前状态是哪个隐状态
  38. path = {}
  39. # 初始化初始状态 (t == 0)
  40. for y in states:
  41. V[0][y] = start_p[y] * emit_p[y][obs[0]]
  42. path[y] = [y]
  43. # 对 t > 0 跑一遍维特比算法
  44. for t in range(1, len(obs)):
  45. V.append({})
  46. newpath = {}
  47. for y in states:
  48. # 概率 隐状态 = 前状态是y0的概率 * y0转移到y的概率 * y表现为当前状态的概率
  49. (prob, state) = max([(V[t - 1][y0] * trans_p[y0][y] * emit_p[y][obs[t]], y0) for y0 in states])
  50. # 记录最大概率
  51. V[t][y] = prob
  52. # 记录路径
  53. newpath[y] = path[state] + [y]
  54. # 不需要保留旧路径
  55. path = newpath
  56. print_dptable(V)
  57. (prob, state) = max([(V[len(obs) - 1][y], y) for y in states])
  58. return (prob, path[state])
  59. def example():
  60. return viterbi(observations,
  61. states,
  62. start_probability,
  63. transition_probability,
  64. emission_probability)
  65. print example()
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注