最近学习负荷时序预测相关模型了解的一些知识点相关的知识可见w-yes6/load-forecasting-learnXGboost就是通过滞后特征或者统计特征等学习时序模型通过树来学习残差然后进行预测的。1. “通过滞后特征或者统计特征等” —— 解决数据重塑因为树模型天生“没有时间概念”你通过滞后特征如shift(24)和滚动统计特征如过去 24 小时均值把原本“前后连贯”的时间线重塑成了一张标准的、包含历史线索的二维监督学习表格。这就是模型的输入。2. “通过树来学习残差” —— 解决核心算法在训练阶段XGBoost 内部的成百上千棵决策树开始接力跑。第一棵树粗糙地预测一个值后面的树则死死盯着前面留下的残差不正确的部分进行针对性纠错。树越建越多残差越来越小历史规律就被这些树的 If-Else 路标牢牢锁定了。3. “然后进行预测的” —— 解决未来推导到了未来虽然我们没有标准答案真实的负荷值但通过shift错位平移我们已经把明天的“特征问卷”准备好了。把明天的特征输入进固定的树群里让数据去“走迷宫”把所有树吐出来的数字加在一起未来的预测值就诞生了。代码示例import warnings import matplotlib.pyplot as plt import numpy as np import pandas as pd import xgboost as xgb # 忽略不必要的警告信息 warnings.filterwarnings(ignore) # # 1. 模拟生成一份电力负荷数据 (以小时为单位) # np.random.seed(42) # 生成 200 个小时的时间序列索引 time_index pd.date_range(start2026-05-01, periods200, freqH) # 模拟带有每日周期波动的负荷数据并加入随机噪声 base_load 100 simulated_load [] for i, t in enumerate(time_index): # 用正弦函数模拟每天 24 小时的周期性波动中午高凌晨低 daily_pattern 30 * np.sin(2 * np.pi * t.hour / 24) noise np.random.normal(0, 5) simulated_load.append(base_load daily_pattern noise) # 组装成 DataFrame df pd.DataFrame(data{load: simulated_load}, indextime_index) # # 2. 特征工程重塑数据赋予模型“历史眼光” # def create_features(data): 把纯时序数据转换成包含时间戳特征和滞后特征的表格数据 df_feat data.copy() # --- 兵团一时间戳特征 (从日期中提取If-Else判断的依据) --- df_feat[hour] df_feat.index.hour # 提取小时 (0-23) df_feat[dayofweek] df_feat.index.dayofweek # 提取星期几 (0-6) # --- 兵团二滞后特征 (直接把过去的历史写在明天的行里) --- # 假设我们只做“单步预测”预测未来1小时所以最小可以从 lag_1 起步 df_feat[lag_1] df_feat[load].shift(1) # 1小时前的负荷 df_feat[lag_2] df_feat[load].shift(2) # 2小时前的负荷 df_feat[lag_24] df_feat[load].shift(24) # 昨天同一时刻的负荷 # --- 兵团三滚动统计特征 (捕捉近期大环境的基线) --- # 基于 lag_1 滚动计算过去 6 小时的平均值防止数据泄露 df_feat[rolling_mean_6h] df_feat[lag_1].rolling(6).mean() return df_feat # 执行特征工程 df_with_features create_features(df) # 注意因为使用了 shift 和 rolling前 24 行数据会产生空值 (NaN)必须剔除 df_with_features df_with_features.dropna() # # 3. 严格按时间先后划分特征 (X) 和标签 (Y) # # 规定哪些是丢给模型走迷宫的“答卷特征” FEATURES [hour, dayofweek, lag_1, lag_2, lag_24, rolling_mean_6h] # 规定哪一个是标准的“未来答案” TARGET load # 划分训练集前 150 个小时的历史 train_df df_with_features.iloc[:150] # 划分测试集最后 26 个小时的未来真相 test_df df_with_features.iloc[150:] X_train, y_train train_df[FEATURES], train_df[TARGET] X_test, y_test test_df[FEATURES], test_df[TARGET] # # 4. 初始化并训练 XGBoost 模型 # # 创建一个 XGBoost 回归树模型 # n_estimators100: 一共建 100 棵树去串行接力纠正残差 # max_depth3: 每棵树的最大深度是 3防止路标太多导致死记硬背过拟合 # learning_rate0.1: 学习率控制每棵树修正残差的步伐大小 model xgb.XGBRegressor(n_estimators100, max_depth3, learning_rate0.1, random_state42) # 让模型开始看历史数据X_train和答案y_train一棵树接一棵树地拟合残差 model.fit(X_train, y_train) # # 5. 带着未来的特征“走迷宫”进行单步预测 # # 此时我们把测试集的特征X_test喂给建好的树模型会顺着路标相加直接吐出预测值 predictions model.predict(X_test) # 将预测结果转化为带有时间索引的 Series方便后面画图对齐 predictions_series pd.Series(predictions, indextest_df.index) # # 6. 结果可视化比对 # plt.figure(figsize(12, 5)) # 画出最后一段已知的训练集历史 plt.plot(train_df.index[-48:], train_df[load][-48:], labelHistory (Last 48h), colorblue) # 画出测试集的真实未来绿色线 plt.plot(test_df.index, y_test, labelActual Future (Truth), colorgreen, linewidth2) # 画出 XGBoost 预测出来的未来红色虚线 plt.plot(test_df.index, predictions_series, labelXGBoost Forecast, colorred, linestyle--, linewidth2) plt.title(Electricity Load Forecasting using XGBoost) plt.xlabel(Time) plt.ylabel(Load (MW)) plt.legend() plt.grid(True) plt.show()
学习时序预测-day 01 XGboost进行时序预测
发布时间:2026/5/26 22:41:54
最近学习负荷时序预测相关模型了解的一些知识点相关的知识可见w-yes6/load-forecasting-learnXGboost就是通过滞后特征或者统计特征等学习时序模型通过树来学习残差然后进行预测的。1. “通过滞后特征或者统计特征等” —— 解决数据重塑因为树模型天生“没有时间概念”你通过滞后特征如shift(24)和滚动统计特征如过去 24 小时均值把原本“前后连贯”的时间线重塑成了一张标准的、包含历史线索的二维监督学习表格。这就是模型的输入。2. “通过树来学习残差” —— 解决核心算法在训练阶段XGBoost 内部的成百上千棵决策树开始接力跑。第一棵树粗糙地预测一个值后面的树则死死盯着前面留下的残差不正确的部分进行针对性纠错。树越建越多残差越来越小历史规律就被这些树的 If-Else 路标牢牢锁定了。3. “然后进行预测的” —— 解决未来推导到了未来虽然我们没有标准答案真实的负荷值但通过shift错位平移我们已经把明天的“特征问卷”准备好了。把明天的特征输入进固定的树群里让数据去“走迷宫”把所有树吐出来的数字加在一起未来的预测值就诞生了。代码示例import warnings import matplotlib.pyplot as plt import numpy as np import pandas as pd import xgboost as xgb # 忽略不必要的警告信息 warnings.filterwarnings(ignore) # # 1. 模拟生成一份电力负荷数据 (以小时为单位) # np.random.seed(42) # 生成 200 个小时的时间序列索引 time_index pd.date_range(start2026-05-01, periods200, freqH) # 模拟带有每日周期波动的负荷数据并加入随机噪声 base_load 100 simulated_load [] for i, t in enumerate(time_index): # 用正弦函数模拟每天 24 小时的周期性波动中午高凌晨低 daily_pattern 30 * np.sin(2 * np.pi * t.hour / 24) noise np.random.normal(0, 5) simulated_load.append(base_load daily_pattern noise) # 组装成 DataFrame df pd.DataFrame(data{load: simulated_load}, indextime_index) # # 2. 特征工程重塑数据赋予模型“历史眼光” # def create_features(data): 把纯时序数据转换成包含时间戳特征和滞后特征的表格数据 df_feat data.copy() # --- 兵团一时间戳特征 (从日期中提取If-Else判断的依据) --- df_feat[hour] df_feat.index.hour # 提取小时 (0-23) df_feat[dayofweek] df_feat.index.dayofweek # 提取星期几 (0-6) # --- 兵团二滞后特征 (直接把过去的历史写在明天的行里) --- # 假设我们只做“单步预测”预测未来1小时所以最小可以从 lag_1 起步 df_feat[lag_1] df_feat[load].shift(1) # 1小时前的负荷 df_feat[lag_2] df_feat[load].shift(2) # 2小时前的负荷 df_feat[lag_24] df_feat[load].shift(24) # 昨天同一时刻的负荷 # --- 兵团三滚动统计特征 (捕捉近期大环境的基线) --- # 基于 lag_1 滚动计算过去 6 小时的平均值防止数据泄露 df_feat[rolling_mean_6h] df_feat[lag_1].rolling(6).mean() return df_feat # 执行特征工程 df_with_features create_features(df) # 注意因为使用了 shift 和 rolling前 24 行数据会产生空值 (NaN)必须剔除 df_with_features df_with_features.dropna() # # 3. 严格按时间先后划分特征 (X) 和标签 (Y) # # 规定哪些是丢给模型走迷宫的“答卷特征” FEATURES [hour, dayofweek, lag_1, lag_2, lag_24, rolling_mean_6h] # 规定哪一个是标准的“未来答案” TARGET load # 划分训练集前 150 个小时的历史 train_df df_with_features.iloc[:150] # 划分测试集最后 26 个小时的未来真相 test_df df_with_features.iloc[150:] X_train, y_train train_df[FEATURES], train_df[TARGET] X_test, y_test test_df[FEATURES], test_df[TARGET] # # 4. 初始化并训练 XGBoost 模型 # # 创建一个 XGBoost 回归树模型 # n_estimators100: 一共建 100 棵树去串行接力纠正残差 # max_depth3: 每棵树的最大深度是 3防止路标太多导致死记硬背过拟合 # learning_rate0.1: 学习率控制每棵树修正残差的步伐大小 model xgb.XGBRegressor(n_estimators100, max_depth3, learning_rate0.1, random_state42) # 让模型开始看历史数据X_train和答案y_train一棵树接一棵树地拟合残差 model.fit(X_train, y_train) # # 5. 带着未来的特征“走迷宫”进行单步预测 # # 此时我们把测试集的特征X_test喂给建好的树模型会顺着路标相加直接吐出预测值 predictions model.predict(X_test) # 将预测结果转化为带有时间索引的 Series方便后面画图对齐 predictions_series pd.Series(predictions, indextest_df.index) # # 6. 结果可视化比对 # plt.figure(figsize(12, 5)) # 画出最后一段已知的训练集历史 plt.plot(train_df.index[-48:], train_df[load][-48:], labelHistory (Last 48h), colorblue) # 画出测试集的真实未来绿色线 plt.plot(test_df.index, y_test, labelActual Future (Truth), colorgreen, linewidth2) # 画出 XGBoost 预测出来的未来红色虚线 plt.plot(test_df.index, predictions_series, labelXGBoost Forecast, colorred, linestyle--, linewidth2) plt.title(Electricity Load Forecasting using XGBoost) plt.xlabel(Time) plt.ylabel(Load (MW)) plt.legend() plt.grid(True) plt.show()