强制模型系数来清理2列数据帧

问题描述 投票:0回答:2

我正在使用交叉验证的弹性网络,我正在研究每个预测器的系数有多大:

lambda <- cv.glmnet(x = features_training, y = outcomes_training, alpha = 0)
elnet <- lambda$glmnet.fit
coefs <- coef(elnet, s = lambda$lambda.min, digits = 3)

coefs变量包含一个dgCMatrix:

                           1
(Intercept)    -1.386936e-16
ret             4.652863e-02
ind30          -2.419878e-03
spyvol          1.570406e-02

有没有一种快速方法可以将其转换为具有2列的数据帧(一个用于预测器名称,另一个用于系数值)? as.data.frameas.matrix或chaining都不起作用。我特别想根据第二列对行进行排序。

r dataframe glmnet coefficients
2个回答
1
投票

另一种方式,并没有通过attributes()功能,但提取rownames和矩阵值。 attributes(class(coefs))通知dgCMatrix是使用Matrix包创建的稀疏矩阵。

data.frame( predict_names = rownames(coefs),
            coef_vals = matrix(coefs))

# predict_names    coef_vals
# 1    (Intercept) 21.117339411
# 2    (Intercept)  0.000000000
# 3            cyl -0.371338786
# 4           disp -0.005254534
# 5             hp -0.011613216
# 6           drat  1.054768651
# 7             wt -1.234201216
# 8           qsec  0.162451314
# 9             vs  0.771959823
# 10            am  1.623812912
# 11          gear  0.544171362
# 12          carb -0.547415029

2
投票

broom::tidy有一个很好的方法来强制dgCMatrix对象到长格式数据框架(有点像as.data.frame.table),这在这里工作得很好:

mod <- glmnet::cv.glmnet(model.matrix(~ ., mtcars[-1]), mtcars$mpg, alpha = 0)

broom::tidy(coef(mod$glmnet.fit, s = mod$lambda.min, digits = 3))
#>            row column        value
#> 1  (Intercept)      1 21.171285892
#> 2          cyl      1 -0.368057153
#> 3         disp      1 -0.005179902
#> 4           hp      1 -0.011713150
#> 5         drat      1  1.053216800
#> 6           wt      1 -1.264212476
#> 7         qsec      1  0.164975032
#> 8           vs      1  0.756163432
#> 9           am      1  1.655635460
#> 10        gear      1  0.546651086
#> 11        carb      1 -0.559817882
© www.soinside.com 2019 - 2024. All rights reserved.