简体   繁体   中英

HMM Package Usage in R

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM