In package depmixs4, converge information of the HMM is shown in print(fit.mod). However I'm trying to extract the value. For instance, when it converges I get 1. When it doesn't I get 0.
In this way when it doesn't converge I can automatically change to HMM with less states. But I didn't find a solution in the manual.
for(i in 3000:(length(p[,2])-252*5)){
mod <- depmix(p[(i):(252*5-1+i),2] ~ 1, data = p[(i):(252*5-1+i),], nstates = 3, family = gaussian())
#set.seed(1)
fit.mod <- fit(mod)}
print(fit.mod) will get
print(fit.mod)
Convergence info: 'maxit' iterations reached in EM without convergence.
'log Lik.' 3478.027 (df=14)
AIC: -6928.053
BIC: -6856.109
The problem is to extract the information "iterations reached in EM without convergence" as a number.
The convergence return value is assigned in function fit
. You can see exactly where in the code with
getMethods("fit", signature = "mix")
and look for the optimizers Rdonlp2::dolnp2
, rsolnp
and solnp
.
A hack can be to extract the slot message
from the object returned by fit
and grepl
an appropriate string.
converged <- function(object, numeric = TRUE){
msg <- object@message
if(numeric) as.integer(grepl("converged", msg)) else msg
}
converged(fm)
#[1] 1
As a test object fm
I have used an example from help('fit')
.
library(depmixS4)
data(speed)
mod <- depmix(list(rt~1,corr~1),data=speed,nstates=2,
family=list(gaussian(),multinomial("identity")),ntimes=c(168,134,137))
# print the model, formulae and parameter values
mod
set.seed(1)
# fit the model by calling fit
fm <- fit(mod, verbose = TRUE)