基于以下R代码:library(glmnet) library(ggplot2) # 生成5030的随机数据和30个变量 set.seed(1111) n <- 50 p <- 30 X <- matrix(runif(n * p), n, p) y <- rnorm(n) # 生成三组不同系数的线性模型 beta1 <- c(rep(1, 3), rep(0, p - 3)) beta2 <- c(rep(0, 10), rep(1, 3), rep(0, p - 13)) beta3 <- c(rep(0, 20), rep(1, 3), rep(0, p - 23)) y1 <- X %% beta1 + rnorm(n) y2 <- X %% beta2 + rnorm(n) y3 <- X %*% beta3 + rnorm(n),每个线性模型组,均进行交叉验证,并以par(3,2)的规格分别画出每组在进行交叉验证时,基于不同的$\lambda$的交叉验证误差图和预测误差图(图中仅需要有一根线平滑地连接每一个点即可,不需要最优$\lambda$取值线为的多余线段,所有画图过程用plot实现)
时间: 2024-02-24 15:56:52 浏览: 27
以下是代码实现:
``` r
# 构建模型
fit1 <- cv.glmnet(X, y1)
fit2 <- cv.glmnet(X, y2)
fit3 <- cv.glmnet(X, y3)
# 交叉验证误差图
par(mfrow = c(3, 2))
plot(fit1)
plot(fit2)
plot(fit3)
# 预测误差图
plot(fit1$lambda, fit1$cvm, type = "l", col = "red", xlab = "lambda", ylab = "CV error")
lines(fit1$lambda, fit1$cvup, col = "blue")
lines(fit1$lambda, fit1$cvlo, col = "blue")
abline(v = fit1$lambda.min, col = "gray")
legend("topright", legend = c("cv error", "upper cv error", "lower cv error"), col = c("red", "blue", "blue"), lty = 1)
plot(fit2$lambda, fit2$cvm, type = "l", col = "red", xlab = "lambda", ylab = "CV error")
lines(fit2$lambda, fit2$cvup, col = "blue")
lines(fit2$lambda, fit2$cvlo, col = "blue")
abline(v = fit2$lambda.min, col = "gray")
legend("topright", legend = c("cv error", "upper cv error", "lower cv error"), col = c("red", "blue", "blue"), lty = 1)
plot(fit3$lambda, fit3$cvm, type = "l", col = "red", xlab = "lambda", ylab = "CV error")
lines(fit3$lambda, fit3$cvup, col = "blue")
lines(fit3$lambda, fit3$cvlo, col = "blue")
abline(v = fit3$lambda.min, col = "gray")
legend("topright", legend = c("cv error", "upper cv error", "lower cv error"), col = c("red", "blue", "blue"), lty = 1)
```
其中,交叉验证误差图使用了`plot`函数,而预测误差图使用了`lines`和`abline`函数。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)