I want to calculate log likelihood for my model but don't know how to do it efficiently. Here is my code that does what I need, but it's slow
up <- rnorm(300,mean = 1,sd = 1)
dw <- rnorm(300,mean = -1,sd = 1)
test <- c(up[1:100],dw[1:100],up[101:200],dw[101:200],up[201:300],dw[201:300])
train <- data.frame(y=up)
test <- data.frame(y=test)
library(depmixS4)
hmm <- depmix(y~1, data=train, nstates=2, family=gaussian()) |> fit()
The function for calculating logLike
is extremely slow because it needs to initialize the model
with new data every time
logLike <- function(model, new_data){
init <- depmix(y~1, data=new_data, nstates=2, family=gaussian())
sp <- setpars(init , getpars(model))
forwardbackward(sp)$logLike
}
llh <- rep(NA,nrow(test))
for(i in 20:nrow(test)){
data <- data.frame(y=test[ (i-19):i ,])
llh[i] <- logLike(hmm, data)
}
layout(1:2)
plot(cumsum(test$y),t="l")
plot(llh,t="l")
Is there any other way to calculate the logLike
more efficiently