隐马尔可夫模型以隐状态为条件对观察到的变量进行建模。因此,预测观察到的变量需要一个预测隐藏状态的中间步骤。一旦你有了隐藏状态的预测概率,你就可以从观察变量的边际分布中预测观察变量,例如
P(Y[T+k]|Y[1:T]) = \sum_i P(Y[T+k]|S[T+k] = i) * P(S[T+k] = i|Y[1:T])
您可以通过将 P(S[T]|Y[1:T]) 与状态转移矩阵相乘来获得预测的状态分布。
library(depmixS4)
n_state <- 2
# My series
draws <- data.frame(obs=rnorm(10000))
# Model
mod <- depmix(obs ~ 1, data = draws, nstates = n_state, stationary=TRUE)
fit.mod <- fit(mod)
# extract the state-transition matrix
transition_mat <- rbind(getpars(getmodel(fit.mod,"transition",1)),getpars(getmodel(fit.mod,"transition",2)))
# extract the probability of the states at the final time point in the data (t=T)
# this will act as a "prior" to compute the forecasted state distributions
prior_vec <- as.numeric(posterior(fit.mod)[1000,-1])
# state-wise predictions for the observed variables
pred_r_by_state <- c(getpars(getmodel(fit.mod,"response",1))[1],
getpars(getmodel(fit.mod,"response",2))[1])
# for T + 1
# the forecasted state distribution is (prior_vec %*% transition_mat)
# so hence the prediction of the observed variable is
sum(pred_r_by_state * (prior_vec %*% transition_mat))
# for T + 2
# the forecasted state distribution is (prior_vec %*% transition_mat %*% transition_mat)
# so hence the prediction of the observed variable is
sum(pred_r_by_state * (prior_vec %*% transition_mat %*% transition_mat))
# for T + 3
sum(pred_r_by_state * (prior_vec %*% transition_mat %*% transition_mat %*% transition_mat))
# etc
您可能想要使用包含%^% 运算符的expm 包,因此您可以使用
transition_mat %^% 3
而不是
transition_mat %*% transition_mat %*% transition_mat
如果模型在观察到的预测变量的模型中包含协变量,您还需要考虑这些变量,即在计算 pred_r_by_state 时尝试以某种方式预测这些变量的值。