我正在处理从this blog开始缩减的最小示例,我想知道如何正确匹配状态。示例代码模拟了两个状态,状态1是波动率低的正收益,状态2是波动率高的负收益。如果多次运行代码,您会发现有时HMM的准确度为100%,而其他时候为0%。我认为这只是分类问题,哪种波动率制度是状态1和哪种状态2。如何使输出保持一致?
library('depmixS4')
bull_mean <- 0.2
bull_var <- 0.05
bear_mean <- -0.1
bear_var <- 0.1
# Create the various bull and bear markets returns
bull <- rnorm(100, bull_mean, bull_var )
bear <- rnorm(100, bear_mean, bear_var )
# Create the list of true regime states and full returns list
true_regimes <- c(rep(1, 100), rep(2, 100))
returns <- c(bull, bear)
# Create and fit the Hidden Markov Model
hmm <- depmix(returns ~ 1, family = gaussian(), nstates = 2, data=data.frame(returns=returns))
hmmfit <- fit(hmm, verbose = FALSE)
post_probs <- posterior(hmmfit)
output <- data.frame(pred = post_probs$state, true_regimes = true_regimes)
table(output)
accuracy = sum(post_probs$state == true_regimes) / nrow(post_probs)
accuracy