使用dnbinom()

时间:2016-10-22 03:27:43

标签: r regression modeling

我使用dnbinom()来编写对数似然函数,然后使用R中的mle2() {bbmle}估算参数。

问题是我的负二项模型有16个警告,所有这些NaN都像这样生成:

  

1:在dnbinom(y,mu = mu,size = k,log = TRUE):生成NaNs

我的代码:

# data
x <- c(0.35,0.45,0.90,0.05,1.00,0.50,0.45,0.25,0.15,0.40,0.26,0.37,0.43,0.34,0.00,0.11,0.00,0.00,0.00,0.41,0.14,0.80,0.60,0.23,0.17,0.31,0.30,0.00,0.23,0.33,0.30,0.00,0.00)
y <- c(1,10,0,0,67,0,9,5,0,0,0,82,36,0,32,7,7,132,14,33,0,67,11,39,41,67,9,1,44,62,111,52,0)

# log-likelihood function
negbinglmLL = function(beta,gamma,k) { 
  mu= exp(beta+gamma*x)
  -sum(dnbinom(y,mu=mu, size=k, log=TRUE))
}

# maximum likelihood estimator
model <- mle2(negbinglmLL, start=list(beta=mean(y), gamma= 0, k=mean(y)^2/(var(y)-mean(y))))

这些警告意味着什么,如果这是一个严重的问题,我该如何避免呢?

1 个答案:

答案 0 :(得分:0)

您并未限制负对数似然函数尝试k的负值。这个可能并没有弄乱你的最终答案,但如果可以的话,最好避免这些警告。两个简单的策略:

  • k上设置下限(切换到method=L-BFGS-B
  • 在日志范围内拟合k参数,如下所示:
negbinglmLL = function(beta,gamma,logk) { 
  mu= exp(beta+gamma*x)
  -sum(dnbinom(y,mu=mu, size=exp(logk), log=TRUE))
}

model <- mle2(negbinglmLL,
              start=list(beta=mean(y),
                         gamma= 0, 
                      logk=log(mean(y)^2/(var(y)-mean(y)))))

顺便说一句,对于像这样的简单问题,您可以使用基于公式的快捷方式,如下所示:

mle2(y~dnbinom(mu=exp(logmu),size=exp(logk)),
     parameters=list(logmu~x),
     start=list(logmu=0,logk=0),
     data=data.frame(x,y))

对于这个简单的情况,MASS::glm.nb也应该能够很好地工作(但也许这是最简单的版本,会变得更加复杂/超出glm.nb的范围。)