【问题标题】:Obtain variable selection order from glmnet从 glmnet 获取变量选择顺序
【发布时间】:2022-01-14 03:04:35
【问题描述】:

我一直在使用 glmnet R 包为一个目标变量 Y(数字)和 762 个协变量构建 LASSO 回归模型。我使用 glmnet() 函数,然后使用coef(fit, s = 0.056360) 来获取特定 lambda 值的系数值。

我现在需要的是变量选择顺序,即先选择哪个协变量(先进入模型),第二个,第三个等等。

当使用plot(fit, label = TRUE) 时,理论上我可以通过绘制的路径看到顺序,但是,协变量太多,标签难以辨认。

从图中可以看出,第一个协变量是 267(绿色路径),然后是 12,但其余的都难以辨认。

【问题讨论】:

    标签: r glmnet variable-selection


    【解决方案1】:

    您可以在fit$beta 中找到沿路径的每个 lambda 的拟合模型。获得所需内容的一种方法是遍历该矩阵并检查每个变量在哪一步进入模型。然后,您可以使用该信息对变量列表进行排序。这是一种快速而简单的方法:

    # Convert the beta table to a matrix object:
    betas <- as.matrix(fit$beta)
    
    # Get a list of the variable names:
    varlist <- row.names(betas)
    
    # Loop over all variables and check when they enter the model:
    which_step <- rep(NA, length(varlist))
    for(i in 1:length(varlist))
    {
          # The variable enters the model at the first step where it's non-zero:
          which_step[i] <- which.max(betas[i,] != 0)
    }
    
    # Order the list of variables after when they enter the model:
    varlist[order(which_step)]
    

    【讨论】:

      【解决方案2】:

      您的系数存储在:

      head(fit$beta[,1:6])
      6 x 6 sparse Matrix of class "dgCMatrix"
           s0          s1         s2         s3        s4         s5
      cyl   . -0.01192151 -0.1447790 -0.2658654 -0.376195 -0.4770942
      disp  .  .           .          .          .         .        
      hp    .  .           .          .          .         .        
      drat  .  .           .          .          .         .        
      wt    . -0.45776130 -0.7006176 -0.9218541 -1.123436 -1.3065806
      qsec  .  .           .          .          .         .      
      

      你可以得到类似这样的情节:

      plot(fit$beta, col = rep(1:nrow(fit$beta),ncol(fit$beta)),pch=20,cex=0.3)
      

      假设我使用 lambda 值 s31 :

      lambda_values = data.frame(name = colnames(fit$beta),fit$lambda)
      
      subset(lambda_values,name=="s31")
         name fit.lambda
      32  s31  0.2877579
      

      我们将矩阵拉到那个 lambda 值:

      mat = fit$beta[,1:which(colnames(fit$beta)=="s31")]
      

      并编写一个函数来返回第一个非零系数的索引,如果全部为零,则返回最后一个:

      first_nonzero = function(x){
                      if(any(x!=0)){
                           min(which(x!=0))
                      }else{
                           length(x)
                      }
                      }
      

      将此应用于每一行,我们会得到他们第一次输入的索引:

      apply(mat,1,first_nonzero)
      
       cyl disp   hp drat   wt qsec   vs   am gear carb 
         2   32   10   26    2   30   30   23   32   24 
                       
      

      【讨论】:

        猜你喜欢
        • 2014-05-22
        • 1970-01-01
        • 2016-04-26
        • 2015-11-12
        • 2016-10-24
        • 2015-01-20
        • 1970-01-01
        • 1970-01-01
        • 2020-03-01
        相关资源
        最近更新 更多