-
Notifications
You must be signed in to change notification settings - Fork 17
/
hmm.Rmd
213 lines (146 loc) · 4.82 KB
/
hmm.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# Hidden Markov Model
This function duplicates [hmm_viterbi.py][HMM], which comes from the [Viterbi algorithm wikipedia page](https://en.wikipedia.org/wiki/Viterbi_algorithm) (at least as it was when I stumbled across it, see it in the [supplemental section](#python-hmm)). This first function is just to provide R code that is similar, in case anyone is interested in a more direct comparison, but the original used lists of tuples and thus was very inefficient R-wise, and provided output that wasn't succinct. The second function takes a vectorized approach and returns a matrix in a much more straightforward fashion. Both will provide the same result as the Python code. See The [Markov Model chapter][Markov Model] also.
## Data Setup
```{r hmm-setup}
library(tidyverse)
obs = c('normal', 'cold', 'dizzy') # observed state
states = c('Healthy', 'Fever') # latent states
start_p = c('Healthy' = 0.6, 'Fever' = 0.4) # starting probabilities
# transition matrix
trans_p = list(
'Healthy' = c('Healthy' = 0.7, 'Fever' = 0.3),
'Fever' = c('Healthy' = 0.4, 'Fever' = 0.6)
)
# emission matrix
emit_p = list(
'Healthy' = c('normal' = 0.5, 'cold' = 0.4, 'dizzy' = 0.1),
'Fever' = c('normal' = 0.1, 'cold' = 0.3, 'dizzy' = 0.6)
)
```
## Function
This first function takes a Python-esque approach in the manner of the original, allowing for easier comparison.
```{r viterbi1}
viterbi <- function(obs, states, start_p, trans_p, emit_p) {
V = vector('list', length(obs))
for (st in seq_along(states)) {
V[[1]][[states[st]]] = list("prob" = start_p[st] * emit_p[[st]][obs[1]],
"prev" = NULL)
}
for (t in 2:length(obs)) {
for (st in seq_along(states)) {
max_tr_prob = numeric()
for (prev_st in states) {
max_tr_prob[prev_st] = V[[t-1]][[prev_st]][["prob"]] * trans_p[[prev_st]][[st]]
}
max_tr_prob = max(max_tr_prob)
for (prev_st in states) {
flag = V[[t-1]][[prev_st]][["prob"]] * trans_p[[prev_st]][[st]] == max_tr_prob
if (flag) {
max_prob = max_tr_prob * emit_p[[st]][obs[t]]
V[[t]][[states[st]]] = list('prob' = max_prob, 'prev' = prev_st)
}
}
}
}
# I don't bother duplicating the text output code of the original
df_out = rbind(
Healthy = sapply(V, function(x) x$Healthy$prob),
Fever = sapply(V, function(x) x$Fever$prob)
)
colnames(df_out) = obs
print(df_out)
m = paste0(
'The steps of states are: ',
paste(rownames(df_out)[apply(df_out, 2, which.max)], collapse = ' '),
paste('\nHighest probability: ', max(df_out[, ncol(df_out)]))
)
message(m)
V
}
```
This approach is much more R-like.
```{r viterbi2}
viterbi_2 <- function(obs, states, start_p, trans_mat, emit_mat) {
prob_mat = matrix(NA, nrow = length(states), ncol = length(obs))
colnames(prob_mat) = obs
rownames(prob_mat) = states
prob_mat[,1] = start_p * emit_mat[,1]
for (t in 2:length(obs)) {
prob_tran = prob_mat[,t-1] * trans_mat
max_tr_prob = apply(prob_tran, 2, max)
prob_mat[,t] = max_tr_prob * emit_mat[, obs[t]]
}
print(prob_mat)
m = paste0(
'The steps of states are: ',
paste(states[apply(prob_mat, 2, which.max)], collapse = ' '),
paste('\nHighest probability: ', max(prob_mat[, ncol(prob_mat)]))
)
message(m)
}
```
## Estimation
First we demo the initial function.
```{r viterbi1-est}
test = viterbi(
obs,
states,
start_p,
trans_p,
emit_p
)
# test
set.seed(123)
obs = sample(obs, 6, replace = TRUE)
test = viterbi(
obs,
states,
start_p,
trans_p,
emit_p
)
# test
```
Now the vectorized approach.
```{r viterbi2-est}
set.seed(123)
obs = c('normal', 'cold', 'dizzy')
obs = sample(obs, 6, replace = T)
# need matrices now
emit_mat = do.call(rbind, emit_p)
trans_mat = do.call(rbind, trans_p)
viterbi_2(
obs,
states,
start_p,
trans_mat,
emit_mat
)
```
## Supplemental demo
This example comes from the [hidden markov model wikipedia page](https://en.wikipedia.org/wiki/Hidden_Markov_model).
```{r viterbi-supp}
states = c('Rainy', 'Sunny')
observations = c('walk', 'shop', 'clean')
start_probability = c('Rainy' = 0.6, 'Sunny' = 0.4)
transition_probability = rbind(
'Rainy' = c('Rainy' = 0.7, 'Sunny' = 0.3),
'Sunny' = c('Rainy' = 0.4, 'Sunny' = 0.6)
)
emission_probability = rbind(
'Rainy' = c('walk' = 0.1, 'shop' = 0.4, 'clean' = 0.5),
'Sunny' = c('walk' = 0.6, 'shop' = 0.3, 'clean' = 0.1)
)
viterbi_2(
observations,
states,
start_probability,
transition_probability,
emission_probability
)
```
## Source
Original code for R found at
https://github.com/m-clark/Miscellaneous-R-Code/blob/master/ModelFitting/hmm_viterbi.R
Original code for Python found at
https://github.com/m-clark/Miscellaneous-R-Code/blob/master/ModelFitting/hmm_viterbi.py