如何将glmnet模型的系数导入数据帧?

时间:2017-11-28 21:32:43

标签: r glmnet

我用插入符号培训了一个glmnet模型

pen.params = expand.grid(lambda = exp(seq(-3,3,0.05)) , alpha = 1 )

model.penalized = train(y~.,
                        data = d.train,
                        trControl = fitControl,
                        tuneGrid = pen.params,
                        method = 'glmnet'
                        )

我可以使用各种工具绘制系数,但我希望将它们放在数据框中。我尝试使用broom来提取系数 使用tidy,但这只给出了非零系数。

是否有一种简单的方法可以从模型中提取系数和惩罚参数,并将它们作为数据框中的列?

1 个答案:

答案 0 :(得分:1)

dfCoef <- data.frame(lambda=model.penalized$finalModel[['lambda']],
          as.matrix(t(model.penalized$finalModel[['beta']])))
dfCoef[1:10,]

#           lambda          X2           X3          X4         X5
# s0  0.1608367514 0.000000000  0.000000000 0.000000000 0.00000000
# s1  0.1465484577 0.000000000  0.000000000 0.000000000 0.01347397
# s2  0.1335294966 0.000000000  0.000000000 0.000000000 0.02575094
# s3  0.1216671042 0.000000000  0.000000000 0.000000000 0.03693727
# s4  0.1108585340 0.000000000  0.000000000 0.000000000 0.04712983
# s5  0.1010101674 0.000000000  0.000000000 0.000000000 0.05641691
# s6  0.0920367025 0.000000000  0.000000000 0.000000000 0.06487896
# s7  0.0838604155 0.000000000  0.000000000 0.000000000 0.07258926
# s8  0.0764104873 0.000000000 -0.006189269 0.000000000 0.07905622
# s9  0.0696223902 0.000000000 -0.011967900 0.000000000 0.08493612
# s10 0.0634373290 0.003340502 -0.016868476 0.000000000 0.09006299
# ...