我在R语言中编写了这段Lasso代码,并得到了一些beta值:
#Lassolibrary(MASS)library(glmnet)Boston=na.omit(Boston)x=model.matrix(crim~.,Boston)[,-1]rownames(x)=c()y=as.matrix(Boston$crim)lasso.mod =glmnet(x,y, alpha =1, lambda = 0.1)beta=as.matrix(rep(0,19))beta=coef(lasso.mod)matplot(beta,type="l",lty=1,xlab="L1",ylab="beta",main="lasso")
我想像这样绘制这些beta值:
但我不知道在R中可以使用哪个绘图函数来实现这一点。
回答:
我不明白你为什么不想使用内置的glmnet方法,但你当然可以重现其结果(这里使用ggplot)。
你仍然需要模型对象来提取lambda值…
编辑:添加了系数与L1范数的对比
重现你的最小示例
library(MASS)library(glmnet)#> Le chargement a nécessité le package : Matrix#> Le chargement a nécessité le package : foreach#> Loaded glmnet 2.0-13library(ggplot2)library(reshape)#> #> Attachement du package : 'reshape'#> The following object is masked from 'package:Matrix':#> #> expandBoston=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)
提取系数值并将其转换为适合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] # 提取lambda值tmp$norm <- apply(abs(beta[-1,]), 2, sum)[tmp$variable+1] # 计算L1范数
使用ggplot绘制:系数与lambda
# x11(width = 13/2.54, height = 9/2.54)ggplot(tmp[tmp$coef != "(Intercept)",], aes(lambda, value, color = coef, linetype = coef)) + geom_line() + scale_x_log10() + xlab("Lambda (对数刻度)") + guides(color = guide_legend(title = ""), linetype = guide_legend(title = "")) + theme_bw() + theme(legend.key.width = unit(3,"lines"))
使用基础绘图glmnet方法相同的结果:
# x11(width = 9/2.54, height = 8/2.54)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)
使用ggplot绘制:系数与L1范数
# x11(width = 13/2.54, height = 9/2.54)ggplot(tmp[tmp$coef != "(Intercept)",], aes(norm, value, color = coef, linetype = coef)) + geom_line() + xlab("L1范数") + guides(color = guide_legend(title = ""), linetype = guide_legend(title = "")) + theme_bw() + theme(legend.key.width = unit(3,"lines"))
使用基础绘图glmnet方法相同的结果:
# x11(width = 9/2.54, height = 8/2.54)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)
由reprex包(v0.2.0)于2018-02-26创建。