然而,我在尝试手动编码 BIC/AIC 时遇到了困难。 R 或 Python 中是否有任何软件包可以帮助我实现这一点?任何示例代码都会有很大帮助。
谢谢
最佳答案
这里是a link一些计算 AIC 和 BIC 以及前向/后向/逐步变量选择的示例 R 代码。所有功劳都归功于乔·哈丁。为了方便起见,我将复制下面的部分代码,并稍微编辑一下格式:
> sat.data <- read.table("sat.csv", header=T, sep=",")
> attach(sat.data)
> sat.n <- nrow(sat.data) # be careful with missing values!!
> ltakers <- log(takers) # variable is quite right skewed
R 中的 AIC 和 BIC
方法一:
> sat.lm0 <- lm(sat ~ 1)
> summary(sat.lm0)
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 948.45 10.21 92.86 <2e-16 ***
---
Signif. codes: 0 *** 0.001 ** 0.01 * 0.05 . 0.1 1
Residual standard error: 71.5 on 48 degrees of freedom
> sat.sse0 <- sum(resid(sat.lm0) ^2)
> sat.n + sat.n*log(2*pi) + sat.n * log(sat.sse0 / sat.n) + 2 * (1+1)
[1] 560.4736
> AIC(sat.lm0, k=2)
[1] 560.4736
> sat.n + sat.n * log(2*pi) + sat.n*log(sat.sse0/sat.n) + log(sat.n)*(1+1)
[1] 564.2573
> AIC(sat.lm0, k=log(sat.n))
[1] 564.2573
方法2:
> sat.lm1 <- lm(sat ~ ltakers)
> summary(sat.lm1)
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 1112.408 12.386 89.81 <2e-16 ***
ltakers -59.175 4.167 -14.20 <2e-16 ***
---
Signif. codes: 0 *** 0.001 ** 0.01 * 0.05 . 0.1 1
Residual standard error: 31.41 on 47 degrees of freedom
Multiple R-squared: 0.811, Adjusted R-squared: 0.807
F-statistic: 201.7 on 1 and 47 DF, p-value: < 2.2e-16
> sat.sse1 <- sum(resid(sat.lm1) ^2)
> sat.n + sat.n*log(2*pi) + sat.n * log(sat.sse1 / sat.n) + 2 * (2+1)
[1] 480.832
> AIC(sat.lm1, k=2)
[1] 480.832
> sat.n + sat.n * log(2*pi) + sat.n*log(sat.sse1/sat.n) + log(sat.n) * (2+1)
[1] 486.5075
> AIC(sat.lm1, k=log(sat.n))
[1] 486.5075
关于python - 如何在 Python 或 R 中获取用于选择主成分数量的 BIC/AIC 图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55091005/