r语言airquality 岭回归、lasso回归、决策树回归模型准确率R语言代码
时间: 2023-12-08 11:03:15 浏览: 117
3_R语言_
5星 · 资源好评率100%
以下是针对airquality数据集进行岭回归、lasso回归和决策树回归模型的R语言代码:
1. 岭回归模型:
```R
# 加载必要的包
library(glmnet)
# 加载数据集
data(airquality)
# 将缺失值替换为平均值
airquality$Ozone[is.na(airquality$Ozone)] <- mean(airquality$Ozone, na.rm = TRUE)
# 将数据集分为训练集和测试集
set.seed(123)
train <- sample(1:nrow(airquality), nrow(airquality)*0.7)
train.airquality <- airquality[train,]
test.airquality <- airquality[-train,]
# 岭回归模型
ridge.model <- glmnet(x = model.matrix(Ozone ~ ., data = train.airquality)[,-1],
y = train.airquality$Ozone,
alpha = 0,
lambda = seq(0,1,0.01))
# 预测
ridge.pred <- predict(ridge.model, newx = model.matrix(Ozone ~ ., data = test.airquality)[,-1])
# 计算均方误差
mean((test.airquality$Ozone - ridge.pred)^2)
```
2. Lasso回归模型:
```R
# 加载必要的包
library(glmnet)
# 加载数据集
data(airquality)
# 将缺失值替换为平均值
airquality$Ozone[is.na(airquality$Ozone)] <- mean(airquality$Ozone, na.rm = TRUE)
# 将数据集分为训练集和测试集
set.seed(123)
train <- sample(1:nrow(airquality), nrow(airquality)*0.7)
train.airquality <- airquality[train,]
test.airquality <- airquality[-train,]
# Lasso回归模型
lasso.model <- glmnet(x = model.matrix(Ozone ~ ., data = train.airquality)[,-1],
y = train.airquality$Ozone,
alpha = 1,
lambda = seq(0,1,0.01))
# 预测
lasso.pred <- predict(lasso.model, newx = model.matrix(Ozone ~ ., data = test.airquality)[,-1])
# 计算均方误差
mean((test.airquality$Ozone - lasso.pred)^2)
```
3. 决策树回归模型:
```R
# 加载必要的包
library(rpart)
# 加载数据集
data(airquality)
# 将缺失值替换为平均值
airquality$Ozone[is.na(airquality$Ozone)] <- mean(airquality$Ozone, na.rm = TRUE)
# 将数据集分为训练集和测试集
set.seed(123)
train <- sample(1:nrow(airquality), nrow(airquality)*0.7)
train.airquality <- airquality[train,]
test.airquality <- airquality[-train,]
# 决策树回归模型
tree.model <- rpart(Ozone ~ ., data = train.airquality)
# 预测
tree.pred <- predict(tree.model, newdata = test.airquality)
# 计算均方误差
mean((test.airquality$Ozone - tree.pred)^2)
```
阅读全文