这是一个关于如何运行 glmnet 的示例:
library(glmnet)
library(tidyverse)
df 是您提供的数据集。
选择 y 变量:
y <- df$SP.DYN.TFRT.IN
选择数值变量:
df %>%
select(-SP.DYN.TFRT.IN, -region, -country.code) %>%
as.matrix() -> x
选择因子变量并转换为虚拟变量:
df %>%
select(region, country.code) %>%
model.matrix( ~ .-1, .) -> x_train
运行模型,这里的几个参数可以调整我建议检查documentation。这里我只是运行 5 折交叉验证来确定最佳 lambda
cv_fit <- cv.glmnet(x, y, nfolds = 5) #just with numeric variables
cv_fit_2 <- cv.glmnet(cbind(x ,x_train), y, nfolds = 5) #both factor and numeric variables
par(mfrow = c(2,1))
plot(cv_fit)
plot(cv_fit_2)
最佳 lambda:
cv_fit$lambda[which.min(cv_fit$cvm)]
最佳系数 lambda
coef(cv_fit, s = cv_fit$lambda[which.min(cv_fit$cvm)])
相当于:
coef(cv_fit, s = "lambda.min")
在运行coef(cv_fit, s = "lambda.min") 后,结果表中带有- 的所有特征都将从模型中删除。这种情况对应于图中左侧垂直虚线所描绘的左侧 lambda。
我建议阅读链接文档 - 如果您了解一点线性回归并且包非常直观,那么弹性网络很容易掌握。我还建议阅读ISLR,至少是 L1 / L2 正则化的部分。这些视频:1、2、34、5、6,前三个是关于通过测试错误估计模型性能,后三个是关于手头的问题。这个one 是如何在 R 中实现这些模型。顺便说一下视频中的这些人发明了 LASSO 并制作了 glment。
还可以查看glmnetUtils 库,它提供了公式界面和其他不错的功能,例如内置混合参数 (alpha) 选择。这是vignette。