我不明白为什么你不想使用内置的glmnet方法,但你肯定可以复制它的结果(这里使用ggplot)。
你仍然需要模型对象来提取lambda值...
编辑:添加了系数与L1范数
复制您的最小示例
library(MASS)
library(glmnet)
library(ggplot2)
library(reshape)
Boston=na.omit(Boston)
x=model.matrix(crim~.,Boston)[,-1]
y=as.matrix(Boston$crim)
lasso.mod =glmnet(x,y, alpha =1)
beta=coef(lasso.mod)
提取coef值并将它们转换为适合于ggplot的长格式整洁形式。
tmp <- as.data.frame(as.matrix(beta))
tmp$coef <- row.names(tmp)
tmp <- reshape::melt(tmp, id = "coef")
tmp$variable <- as.numeric(gsub("s", "", tmp$variable))
tmp$lambda <- lasso.mod$lambda[tmp$variable+1]
tmp$norm <- apply(abs(beta[-1,]), 2, sum)[tmp$variable+1]
使用ggplot绘制图表:coef vs lambda
ggplot(tmp[tmp$coef != "(Intercept)",], aes(lambda, value, color = coef, linetype = coef)) +
geom_line() +
scale_x_log10() +
xlab("Lambda (log scale)") +
guides(color = guide_legend(title = ""),
linetype = guide_legend(title = "")) +
theme_bw() +
theme(legend.key.width = unit(3,"lines"))
![](https://i.imgur.com/UxGzuBi.png)
使用glmnet基本绘图方法是相同的:
par(mfrow = c(1,1), mar = c(3.5,3.5,2,1), mgp = c(2, 0.6, 0), cex = 0.8, las = 1)
plot(lasso.mod, "lambda", label = TRUE)
![](https://i.imgur.com/7PE9u01.png)
使用ggplot绘制图表:coef vs L1 norm
ggplot(tmp[tmp$coef != "(Intercept)",], aes(norm, value, color = coef, linetype = coef)) +
geom_line() +
xlab("L1 norm") +
guides(color = guide_legend(title = ""),
linetype = guide_legend(title = "")) +
theme_bw() +
theme(legend.key.width = unit(3,"lines"))
![](https://i.imgur.com/wW1cSoq.png)
对于基本的glmnet方法,情况是相同的:
par(mfrow = c(1,1), mar = c(3.5,3.5,2,1), mgp = c(2, 0.6, 0), cex = 0.8, las = 1)
plot(lasso.mod, "norm", label = TRUE)
![](https://i.imgur.com/S5vfWn0.png)
此内容是由reprex包(v0.2.0)于2018年2月26日创建的。
plot(lasso.mod)
可以实现这个功能,请提供数据集以使示例可重现(可能从r包中加载?) - Gilles San Martinlasso.mod
的情况下绘制beta值的图表。 - Majklasso.mod =glmnet(x,y, alpha =1)
,然后使用coef(lasso.mod)
和/或plot(lasso.mod)
。 - Gilles San Martin