gpt4 book ai didi

r - 如何在 stepAIC 中计算 AIC

转载 作者:行者123 更新时间:2023-12-04 11:42:58 29 4
gpt4 key购买 nike

这是来自 ?lm 的一个非常简单的 lm 模型

ctl <- c(4.17,5.58,5.18,6.11,4.50,4.61,5.17,4.53,5.33,5.14)
trt <- c(4.81,4.17,4.41,3.59,5.87,3.83,6.03,4.89,4.32,4.69)
group <- gl(2,10,20, labels=c("Ctl","Trt"))
weight <- c(ctl, trt)
lm.D9 <- lm(weight ~ group)

如果我使用 stepAIC 到 lm.D9,在第一行它说 AIC = -12.58
require(MASS)
stepAIC(lm.D9)

如果我直接在 lm.D9 上使用 AIC,它会给出不同的值 46.17648
AIC(lm.D9)

我的问题是为什么 2 个 AIC 值不同。谢谢!

最佳答案

这让我很恼火,所以我决定从首要原则来解决它。

重新拟合模型:

d <- data.frame(weight=
c(ctl=c(4.17,5.58,5.18,6.11,4.50,4.61,5.17,4.53,5.33,5.14),
trt=c(4.81,4.17,4.41,3.59,5.87,3.83,6.03,4.89,4.32,4.69)),
group=gl(2,10,20, labels=c("Ctl","Trt")))
lm.D9 <- lm(weight ~ group, d)

标准访问器返回的值:
(AIC1 <- AIC(lm.D9))
> 46.17468
(LL1 <- logLik(lm.D9))
> -20.08824 (df=3)

从第一性原理重构:
n <- nrow(d)
ss0 <- summary(lm.D9)$sigma
ss <- ss0*(n-1)/n
(LL2 <- sum(dnorm(d$weight,fitted(lm.D9),
sd=ss,log=TRUE)))
> -20.08828

这有点不对劲,还没发现毛病。

参数数量:
npar <- length(coef(lm.D9))+1 


(AIC2 <- -2*LL2+2*npar)
> 46.1756

仍然超过数字模糊,但只有大约百万分之一。

现在让我们看看 stepAIC是在做:
MASS::stepAIC(lm.D9)  ## start: AIC = -12.58
extractAIC(lm.D9) ## same value (see MASS::stepAIC for details)
stats:::extractAIC.lm ## examine the code


RSS1 <- deviance(lm.D9) ## UNSCALED sum of squares
RSS2 <- sum((d$weight-fitted(lm.D9))^2) ## ditto, from first principles
AIC3 <- n*log(RSS1/n)+2*2 ## formula used within extractAIC

您可以从 sigma-hat=RSS/n 计算出上面使用的公式——或者查看 Venables 和 Ripley MASS 以获得推导。

添加缺失项:未计数的方差参数,加上归一化常数
(AIC3 + 2 - 2*(-n/2*(log(2*pi)+1)))

这与 AIC1 完全相同(到 1e-14)以上

关于r - 如何在 stepAIC 中计算 AIC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8374025/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com