使用dnbinom()在负二项式回归中产生的NaN [英] NaNs produced in negative binomial regression when using dnbinom()
问题描述
我正在使用dnbinom()
编写对数似然函数,然后使用R中的mle2()
{bbmle}估计参数.
I am using dnbinom()
for writing the log-likelihood function and then estimate parameters using mle2()
{bbmle} in R.
问题是我的负二项式模型收到了16条警告,所有的NaN都是这样产生的:
The problem is that I got 16 warnings for my negative binomial model, all of them NaNs produced like this one:
1:在dnbinom中(y,mu = mu,大小= k,log = TRUE):产生了NaNs
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))))
这些警告是什么意思,如果这是一个严重的问题,我该如何避免呢?
What do these warnings mean, and if this is a serious problem how can I avoid it?
推荐答案
您没有在限制负对数可能性函数尝试使用k
的负值.这个可能不会弄乱您的最终答案,但是如果可以的话,最好避免出现此类警告.两种简单的策略:
You're not restricting the negative log-likelihood function from trying negative values of k
. This probably doesn't mess up your final answer, but it's always best to avoid these kinds of warnings if you can. Two simple strategies:
- 在
k
上设置一个下限(切换到method=L-BFGS-B
) - 使
k
参数适合对数刻度,如下所示:
- put a lower bound on
k
(switching tomethod=L-BFGS-B
) - fit the
k
parameter on the log scale, as follows:
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)))))
顺便说一句,对于像这样的简单问题,您可以使用基于公式的快捷方式,如下所示:
By the way, for simple problems like this you can use a formula-based shortcut as follows:
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
的范围).
For this simple case MASS::glm.nb
should also work perfectly well (but perhaps this is the simplest version of something that will get more complicated/beyond the scope of glm.nb
).
这篇关于使用dnbinom()在负二项式回归中产生的NaN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!