首页 > 代码库 > 用ruby写的wikipedia上的维特比算法
用ruby写的wikipedia上的维特比算法
维特比算法可以解决隐马尔科夫模型的最可能状态序列问题。
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个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。