3

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

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

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

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

协变量路径

4

2 回答 2

0

您的系数存储在:

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 
                 
于 2021-12-10T12:24:47.100 回答
0

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

# 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)]
于 2021-12-10T11:33:54.663 回答