This section mainly implements the predictive algorithm of the hidden Markov model: Viterbi algorithm
Hangyuan Li, Statistical learning method
#!/usr/bin/env python #-*-coding:utf-8-*-"" "@author: Xiangguosun @contact: sunxiangguodut@qq.com @file: viterbi.py @ Time:2017/3/27 12:40 @software: Pycharm "" "Import NumPy as NP def Viterbi (observe,model): A = model[0] B = MoD El[1] pi = model[2] T = observe.size N = b.shape[0] Delta = Np.zeros ((t,n)) F = Np.zeros ((t,n)) F
Or I in Xrange (0,n): delta[0,i]=pi[i]*b[i,observe[0] "for T in Xrange (1,t): For I in Xrange (0,n):
Delta[t, I] = Np.max (Delta[t-1,:]*a[:,i]) *b[i,observe[t]] f[t,i] = Np.argmax (Delta[t-1,:]*a[:,i]) It=np.zeros ((T,), Dtype=int) It[t-1]=np.argmax (delta[-1,:]) for T in Xrange (t-2,-1,-1): it[t] = F[t+1,it
[T+1]]
return IT,DELTA,F If __name__ = = ' __main__ ': A = Np.array ([[0.5, 0.2, 0.3], [0.3, 0.5, 0.2],
[0.2, 0.3, 0.5]]) B = Np.array ([[0.5, 0.5], [0.4, 0.6], [0.7, 0.3]]) PI = NP. Array ([0.2, 0.4, 0.4]) model = (A, B, pi) Observe = Np.array ([0,1,0]) states = Np.array ([+]) IT, de LTA, F = Viterbi (Observe, model) print IT, ' \ n ', delta, ' \ n ', f