-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathmarkov.Rmd
251 lines (165 loc) · 4.94 KB
/
markov.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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
# Markov Model
Here we demonstrate a [Markov model](https://en.wikipedia.org/wiki/Markov_model). We start by showing how to create some data and estimate such a model via the <span class="pack" style = "">markovchain</span> package. You may want to play with it to get a better feel for how it works, as we will use it for comparison later.
```{r markov-chain-demo}
library(tidyverse)
library(markovchain)
A = matrix(c(.7, .3, .9, .1), nrow = 2, byrow = TRUE)
dtmcA = new(
'markovchain',
transitionMatrix = A,
states = c('a', 'b'),
name = 'MarkovChain A'
)
dtmcA
plot(dtmcA)
transitionProbability(dtmcA, 'b', 'b')
initialState = c(0, 1)
steps = 4
finalState = initialState * dtmcA^steps # using power operator
finalState
steadyStates(dtmcA)
observed_states = sample(c('a', 'b'), 50, c(.7, .3), replace = TRUE)
createSequenceMatrix(observed_states)
markovchainFit(observed_states)
```
## Data Setup
### Data Functions
A recursive function to take a matrix power.
```{r matrix-power}
mat_power <- function(M, N) {
if (N == 1) return(M)
M %*% mat_power(M, N - 1)
}
```
A function to create a sequence.
```{r create-sequence}
create_sequence <- function(states, len, tmat) {
# states: number of states
# len: length of sequence
# tmat: the transition matrix
states_numeric = length(unique(states))
out = numeric(len)
out[1] = sample(states_numeric, 1, prob = colMeans(tmat)) # initial state
for (i in 2:len){
out[i] = sample(states_numeric, 1, prob = tmat[out[i - 1], ])
}
states[out]
}
```
```{r markov-setup}
# example
test_matrix = matrix(rep(2, 4), nrow = 2)
test_matrix
mat_power(test_matrix, 2)
# transition matrix
A = matrix(c(.7, .3, .4, .6), nrow = 2, byrow = TRUE)
mat_power(A, 10)
```
### Two states Demo
Note that a notably long sequence is needed to get close to recovering the true transition matrix.
```{r two-state-demo}
A = matrix(c(.7, .3, .9, .1), nrow = 2, byrow = TRUE)
observed_states = create_sequence(c('a', 'b'), 500, tmat = A)
createSequenceMatrix(observed_states)
prop.table(createSequenceMatrix(observed_states), 1)
fit = markovchainFit(observed_states)
fit
# log likelihood
sum(createSequenceMatrix(observed_states) * log(fit$estimate@transitionMatrix))
```
### Three states demo
```{r three-state-demo}
A = matrix(
c(.70, .20, .10,
.20, .40, .40,
.05, .05, .90),
nrow = 3,
byrow = TRUE
)
observed_states = create_sequence(c('a', 'b', 'c'), 500, tmat = A)
createSequenceMatrix(observed_states)
prop.table(createSequenceMatrix(observed_states), 1)
markovchainFit(observed_states)
```
## Function
Now we create a function to calculate the (negative) log likelihood.
```{r markov-ll}
markov_ll <- function(par, x) {
# par should be the c(A) of transition probabilities A
nstates = length(unique(x))
# create transition matrix
par = matrix(par, ncol = nstates)
par = t(apply(par, 1, function(x) x / sum(x)))
# create seq matrix
seq_mat = table(x[-length(x)], x[-1])
# calculate log likelihood
ll = sum(seq_mat * log(par))
-ll
}
```
```{r data-gen}
A = matrix(
c(.70, .20, .10,
.40, .20, .40,
.10, .15, .75),
nrow = 3,
byrow = TRUE
)
observed_states = create_sequence(c('a', 'b', 'c'), 1000, tmat = A)
```
## Estimation
Note that initial state values will be transformed to rowsum to one, so the specific initial values don't matter (i.e. they don't have to be probabilities). With the basic <span class="func" style = "">optim</span> approach, sometimes log(0) will occur and produce a warning. Can be ignored, or use `LFBGS` as demonstrated at the end.
```{r mm-est}
initpar = rep(1, 9)
fit = optim(
par = initpar,
fn = markov_ll,
x = observed_states,
method = 'BFGS',
control = list(reltol = 1e-12)
)
# get estimates on prob scale
est_mat = matrix(fit$par, ncol = 3)
est_mat = t(apply(est_mat, 1, function(x) x / sum(x)))
```
## Comparison
Compare with <span class="pack" style = "">markovchain</span> package.
```{r markov-compare}
fit_compare = markovchainFit(observed_states)
# compare log likelihood
c(-fit$value, fit_compare$logLikelihood)
# compare estimated transition matrix
list(
`Estimated via optim` = est_mat,
`markovchain Package` = fit_compare$estimate@transitionMatrix,
`Analytical Solution` = prop.table(
table(observed_states[-length(observed_states)], observed_states[-1])
, 1)
) %>%
purrr::map(round, 3)
```
Visualize.
```{r markov-vis}
plot(
new(
'markovchain',
transitionMatrix = est_mat,
states = c('a', 'b', 'c'),
name = 'Estimated Markov Chain'
)
)
```
If you don't want warnings due to zeros use constraints (`?constrOptim`).
```{r markov-est-constrained, eval=FALSE}
fit = optim(
par = initpar,
fn = markov_ll,
x = observed_states,
method = 'L-BFGS',
lower = rep(1e-20, length(initpar)),
control = list(pgtol = 1e-12)
)
```
## Source
Original code available at
https://github.com/m-clark/Miscellaneous-R-Code/blob/master/ModelFitting/markov_model.R