Class: Ai4r::Hmm::HiddenMarkovModel

Inherits:
Object
  • Object
show all
Includes:
Data::Parameterizable
Defined in:
lib/ai4r/hmm/hidden_markov_model.rb

Overview

Introduction

A simple implementation of a discrete Hidden Markov Model (HMM). You must provide the states and observations as well as the probability matrices. This class exposes two main operations:

  • eval(sequence): probability of the observation sequence.

  • decode(sequence): most likely hidden state sequence (Viterbi).

Probabilities are provided as arrays. Example:

states = [:Rainy, :Sunny]
observations = [:walk, :shop, :clean]
start_prob = [0.6, 0.4]
transition = [[0.7, 0.3], [0.4, 0.6]]
emission = [[0.1, 0.4, 0.5], [0.6, 0.3, 0.1]]
hmm = Ai4r::Hmm::HiddenMarkovModel.new(
  states: states,
  observations: observations,
  start_prob: start_prob,
  transition_prob: transition,
  emission_prob: emission
)
hmm.eval([:walk, :shop, :clean])
hmm.decode([:walk, :shop, :clean])

Instance Method Summary collapse

Methods included from Data::Parameterizable

#get_parameters, included, #set_parameters

Constructor Details

#initialize(params = {}) ⇒ HiddenMarkovModel

Returns a new instance of HiddenMarkovModel.



50
51
52
53
54
55
56
57
# File 'lib/ai4r/hmm/hidden_markov_model.rb', line 50

def initialize(params = {})
  @states = []
  @observations = []
  @start_prob = []
  @transition_prob = []
  @emission_prob = []
  set_parameters(params) if params && !params.empty?
end

Instance Method Details

#decode(sequence) ⇒ Object

Return the most likely hidden state sequence for the given observations using the Viterbi algorithm.



67
68
69
# File 'lib/ai4r/hmm/hidden_markov_model.rb', line 67

def decode(sequence)
  viterbi(sequence)
end

#eval(sequence) ⇒ Object

Probability of the given observation sequence using the forward algorithm.



61
62
63
# File 'lib/ai4r/hmm/hidden_markov_model.rb', line 61

def eval(sequence)
  forward(sequence).last.sum
end