使用XGBoost进行单变量时间序列预测:从数据准备到模型优化
创作时间:
作者:
@小白创作中心
使用XGBoost进行单变量时间序列预测:从数据准备到模型优化
引用
CSDN
1.
https://blog.csdn.net/sinat_41858359/article/details/145704577
本文通过一个具体的案例,逐步讲解了如何使用XGBoost模型进行单变量时间序列预测。内容包括数据读取、格式转换、模型训练、预测、评估等多个环节,并配有详细的代码示例和结果展示。
一、引言
XGBoost 是一种高效的梯度提升树(Gradient Boosting Decision Tree, GBDT)算法。尽管 XGBoost 主要用于监督学习任务(如分类和回归),但通过适当的数据预处理,它也可以用于时间序列预测(Time Series Forecasting)。本文通过一个具体的案例逐步讲解XGBoost模型用于单变量时序数据预测。
二、实现过程
2.1 读取时间序列数据
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
data = pd.read_csv('data.csv')
data['Month'] = pd.to_datetime(data['Month'])
df = data
sns.set(font_scale=1.2)
plt.rc('font', family=['Times New Roman', 'SimSun'], size=12)
plt.figure()
plt.plot(df['Month'], df['Passengers'], color='b', alpha=0.6, label='Original Time Series')
plt.title('Original Time Series', fontsize=12)
plt.legend()
plt.tight_layout()
plt.show()
2.2 数据格式转换
使用滑动窗口法将时间序列数据转换为监督学习格式:
from sklearn.preprocessing import create_lag_features
df_lagged = create_lag_features(df, lags=10)
X = df_lagged.drop(columns=['Passengers'])
y = df_lagged['Passengers']
2.3 数据集划分
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, shuffle=False)
print(X_train.shape, X_test.shape, y_train.shape, y_test.shape)
2.4 模型训练
from xgboost import XGBRegressor
model = XGBRegressor(objective='reg:squarederror', n_estimators=200, learning_rate=0.1, max_depth=5)
model.fit(X_train, y_train)
2.5 模型预测
y_pred = model.predict(X_test)
2.6 模型评估
from sklearn.metrics import mean_squared_error
mse = mean_squared_error(y_test, y_pred)
print(f'Mean Squared Error: {mse:.4f}')
可视化预测结果:
plt.figure()
plt.plot(y_test.values, label='Actual', color='g')
plt.plot(y_pred, label='Predicted', color='r', linestyle='dashed')
plt.title('Actual vs Predicted', fontsize=12)
plt.legend()
plt.tight_layout()
plt.show()
查看预测误差的分布情况:
plt.figure()
sns.histplot(y_test - y_pred, bins=30, kde=True, color='purple')
plt.title('Error Distribution', fontsize=12)
plt.tight_layout()
plt.show()
2.7 特征重要性分析
分析哪些滞后变量对预测最重要:
plt.figure()
feature_importance = model.feature_importances_
sns.barplot(x=X.columns, y=feature_importance, palette='viridis')
plt.title('Feature Importance', fontsize=12)
plt.xticks(X.columns, rotation=45)
plt.tight_layout()
plt.show()
2.8 参数调优
使用网格搜索进行参数调优:
from sklearn.model_selection import GridSearchCV
grid_params = {
'n_estimators': [100, 200, 500],
'max_depth': [3, 5, 7],
'learning_rate': [0.01, 0.1, 0.2]
}
grid_search = GridSearchCV(XGBRegressor(objective='reg:squarederror'), grid_params, cv=3, scoring='neg_mean_squared_error')
grid_search.fit(X_train, y_train)
print(f'Best Parameters: {grid_search.best_params_}')
热门推荐
“生命中最快乐的是拼搏而非成功”——这句名言给写作带来的启示
小说《长恨歌》王琦瑶的人物性格分析
智能商用餐饮设备:餐饮业创新转型的新引擎
有目的的内容营销:讲述能引起共鸣的故事
这些神话,为何不断创造“神话”?
揭秘喜羊羊:Q版角色设计的成功密码
富二代的心理困境:从享受、唯我到惰性
赵佗:从秦朝将领到南越皇帝的传奇之路
赵佗、吕嘉与汉武帝:谁才是南越国灭亡的关键?
揭秘南越国军队:从“东南亚第一强军”到55天崩溃
南越国:赵佗如何称霸岭南?
祖母助力母乳喂养:科学育儿的新趋势
大城馨港购房者维权:法律注意事项揭秘
HTTPS:安全下载网址的最佳实践
Chrome浏览器教你轻松查看下载链接
和平精英:地铁传世神武双截棍获取秘籍大揭秘!
钓鱼技巧:子线夹铅的3个妙用,适合多种鱼情变化
育儿观念大不同:如何理解并尊重奶奶?
科学育儿时代,奶奶们如何华丽转身?
海钓钓组搭配及注意事项
仙人洞村:乡村旅游的致富密码
普者黑5A景区助力仙人洞村振兴:从贫困到“首富”的蝶变之路
春节打卡:北京昌平区仙人洞村的文化传承
云南仙人洞村:生态振兴的典范
安乃近风险警示:肝损伤等严重不良反应,这些安全用药指南请收好
新冠用药指南:警惕安乃近潜在风险!
从“神药”到“毒药”:安乃近的百年沉浮
安乃近退市后,布洛芬和对乙酰氨基酚如何安全使用?
服用安乃近期间的饮食和用药禁忌
寒潮来袭,成都公交用暖心服务温暖你的出行路