如何获得 BIC/AIC 图以选择 Python 或 R 中的主成分数量

How to get BIC/AIC plot for selecting number of Principal Components in Python or R

我想要这样的图来选择 PCA 中的组件数量:

然而,我一直在尝试手动编码 BIC/AIC。 R 或 Python 中是否有任何包可以帮助我得到这个?任何示例代码都会有很大帮助。

谢谢

这里是 a link 一些计算 AIC 和 BIC 的示例 R 代码,以及 forward/backward/stepwise 变量选择。所有功劳都归功于 Jo Hardin。为方便起见,我将复制下面的部分代码,对格式进行了轻微编辑:

> 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

方法二:

> 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