# Demo entry 5181393

**Viterbi en Python**

Submitted by **anonymous**
on Jun 08, 2016 at 07:44

Language: Python 3. Code size: 879 Bytes.

import numpy as np class HMM: def __init__(self,A,B,pi): self.A = A self.B = B self.pi = pi def viterbi(self, emissions): probs = self.B[emissions[0]] * self.pi stack = [] for emission in emissions[1:]: trans_probs = self.A * np.row_stack(probs) max_col_ixs = np.argmax(trans_probs, axis=0) probs = self.B[emission] * trans_probs[max_col_ixs, np.arange(len(self.pi))] stack.append(max_col_ixs) state_seq = [np.argmax(probs)] while stack: max_col_ixs = stack.pop() state_seq.append(max_col_ixs[state_seq[-1]]) state_seq.reverse() return state_seq B=np.array([[0.7,.3],[0.4,0.6],[0.8,0.2]]).transpose() A=np.array([[0.5,0.3,0.2],[0,0.6,0.4],[0,0,1]]).transpose() pi=np.array([0.9,0.1,0]) observations=np.array([0,1,0]) hmm=HMM(A,B,pi) print(hmm.viterbi(observations))

This snippet took 0.00 seconds to highlight.

Back to the Entry List or Home.