2

I'm trying to implement the following example of the Hidden Markov Model in R using the HMM package:

https://github.com/luisguiserrano/hmm/blob/master/Simple%20HMM.ipynb

Here is my R code:

states = c("S", "R")
symbols = c("H", "G")
startProbs = c(2/3, 1/3)
transProbs = matrix(c(0.8, 0.4, 0.2, 0.6), 2)
emissionProbs = matrix(c(0.8, 0.4, 0.2, 0.6), 2)
# Initialise HMM
hmm = initHMM(States = states, Symbols = symbols, startProbs = startProbs, transProbs = transProbs, emissionProbs = emissionProbs)

observations = c("H", "H", "G", "G", "G", "H")

print(exp(forward(hmm,observations)))

viterbi = viterbi(hmm,observations)
print(viterbi)

But, I'm getting a different result:

> print(exp(forward(hmm,observations)))
states         1          2          3          4           5           6
     S 0.5333333 0.38400000 0.06741333 0.01662293 0.005408085 0.008057214
     R 0.1333333 0.07466667 0.07296000 0.03435520 0.014362624 0.003879677

> print(viterbi)
"S" "S" "R" "R" "R" "S"

The result should be:

"S" "S" "S" "R" "R" "S"

What is the problem?

Matt
  • 195
  • 3
  • 8

1 Answers1

2

The HMM package uses a slightly different algorithm for the calculation of the most probable path of states. You can read about the implementation here.

For example, the forward probability for Sunny on Tuesday in the given example = max(0.533*0.8*0.8, 0.133*0.4*0.8) = 0.341

However, using the function forward() from our HMM package we obtain: 0.533*0.8*0.8 + 0.133*0.4*0.8 = 0.384.

Therefore, the sequences of states are different.

onlyphantom
  • 8,606
  • 4
  • 44
  • 58