Hidden state as lines in figure. #32
-
Is there any option to create this kind of figure with hmmTMB? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Am I understanding correctly that the plot shows the state-dependent mean parameter as a red line? You could get the information required to produce this plot from a fitted I'm including an example based on simulated data below. I fit a 2-state normal HMM to simulated data, and then get the estimated parameters and decoded states to create the graph. Here is the result. library(hmmTMB)
set.seed(4634)
###################
## Simulate data ##
###################
n <- 500
tpm <- matrix(c(0.95, 0.01, 0.05, 0.99), 2, 2)
S <- rep(1, n)
for(i in 2:n) S[i] <- sample(1:2, size = 1, prob = tpm[S[i-1],])
Z <- rnorm(n, mean = c(25, 75)[S], sd = c(10, 15)[S])
plot(Z, col = S)
data <- data.frame(Z = Z)
###############
## Fit model ##
###############
# Hidden state model
hid <- MarkovChain$new(data = data, n_states = 2)
# Observation model
par0 <- list(Z = list(mean = c(15, 60), sd = c(15, 20)))
obs <- Observation$new(data = data,
dists = list(Z = "norm"),
n_states = 2,
par = par0)
# Fit HMM
hmm <- HMM$new(obs = obs, hid = hid)
hmm$fit()
#################
## Create plot ##
#################
# Get mean parameters for the two states
estimated_means <- hmm$par()$obspar["Z.mean",,1]
# Get most likely state sequence
decoded_states <- hmm$viterbi()
# Predicted mean at each time step
data$mean <- estimated_means[decoded_states]
# Plot data and predicted mean
ggplot(data, aes(1:n, Z)) +
geom_line() +
geom_line(aes(y = mean), col = 2, linewidth = 1) |
Beta Was this translation helpful? Give feedback.
Am I understanding correctly that the plot shows the state-dependent mean parameter as a red line? You could get the information required to produce this plot from a fitted
HMM
model. In particular, you could use$par()
to get the estimated state-dependent mean parameters, and$viterbi()
to get the most likely state sequence.I'm including an example based on simulated data below. I fit a 2-state normal HMM to simulated data, and then get the estimated parameters and decoded states to create the graph. Here is the result.