用ruby寫的wikipedia上的維特比演算法

來源:互聯網
上載者:User

標籤:style   blog   http   color   使用   os   

維特比演算法可以解決隱馬爾科夫模型的最可能狀態序列問題。

wikipedia上關於維特比演算法,提供了一個python的例子,原文地址如下

http://zh.wikipedia.org/wiki/%E7%BB%B4%E7%89%B9%E6%AF%94%E7%AE%97%E6%B3%95

鑒於最近正在學習ruby,就把這個演算法從python遷移到ruby,這兩個語言的文法很接近,所以,前移過去沒有什麼難度,希望使用代碼之前先瞭解一下維特比演算法的基礎理論。

 

 


##encoding:utf-8puts ‘This is Viterbi‘$states = [:Healthy, :Fever]#puts "length: #{$states.length}"$obervastions = [:normal, :cold, :dizzy]$start_probability = {Healthy: 0.6, Fever: 0.4}# puts $start_probability[$states[0]]$transition_probability = { Healthy: {Healthy: 0.7, Fever: 0.3}, Fever: {Healthy: 0.4, Fever: 0.6},}$emission_probability = { Healthy: {normal: 0.5, cold: 0.4, dizzy: 0.1}, Fever: {normal: 0.1, cold: 0.3, dizzy: 0.6}}def print_dptable(v) puts ‘ ‘ for i in 0..v.length puts "%7d" % i end for y in v[0].keys puts "%5s" % y for t in 0...v.length puts "%.7s" % ("%f" % v[t][y]) end endenddef viterbi(obs, states, start_p, trans_p, emit_p) v = [{}] path = {}# Initialize base cases (t == 0) states.each { |y| v[0][y] = start_p[y] * emit_p[y][obs[0]] path[y] = [y] }# Run Viterbi for t > 0 for t in 1...obs.length v << {} newpath = {} for y in states prob, state = states.map { |y0| [v[t-1][y0] * trans_p[y0][y] * emit_p[y][obs[t]], y0] }.max v[t][y] = prob newpath[y] = path[state] + [y] end # Don‘t need to remember the old paths path = newpath end print_dptable v prob, state = states.map { |y| [v[obs.size - 1][y], y] }.max return prob, path[state]enddef example viterbi $obervastions, $states, $start_probability, $transition_probability, $emission_probabilityendputs example

 

 
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.