R语言LightGBM回归波士顿房价预测
时间: 2024-01-25 14:11:17 浏览: 166
预测波士顿房价
5星 · 资源好评率100%
以下是使用R语言中的LightGBM进行回归波士顿房价预测的示例代码:
```R
# 加载所需的库
library(lightgbm)
library(mlbench)
library(caret)
# 加载数据集
data(BostonHousing)
df <- BostonHousing
# 将数据集分为训练集和测试集
set.seed(123)
trainIndex <- createDataPartition(df$medv, p = .8, list = FALSE)
train <- df[ trainIndex,]
test <- df[-trainIndex,]
# 将数据转换为LightGBM需要的格式
train_data <- lgb.Dataset(train[, -14], label = train$medv)
test_data <- lgb.Dataset(test[, -14], label = test$medv)
# 设置LightGBM参数
params <- list(objective = "regression",
metric = "rmse",
learning_rate = 0.1,
num_leaves = 31,
max_depth = -1,
min_child_samples = 20,
subsample = 1,
colsample_bytree = 1)
# 训练模型
model <- lgb.train(params = params,
data = train_data,
nrounds = 100,
verbose = 0)
# 预测测试集
pred <- predict(model, test[, -14])
# 计算RMSE
rmse <- sqrt(mean((pred - test$medv)^2))
cat("RMSE:", rmse)
# 绘制特征重要性图
lgb.plot.importance(model)
```
阅读全文