我正在尝试获得似然比检验的功效,以便将伽马分布与广义伽马分布进行比较。因此,我需要使用三个参数对广义伽玛分布进行最大似然估计。我编写的代码如下。
library(bbmle)
library(flexsurv)
sig=0.05
den=1000
n=30
apar=2 ###alfa
bpar=3 ##beta
cpar=4 ##c parametresi
LRatio=function(den,n,par=c(cpar,apar,bpar)){
LR2=rep(0,den)
count=rep(0,den)
cpar=par[1]
apar=par[2]
bpar=par[3]
for(i in 1:den){
y=rgengamma.orig(n,shape=cpar,scale=bpar,k=apar)
gamma4 = function(shape, scale) {
-sum(dgamma(y, shape = shape, scale = scale,log = TRUE))
}
gm = mean(y)
cv = var(y)/mean(y)
m5 = mle2(gamma4, start = list(shape = gm/cv, scale = cv),method = "L-BFGS-B", lower =c(.00001,.00001),upper = c(Inf,Inf))
gengamma3 = function(shape, scale,k) {
-sum(dgengamma.orig(y, shape = shape, scale = scale,k=k,log =TRUE))
#-(n*log(abs(shape))-n*shape*k*log(scale)+(shape*k-1)*sum(log(y))-n*log(exp(lgamma(k)))-sum((y/scale)^shape))
}
ci=mean(y) #c initial value
a1=ci*mean(y)^(ci-1)
a2=ci*(ci-1)*(mean(y)^(ci-1))/2
mu1=mean(y)^ci+a2*mean(y^2)
mu2=(a1^2)*mean(y^2)+2*a1*a2*mean(y^3)+(a2^2)*(mean(y^4)-mean(y^2)^2)
alp =(mu1^2)/mu2 #alpha initial value
bet=mean(y)*gamma(alp)/gamma(alp+(1/ci)) #beta initial value
m6 = mle2(gengamma3,start = list(shape = ci, scale = bet, k=alp),method = "L-BFGS-B", lower = c(0, 0,0),upper = c(Inf, Inf, Inf))
LR2[i]=2*(logLik(m6)-logLik(m5))
count[i]=LR2[i]>=qchisq(1-sig, df=1)
}
pow=sum(count)/den
print(i)
print(pow)
}
但我收到了错误:
optim(par = c(3.88907163215354, 3.62005456122935, 1.66499331462506 :
L-BFGS-B needs finite values of 'fn'
有什么问题?