R:从 GLMNet 获取 AIC/BIC/Likelihood

R: Getting AIC/BIC/Likelihood from GLMNet

我想知道是否可以从 GLMNet 获取 AIC 和 BIC。我发现 glmnet.cr 似乎可以做到,但我的回答是时间,而不是顺序。我可以自己根据可能性计算它,但 glmnet 也不会 return。

切线:我真的可以 return l1norm 吗?我觉得应该是

fit$norm

但好像不是。 (我知道它说不要拉出数字但我实际上没有使用 R)

在此先感谢您的帮助。

我一直在努力寻找一种方法来计算 glmnet 模型的 AIC 和 BIC。但是,经过大量搜索后,我在 google 结果的第三页找到了答案。可以找到here。我将它发布在这里供未来的读者使用,因为我相信我不会是唯一的读者。

最终我实现了AIC和BIC的方式如下:

fit <- glmnet(x, y, family = "multinomial") 

tLL <- fit$nulldev - deviance(fit)
k <- fit$df
n <- fit$nobs
AICc <- -tLL+2*k+2*k*(k+1)/(n-k-1)
AICc

BIC<-log(n)*k - tLL
BIC

不幸的是,我无法使用此公式从 "normal" glm 模型(内置函数 BIC 作为正确参考)重现 BIC

我更改了上面建议的代码以使其适用于 glm 对象:

    #BIC function for glm according to Whosebug
    BICAICglm=function(fit){
      tLL <- fit$null.deviance - deviance(fit)
      k <- dim(model.matrix(fit))[2]
      n <- nobs(fit)
      AICc <- -tLL+2*k+2*k*(k+1)/(n-k-1)
      AICc

      BIC<-log(n)*k - tLL
      res=c(AICc, BIC)
      names(res)=c("AICc", "BIC")
      return(res)
    }

    #some data simulation to test
    set.seed(123)
    x=rnorm(20)
    set.seed(231)
    y=as.numeric(x+rnorm(20)<0)

    #the model
    glm1=glm(y~x, family="binomial")

现在,当我们应用标准 BIC() 函数时,我们得到模型的 "true" BIC,然后我们可以将其与此处建议的函数进行比较。

    BIC(glm1)
    [1] 23.68755

和新的:

    BICAICglm(glm1)
    AICc       BIC 
    -4.518496 -3.232914 

所以这样计算BIC和AICc的方法不太对

根据@merten的回答,我修正了公式。现在它匹配内置函数。

总结,

  1. 原始对数似然 (tLL) 存在偏差。
  2. 添加了内置函数中的 AIC 和 AICc 以进行比较。
BICAICglm=function(fit){
  #tLL <- fit$null.deviance - deviance(fit)  
  tLL <- -deviance(fit) # 2*log-likelihood
  k <- dim(model.matrix(fit))[2]
  n <- nobs(fit)
  AICc <- -tLL+2*k+2*k*(k+1)/(n-k-1)
  AIC_ <- -tLL+2*k

  BIC<-log(n)*k - tLL
  res=c(AIC_, BIC, AICc)
  names(res)=c("AIC", "BIC", "AICc")
  return(res)
}
#some data simulation to test
set.seed(123)
x=rnorm(20)
set.seed(231)
y=as.numeric(x+rnorm(20)<0)

#the model
glm1=glm(y~x, family="binomial")

结果

BICAICglm(glm1)
     AIC      BIC     AICc 
21.91018 23.90165 22.61607

根据内置函数回答

AIC(glm1)
[1] 21.91018
BIC(glm1)
[1] 23.90165

AICc 小样本量校正

AIC(glm1, k=2*nobs(glm1)/(nobs(glm1)-1-glm1$rank))
[1] 22.61607