基于R 4.2.2版本演示
一、写在前面
花了好几期分享了使用R语言实现机器学习分类,基本把常见模型都讲完了。
最后就以Lasso回归收尾得了。
Lasso回归应该很出名了,做特征变量筛选的,因此,不过多介绍。
二、R代码实现Lasso回归
(1)导入数据
我习惯用RStudio自带的导入功能:
(2)建立Lasso回归模型(默认参数)
# 安装并加载 glmnet 库(如果尚未加载)
# install.packages("glmnet")
library(glmnet)
library(ggplot2)
# 准备数据
x_train <- model.matrix(~ . -X, data = trainData)
y_train <- as.numeric(trainData$X) - 1
# 训练 LASSO 回归模型
lassoModel <- glmnet(x_train, y_train, family = "binomial", alpha = 1)
# 使用交叉验证找到最优 lambda 值
cv_lasso <- cv.glmnet(x_train, y_train, family = "binomial", type.measure = "mse", alpha = 1)
# 选择一个 lambda 值
lambda_min <- cv_lasso$lambda.min
lambda_1se <- cv_lasso$lambda.1se
# 输出最优 lambda 值
cat("Lambda.min:", lambda_min, "\n")
cat("Lambda.1se:", lambda_1se, "\n")
# 提取系数(使用 lambda.min)
coef_lasso <- coef(cv_lasso, s = "lambda.min")
# 转换为数据框并过滤非零系数
coef_lasso_matrix <- as.matrix(coef_lasso)
# 提取非零系数(忽略截距)
important_features <- coef_lasso_matrix[coef_lasso_matrix[, 1] != 0, , drop = FALSE]
# 显示重要特征
print("Important Features from LASSO Regression:")
print(important_features)
结果输出:
把每一个特征的重要性进行了量化输出。
三、Lasso回归结果可视化
下一步,就是如何把Lasso回归模型的输出可视化,这里有几种方式:
(1)柱状图
# 创建一个数据框用于图形展示
important_features_df <- data.frame(
Feature = rownames(important_features),
Coefficient = important_features[, 1]
)
# 绘制重要特征的系数图
ggplot(important_features_df, aes(x = reorder(Feature, Coefficient), y = Coefficient)) +
geom_col(fill = "steelblue") +
labs(title = "Important Features in LASSO Model",
x = "Feature",
y = "Coefficient") +
theme_minimal() +
theme(axis.text.x = element_text(angle = 65, hjust = 1))
输出:
(2)棒棒糖图
# 绘制棒棒糖图展示系数
ggplot(important_features_df, aes(x = reorder(Feature, Coefficient), y = Coefficient)) +
geom_segment(aes(x = Feature, xend = Feature, y = 0, yend = Coefficient), color = "grey") +
geom_point(size = 3, color = "blue") +
labs(title = "Lollipop Chart of LASSO Coefficients",
x = "Feature",
y = "Coefficient") +
theme_minimal() +
theme(axis.text.x = element_text(angle = 65, hjust = 1))
输出:
(3)Coefficient Path
library(glmnet)
# 准备数据
# 确保 data$X 已被转换为因子
x_train <- model.matrix(~ . - X, data = trainData)
y_train <- as.numeric(trainData$X) - 1
# 训练 LASSO 回归模型,允许 glmnet 自动生成 lambda 序列
lassoModel <- glmnet(x_train, y_train, family = "binomial", alpha = 1)
# 绘制系数路径图,确保使用变量名称作为标签
plot(lassoModel, xvar = "lambda", label = TRUE, xlab = "Log(Lambda)", ylab = "Coefficients")
# 添加图表标题
title("Coefficient Path for LASSO Model")
输出:
至于上述结果怎么看,自行GPT啦。
四、最后
至于怎么安装,自学了哈。
数据嘛:
链接:https://pan.baidu.com/s/1rEf6JZyzA1ia5exoq5OF7g?pwd=x8xm
提取码:x8xm