簡體   English   中英

使用帶有T和R材料的KFAS R包估計自定義狀態空間模型

[英]Estimation of custom State Space model using KFAS R package with T and R matxices

我想用一些特定的假設來估計狀態空間模型。 我研究了如何使用帶有AR(1)轉換方程的'KFAS'R包估計卡爾曼濾波器? 克服Error ... : System matrices (excluding Z) contain NA or infinite values的問題Error ... : System matrices (excluding Z) contain NA or infinite values ,但是仍然無法獲得預期的結果。

這是一些例子:

# simulation ----------------------
library(KFAS)
set.seed(2018)

xt<-arima.sim(n = 100, list(ar = c(0.7)))+5
at<-arima.sim(n = 100, list(ar = c(0.2,0.1)),sd=0.1)
bt<-arima.sim(n = 100, list(ar = c(0.1)),sd=0.1)
e1<-rnorm(100,0,0.5)
e2<-rnorm(100,0,0.5)

plot(xt+at,type='l')
lines(xt+bt,type='l',col='red')

tempM<-matrix(c(xt+at+e1,
           xt+bt+e2),100,2)   
# model -----------------------------------------------

Zt <- t(matrix(c(1,1,0,1,0,1,0,1,0,1),5,2))
Ht <- matrix(c(0,0,0,0),2,2)
Tt <- diag(NA,5)
Rt <- matrix(c(c(NA,0,0,0,0),c(NA,NA,0,0,0),c(NA,NA,NA,0,0),c(0,0,0,NA,0),c(0,0,0,0,NA)),5,5)
Qt <- diag(1,5)

ss_model <- SSModel(tempM ~ -1 + SSMcustom(Z = Zt, T = Tt, R = Rt, 
                                       Q = Qt), H = Ht)

# this gives an error
updatefn <- function(pars, model) {
  model$T[1] <- pars[1]
  model$R[1] <- pars[2]
  model
}

fit <- fitSSM(ss_model, c(1, 0.5), updatefn, method = "L-BFGS-B",
          lower = c(0, -0.99), upper = c(100, 0.99))
# end error example

# using optim (from link) -------------------

objf <- function(pars, model, estimate = TRUE) {
  model$T[1] <- pars[1]
  model$R[1] <- pars[2]
  if (estimate) {
    -logLik(model)
  } else {
    model
  }
}

opt <- optim(c(diag(1,5),diag(1,5)), objf, method = "L-BFGS-B", 
         model = ss_model)

ss_model_opt <- objf(opt$par, ss_model, estimate = FALSE)

現在我得到:

ss_model_opt$R

        [,1] [,2] [,3] [,4] [,5]
custom1    0   NA   NA    0    0    
custom2    0   NA   NA    0    0
custom3    0    0   NA    0    0
custom4    0    0    0   NA    0
custom5    0    0    0    0   NA

而且我希望這樣的事情:

     [,1] [,2] [,3] [,4] [,5]
[1,]    1  0.1  0.1  0.0  0.0
[2,]    0 -0.1 -0.1  0.0  0.0
[3,]    0  0.0 -0.1  0.0  0.0
[4,]    0  0.0  0.0  0.5  0.0
[5,]    0  0.0  0.0  0.0  0.5

具體來說,我想從“ 建模數據修訂版”中應用模型:測量誤差和“真實”值的動態變化到二維可觀察向量。

您的模型中有13個NA值,但是您只能在目標函數中修改其中兩個。 嘗試這個:

updatefn <- function(pars, model) {
  diag(model$T[,,1]) <- pars[1:5]
  model$R[is.na(model$R)] <- pars[6:13]
  model
}

fit <- fitSSM(ss_model, rep(0.5,13), updatefn, method = "L-BFGS-B",
              lower = c(0, -0.99), upper = c(100, 0.99))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM