使用optim()在R中创建协方差矩阵

时间:2018-11-18 20:37:18

标签: r optimization covariance covariance-matrix

我想使用optim()函数在R中创建协方差矩阵。特别地,协方差矩阵如下所示:

[ (sigma_a)^2               rho*sigma_a*sigma_b     0 ]
[ rho*sigma_a*sigma_b       (sigma_b)^2             0 ]
[      0                         0                  0 ]

其中(sigma_a)^2(sigma_b)^2是方差,rho*sigma_a*sigma_b是协方差部分(rho是相关性)。

我在下面添加了我的代码,特别是我在R中使用KFAS包,因此大多数代码与我的问题无关-这是updatefn部分,其中包含协方差矩阵Q,我不确定有人对此进行检查,因为我不确定那一部分:

# This section sets up everything
library('KFAS')
set.seed(1)
xx <- rnorm(1000)
Zt <- matrix(c(1,1,0),1,3)
Ht <- matrix(0)
Tt <- matrix(c(1,0,0,0,NA,NA,0,1,0),3,3,byrow=TRUE)
Rt <- matrix(c(1,0,0,0,1,0,0,0,0),3,3,byrow=TRUE)
Qt <- matrix(c(NA,NA,0,NA,NA,0,0,0,0),3,3,byrow=TRUE)
a1 <- matrix(c(0, 0, 0), 3, 1)
P1 <- matrix(0, 3, 3)
P1inf <- matrix(c(1,0,0,0,1,0,0,0,1),3,3,byrow=TRUE)
model_gaussian <- SSModel(xx  ~ -1 + SSMcustom(Z = Zt, T = Tt, R = Rt, Q = Qt, a1 = a1, P1 = P1, P1inf = P1inf), H = Ht) 

##############################
# RELEVANT PART OF CODE BELOW
#############################

updatefn <- function(pars, model) {

   model$T[is.na(model$T)] <- pars[1:2]  
   model$Q[is.na(model$Q)] <- pars[3:6] # Matrix Q is the Covariance matrix

   model["Q", etas = "custom"] <- crossprod(model$Q) # Creates covariance matrix from estimated parameters

   model
}


fitSSM(model_gaussian, c(0,0, 0.1,0.1,0.1,0.1), updatefn, method = "L-BFGS-B", lower = c(-0.8, -0.8, 0, -Inf, -Inf,0), upper = c(0.8, 0.8, Inf, Inf, Inf, Inf))

代码的最后一行(即fitSSM())基本上是optim()函数的输入,它的输出参数如下:

$optim.out
$optim.out$par
[1] -0.2063339 -0.1199854  0.3001893  0.3001893  0.3001893  0.3001893

(值-0.2063339 -0.1199854用于T矩阵,与我的问题无关)

从optim()函数获得的用于协方差矩阵的参数以0.3001893 0.3001893 0.3001893 0.3001893的形式给出。

我还尝试过通过以下方式修改我的功能:

updatefn <- function(pars, model) {

    model$T[is.na(model$T)] <- pars[1:2]
    Q <- matrix(c(NA,NA,0,NA,NA,0,0,0,0),3,3,byrow=TRUE)

    Q[1,1] <- pars[3]
    Q[2,2] <- pars[6]
    Q[1,2] <- pars[4]
    Q[2,1] <- pars[5]
    Q <- crossprod(Q)

    model$Q[is.na(model$Q)] <- c(Q[1,1],Q[1,2],Q[2,1],Q[2,2])

    model
}

但是此方法仍然无法解决-值Q [1,2]和Q [2,1]应该相等,而且Q [1,2]除以(sqrt(Q [1,1] )* sqrt(Q [2,2]))应该给出相关性,该值是介于-1和1之间的值(不幸的是我没有得到。因此,如果有人可以帮助我,我会很感激,谢谢!

0 个答案:

没有答案
相关问题