- 已编辑
XGBoost 很强,就不多说了,懂的都懂,不懂的我还在路上,刚上手遇到一小白问题。 还是用老掉牙的时序数据 AirPassengers,准备来评测一下几个方法
air_passengers <- data.frame(
y = as.vector(AirPassengers),
month = rep(1:12, 12),
year = rep(1949:1960, each = 12)
)
# 日期列用作后续 ggplot2 绘图
air_passengers$date <- as.Date(paste(air_passengers$year, air_passengers$month, "01", sep = "-"))
加载 xgboost 包,分割数据、训练数据、再拟合数据
library(xgboost)
data_size <- nrow(air_passengers)
# 拆分数据集
train_size <- floor(data_size * 0.67)
# 预测问题当作回归任务
mod_xgb <- xgboost(
y = air_passengers[, 1],
x = air_passengers[, -c(1,4)],
eval_set = (train_size+1):data_size, # 验证集
early_stopping_rounds = 50,
verbosity = 0 # 不显示训练过程
)
# 拟合历史和预测未来 12 期
pred_xgb <- predict(mod_xgb, newdata = data.frame(
month = c(air_passengers$month, 1:12),
year = c(air_passengers$year, rep(1961, 12))
), validate_features = TRUE)
# 整理数据
air_passengers_xgb <- data.frame(
y = pred_xgb,
month = c(air_passengers$month, 1:12),
year = c(air_passengers$year, rep(1961, 12))
)
air_passengers_xgb$date <- as.Date(paste(air_passengers_xgb$year, air_passengers_xgb$month, "01", sep = "-"))
最后,将对历史的拟合结果和对未来的预测结果展示出来
library(ggplot2)
ggplot() +
geom_point(data = air_passengers, aes(x = date, y = y), size = 1) +
geom_line(data = air_passengers_xgb, aes(x = date, y = y), color = "red") +
labs(x = "", y = "")
图中黑色的点是原始数据,红色的线是拟合、预测结果。发现,离了大谱,模型经过所有训练数据(显然过拟合),从测试数据集来看,周期性学到了,但是趋势性和波动性没有学到,基于我的 XGBoost 信任,我先是怀疑我哪个地方用错了,但是,xgboost 文档翻了,不知道咋搞?特来求助。