为什么我从优化得到错误的hessian矩阵,从而得到错误的协方差矩阵?

时间:2018-03-11 17:33:32

标签: optimization regression covariance mle hessian-matrix

我尝试为数据集运行MLE。我得到了与glm相同的系数。我通过使用优化中的粗糙矩阵的结果来计算渐近协方差矩阵,并且对于协方差矩阵,得到的结果与glm几乎不相同。我的错误在哪里? 谢谢!

 logLikePois <- function(y, x, parameter) {

      betaKoef <- parameter

      lambda <- exp(betaKoef %*% t(x))

      logLikeliHood <- sum(dpois(y, lambda, log = TRUE))

      return(-logLikeliHood)

    }

    grad <- function (y,x,parameter){
      betaKoef <- parameter

      lambda <- exp(betaKoef%*%t(x))
      gradient <-  -((y-lambda)%*%(x))
      return(gradient)
    }

    data(discoveries)
    disc <- data.frame(count=as.numeric(discoveries),
                       year=seq(0,(length(discoveries)-1),1))

    yearSqr <- disc$year^2

    formula <- count~  year + yearSqr

    form <- formula(formula)

    model <- model.frame(formula, data = disc)

    x <- model.matrix(formula, data = disc)

    y <- model.response(model)

    parFullModell <- rep(0,ncol(x))

    optimierung <- optim(par = parFullModell,gr=grad, fn = logLikePois,
                         x = x, y = y, method = "BFGS" ,hessian = TRUE)

    covVar <- solve(optimierung$hessian)
    covVar
    TEST <- summary(glm(count ~ year + yearSqr,family = "poisson", disc))
    TEST$cov.unscaled

0 个答案:

没有答案