r - R:与 R 中的 glm 和 mle2 包不同的结果
问题描述
所以我想使用 GLM 找到估计参数并将其与 mle2 包进行比较。这是我的 GLM 代码
d <- read.delim("http://dnett.github.io/S510/Disease.txt")
d$disease=factor(d$disease)
d$ses=factor(d$ses)
d$sector=factor(d$sector)
str(d)
glm2 <- glm(disease~ses+sector, family=binomial(link=logit), data=d)
summary(glm2)
我的 mle2() 代码
y<-as.numeric(as.character(d$disease))
x1<-as.numeric(as.character(d$age))
x2<-as.numeric(as.character(d$sector))
x3<-as.numeric(as.character(d$ses))
library(bbmle)
nlldbin=function(A,B,C,D){
eta<-A+B*(x3==2)+C*(x3==3)+D*(x2==2)
p<-1/(1+exp(-eta))
joint.pdf= (p^y)*((1-p)^(1-y))
-sum(joint.pdf, log=TRUE ,na.rm=TRUE)
}
st <- list(A=0.0001,B=0.0001,C=0.0001,D=0.0001)
est_mle2<-mle2(start=st,nlldbin,hessian=TRUE)
summary(est_mle2)
但结果却截然不同。请帮我解决这个问题,谢谢!
> summary(est_mle2)
Maximum likelihood estimation
Call:
mle2(minuslogl = nlldbin, start = st, hessian.opts = TRUE)
Coefficients:
Estimate Std. Error z value Pr(z)
A -20.4999 5775.1484 -0.0035 0.9972
B -5.2499 120578.9515 0.0000 1.0000
C -7.9999 722637.2670 0.0000 1.0000
D -2.2499 39746.6639 -0.0001 1.0000
> summary(glm2)
Call:
glm(formula = disease ~ ses + sector, family = binomial(link = logit),
data = d)
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) -1.52001 0.33514 -4.535 5.75e-06 ***
ses2 -0.08525 0.41744 -0.204 0.838177
ses3 0.16086 0.39261 0.410 0.682019
sector2 1.28098 0.34140 3.752 0.000175 ***
解决方案
这条线
-sum(joint.pdf, log=TRUE ,na.rm=TRUE)
是错的。sum
没有特殊的log
论点;您正在做的是将值TRUE
(转换为 1)添加到 pdf 中。
你想要的是
-sum(log(joint.pdf), na.rm=TRUE)
但由于数字原因,这也不是很好,因为 pdf 可能会下溢。更好的写作方式是
logpdf <- y*log(p) + (1-y)*log(1-p)
-sum(logpdf, na.rm=TRUE)
推荐阅读
- java - 单击菜单项时如何显示 JavaFX 网络视图?
- javascript - Javascript html 字符串连接 Uncaught SyntaxError: missing ) 在参数列表之后
- python - 在 Python 中为套接字使用选择器模块
- angularjs - 如何将锚点 href 调用重定向到索引数据库并下载文档
- xml - 如何生成 XML 文件的元数据?
- php - WAMP ~ 自定义 url 处理在项目文件夹中不起作用
- java - 检索哈希数,git编译war
- ios - 观察 UINavigationController 导航栏显示/隐藏
- php - 为什么我不能使用 composer 创建 Laravel 项目?
- hadoop - 使用 Sqoop 将列的子集从 RDBMS 导入 Hive 表