1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | def viterbi(obs, states, start_p, trans_p, emit_p): V = [{}] path = {} # Initialize base cases (t == 0) for y in states: V[0][y] = start_p[y] * emit_p[y][obs[0]] path[y] = [y] # Run Viterbi for t > 0 for t in range(1, len(obs)): V.append({}) newpath = {} for y in states: (prob, state) = max((V[t-1][y0] * trans_p[y0][y] * emit_p[y][obs[t]], y0) for y0 in states) V[t][y] = prob newpath[y] = path[state] + [y] # Don't need to remember the old paths path = newpath n = 0 # if only one element is observed max is sought in the initialization values if len(obs) != 1: n = t print_dptable(V) (prob, state) = max((V[n][y], y) for y in states) return (prob, path[state]) # Don't study this, it just prints a table of the steps. def print_dptable(V): s = " " + " ".join(("%7d" % i) for i in range(len(V))) + "\n" for y in V[0]: s += "%.5s: " % y s += " ".join("%.7s" % ("%f" % v[y]) for v in V) s += "\n" print(s) |
1 2 3 4 5 6 7 | <span class="kw1">def</span> example<span class="br0">(</span><span class="br0">)</span>: <span class="kw1">return</span> viterbi<span class="br0">(</span>observations<span class="sy0">,</span> states<span class="sy0">,</span> start_probability<span class="sy0">,</span> transition_probability<span class="sy0">,</span> emission_probability<span class="br0">)</span> <span class="kw1">print</span><span class="br0">(</span>example<span class="br0">(</span><span class="br0">)</span><span class="br0">)</span> |
欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/) | Powered by Discuz! 7.0.0 |