码迷,mamicode.com
首页 > 其他好文 > 详细

用ruby写的wikipedia上的维特比算法

时间:2014-07-16 18:58:42      阅读:176      评论:0      收藏:0      [点我收藏+]

标签: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-8 puts 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 end end def 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] end def example viterbi $obervastions, $states, $start_probability, $transition_probability, $emission_probability end puts example

 

用ruby写的wikipedia上的维特比算法,布布扣,bubuko.com

用ruby写的wikipedia上的维特比算法

标签:style   blog   http   color   使用   os   

原文地址:http://www.cnblogs.com/daoyou/p/3844890.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!