使用 dnbinom() 时在负二项回归中产生的 NaN

NaNs produced in negative binomial regression when using dnbinom()

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

问题是我的负二项式模型收到了 16 个警告,所有这些都是 NaN,如下所示:

1: In dnbinom(y, mu = mu, size = k, log = TRUE) : NaNs produced

我的代码:

# 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))))

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

您并未限制负对数似然函数尝试 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 也应该可以很好地工作(但也许这是最简单的版本,它将获得更多 complicated/beyond glm.nb 的范围)。