Rom*_*man 5 r glmnet variable-selection
我一直在使用 glmnet R 包为一个目标变量 Y(数字)和 762 个协变量构建 LASSO 回归模型。我使用 glmnet() 函数,然后coef(fit, s = 0.056360)获取该特定 lambda 值的系数值。
我现在需要的是变量选择顺序,即首先选择选定的协变量中的哪一个(首先进入模型),第二个,第三个等等。
使用时,plot(fit, label = TRUE)理论上我可以通过绘制的路径看到顺序,但是,协变量太多,标签难以辨认。
从图像中可以看到,第一个协变量是 267(绿色路径),然后是 12,但其余的难以辨认。

您可以在 中找到沿路径的每个 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)]
Run Code Online (Sandbox Code Playgroud)