Python入門練習(二)Viterbi演算法

來源:互聯網
上載者:User

資料見:http://en.wikipedia.org/wiki/Viterbi_algorithm

代碼如下

 

C:Python26MyViterbiMyViterbi.py

# -*- coding: cp936 -*-

def forward_viterbi(obs, states, start_p, trans_p, emit_p):
   T = {}
   for state in states:
       ##          prob.           V. path  V. prob.
       T[state] = (start_p[state], [state], start_p[state])
   for output in obs:
       U = {}
       for next_state in states:
           total = 0
           argmax = None
           valmax = 0
           for source_state in states:
               (prob, v_path, v_prob) = T[source_state]
               p = emit_p[source_state][output] * trans_p[source_state][next_state]
               prob *= p
               v_prob *= p
               total += prob
               if v_prob > valmax:
                   argmax = v_path + [next_state]
                   valmax = v_prob
           U[next_state] = (total, argmax, valmax)
       T = U
   ## apply sum/max to the final states:
   total = 0
   argmax = None
   valmax = 0
   for state in states:
       (prob, v_path, v_prob) = T[state]
       total += prob
       if v_prob > valmax:
           argmax = v_path
           valmax = v_prob
   return (total, argmax, valmax)

 

 

C:Python26MyViterbimyTestViterbi.py

# -*- coding: cp936 -*-
from MyViterbi import forward_viterbi
states=('Rainy','Sunny')#元組
observations=('walk','shop','clean')#元組
start_probability={'Rainy':0.6,'Sunny':0.4}
transition_probility={
    'Rainy':{'Rainy':0.7,'Sunny':0.3},
    'Sunny':{'Rainy':0.4,'Sunny':0.6}
    }
emission_probability={
    'Rainy':{'walk':0.1,'shop':0.4,'clean':0.5},
    'Sunny':{'walk':0.6,'shop':0.3,'clean':0.1}
    }
observation=('walk','clean','walk')

c=forward_viterbi(observation,states,start_probability,transition_probility,emission_probability)
print c

 

別忘了在MyViterbi檔案夾下加init.py

直接運行myTestViterbi.py

結果如下:

(0.023729999999999994, ['Sunny', 'Rainy', 'Sunny', 'Sunny'], 0.0051839999999999994)

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.