如何将套索和岭回归拟合(Glmnet)叠加到数据上?

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

我有数据(下面),并进行了线性,脊和套索回归。对于套索和脊回归,我已经使用交叉验证找到了最佳lambda。我现在想要将拟合的模型叠加到我原始数据的y对x图上。我在图表上有线性模型,我无法弄清楚如何让其他两个出现。我在ggplot中尝试过它,但是基础R中的答案也非常有用!即使你能指出我正确的方向,那也很棒。

我的模型一切正常。我在图上有线性回归线。然而,当我尝试以相同的方式绘制其他两个适合时,它将无法工作。

code to create the data

set.seed(1)
x <- rnorm(100)
y <- 1 + .2*x+3*x^2+.6*x^3 + rnorm(100)
d <- data.frame(x=x,y=y)
d$x2 <- d$x^2
d$x3 <- d$x^3
d$x4 <-d$x^4
d$x5 <-d$x^5

linear regression

f <- lm(y ~ ., data=d)

ridge regression

library(glmnet) 
x <- model.matrix(y ~ ., data=d)
y <- d$y

grid <- 0.001:50
ridge.fit <- glmnet(x,y,alpha=0, lambda = grid)

cv <- cv.glmnet(x,y)
r.fit.new <-  glmnet(x,y,alpha=0, lambda = cv$lambda.min)

lasso

lasso.fit <- glmnet(x,y,alpha=1, lambda = grid) 
l.fit.new <- glmnet(x,y,alpha=1, lambda = cv$lambda.min)

graph

ggplot(data=d, aes(x=x, y=y)) + geom_point() + geom_line(aes(y=fitted(f)), colour="blue") 
r graph regression glmnet
1个回答
0
投票

改变了你的代码来创建数据

set.seed(1)
x <- rnorm(100)
y <- 1 + .2*x+3*x^2+.6*x^3 + rnorm(100)
d <- data.frame(x.values=x,y=y)
d$x2 <- d$x.values^2
d$x3 <- d$x.values^3
d$x4 <-d$x.values^4
d$x5 <-d$x.values^5

代码的其余部分用于创建模型矩阵并按原样执行模型。

有些人正在格式化数据以进行绘图

library(dplyr)
data.for.plot <- d%>%
select(x.values,y) %>%
mutate(fitted_lm = as.numeric(fitted(f)),
fitted_ridge_lm = as.numeric(predict(r.fit.new, newx= x)),
fitted_lasso_lm = as.numeric(predict(l.fit.new, newx= x)))

#Plot
ggplot(data.for.plot, aes(x = x.values, y = y)) + 
  geom_point() + 
  geom_line(aes(y=fitted_lm), colour="blue") + 
  geom_line(aes(y=fitted_ridge_lm), colour="red") + 
  geom_line(aes(y= fitted_lasso_lm),color="grey75") + theme_bw()

enter image description here

现在你会注意到很难看到它们彼此非常接近(很棒的模型同意)。因此,让我们稍微格式化数据,并在ggplot中使用faceting来单独查看拟合

library(tidyr)
data.for.plot.long <- gather(data.for.plot, key= fit_type, value = fits, -x.values,-y)
ggplot(data.for.plot.long, aes(y = y, x = x.values)) +
    geom_point() + 
    geom_line(aes(y = fits,colour=fit_type))+facet_wrap(~fit_type, ncol = 1,scales = "free") + theme_bw()

由此产生的情节:enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.