在下面的代码中,我尝试将模拟数据的伽马分布与使用该数据计算的 MLE 进行比较。我希望能够完成将产生两个密度之间的空间的积分并将其报告为我的错误。
这些图表可以正常工作,所以我不确定为什么错误计算不是。
提前感谢您的任何帮助!
library("maxLik");
#GAMMA MLE Process
GammaLogLikelihood<- function(t){
# log likelihood for Gamma(alpha,scale=beta)
alpha <- t[1]
beta <- t[2]
loglik <- sum(dgamma(x,t[1],scale=1/t[2],log=TRUE))
return(loglik)
}
GetGammaParameters<-function(x){
start<- mean(x)
GammaEst<-maxLik(GammaLogLikelihood, start=c(start,start))
return(GammaEst$estimate)
}
#Simulation
x<-rgamma(100,3,2);
mleEst<-GetGammaParameters(x);
#Graph
color2 <- rgb(1,0,0,0.2)
color1 <- rgb(0,0,1,0.2)
xax<-seq(0,max(x),.01);
plot(density(x),type="l",xlim=c(0,max(x)),ylim=c(0,1.1));
lines(xax,dgamma(xax,mleEst[1],mleEst[2]),type="l",lty=2);
polygon(density(x),density=-1,col=color1);
polygon(c(xax,max(x)),c(dgamma(xax,mleEst[1],mleEst[2]),0),density=-1,col=color2);
#Find Error
finderror<-function(data,est,l,u){
integrand<-function(x){
abs(data(x)-est(x));
}
integrate(integrand, lower = l, upper = u)
}
dataDensity<-function(x){
density(x)
}
estDensity<-function(x){
dgamma(x,mleEst[1],mleEst[2]);
}
finderror(dataDensity,estDensity,min(x),max(x));