如何编写函数输出XGBoost时间序列6折交叉验证预测对比图
时间序列预测可视化需求与示例代码
我正在使用XGBoost进行时间序列预测,采用TimeSeriesSplit实现6折交叉验证。需要编写一个函数,通过循环输出6张实际值vs预测值对比图(每个交叉验证折对应一张),每张图需基于对应折的数据,先用XGBoost计算出预测值列,再生成图表。
示例数据
import pandas as pd import numpy as np import matplotlib.pyplot as plt # 生成包含日期、实际值、模拟预测值的示例数据集 df = pd.DataFrame({ 'date': pd.date_range(start='2022-01-01', end='2023-06-30'), 'actual': np.random.randint(0, 10, size=546), 'predicted': np.random.randint(0, 14, size=546) }) df.set_index('date', inplace=True) # 将日期列设为数据索引
单折绘图示例
# 筛选2022年6月的数据绘制对比图 ax = df.loc[(df.index > '2022-05-31') & (df.index < '2022-07-1')]['actual'].plot(figsize=(15, 5), title='实际值vs预测值') df.loc[(df.index > '2022-05-31') & (df.index < '2022-07-1')]['predicted'].plot(style='.') plt.legend(['实际值', '预测值']) plt.show()
双折绘图示例
# 定义两个时间段的筛选条件 bool1 = (df.index > '2022-05-31') & (df.index < '2022-07-1') # 2022年6月 bool2 = (df.index > '2022-10-31') & (df.index < '2022-12-1') # 2022年11月 # 绘制第一组时间段的对比图 ax = df.loc[bool1]['actual'].plot(figsize=(15, 5), title='实际值vs预测值') df.loc[bool1]['predicted'].plot(style='.') plt.legend(['实际值', '预测值']) plt.show() # 绘制第二组时间段的对比图 ax = df.loc[bool2]['actual'].plot(figsize=(15, 5), title='实际值vs预测值') df.loc[bool2]['predicted'].plot(style='.') plt.legend(['实际值', '预测值']) plt.show()
内容的提问来源于stack exchange,提问作者Karthik S
相关产品推荐
相关产品推荐

