0

I have this following model, I want to estimate the matrix of Ht and Qt using 200 random initialization using multivariate uniform distribution, then choosing the maximum likelihood. I try this following code, and got Qt as negative value (-0.02298325)

# Define initial state and covariance matrix
Zt <- matrix(c(1,rep(0,8)),1,9)
Tt <- t(matrix(c(rep(0,8),1,1,rep(0,9),1,rep(0,9),1,rep(0,9),1,rep(0,9),1,rep(0,9),1,rep(0,9),1,rep(0,9),1,0),9,9))
Rt <- matrix(c(1, rep(0,8)), 9,1)
Ht <- matrix(NA)
Qt <- matrix(NA)
P1 <- 10^(6)*diag(1,9,9)
a1 <- matrix(rep(0,9),1,9)
P1inf <- diag(0,9,9)


# Define model
model <- SSModel(dt~-1+SSMcustom(Z = Zt, T = Tt, R = Rt, Q = Qt, P1 = P1,a1=a1,P1inf=P1inf), H = Ht)

set.seed(123)
initialHt <- runif(200)
initialQt <- runif(200)

maxLogLik <- -Inf
bestModel <- NULL

for (i in 1:200) {
  model <- SSModel(dt ~ -1 + SSMcustom(Z = Zt, T = Tt, R = Rt, Q = Qt, P1 = P1, a1 = a1, P1inf = P1inf), H = Ht)
  
  objf <- function(pars, model, estimate = TRUE) {
    model$H <- pars[1]
    model$Q <- pars[2]
    if (estimate) {
      logLik(model)  # Retrieve log-likelihood
    } else {
      model
    }
  }
  
  opt <- optim(c(initialHt[i], initialQt[i]), objf, method = "BFGS", model = model)
  ss_model_opt <- logLik(objf(opt$par, model, estimate = FALSE))
  
  if (ss_model_opt > maxLogLik) {
    maxLogLik <- ss_model_opt
    bestModel <- fitSSM(model, c(initialHt[i], initialQt[i]), updatefn, method = "BFGS")
  }
}
bestHt <- bestModel$model$H
bestQt <- bestModel$model$Q
bestHt
bestQt

0 Answers0