You need to enable JavaScript to run this app. Python中时间序列按月划分训练/测试集及XGBoost适配方法
优惠活动
大模型
产品
解决方案
定价
更多

Python中时间序列按月划分训练/测试集及XGBoost适配方法

实现逻辑说明

要实现按自然月单独拆分时间序列数据集,核心逻辑如下:

  • 首先将数据中的时间字段转换为datetime格式,提取「年月」标识作为分组依据,将同属一个自然月的样本归为同一组
  • 对每个自然月的分组,严格按照时间先后顺序取前80%作为训练集、后20%作为测试集,绝对不能打乱样本顺序,否则会出现未来数据泄露,导致模型效果虚高
  • 把所有月份的训练子集合并得到全局训练集,所有月份的测试子集合并得到全局测试集,后续直接输入XGBoost训练即可
可直接运行的代码示例
import pandas as pd
import numpy as np
import xgboost as xgb
from sklearn.metrics import mean_squared_error

# ---------------------- 1. 数据准备(替换为自己的数据集即可) ----------------------
# 模拟3年日度时间序列数据
date_range = pd.date_range(start='2020-01-01', end='2022-12-31', freq='D')
df = pd.DataFrame({
    'datetime': date_range,
    'feature1': np.random.randn(len(date_range)),
    'feature2': np.random.randint(0, 100, len(date_range)),
    'feature3': np.random.uniform(10, 50, len(date_range)),
    'label': np.random.randn(len(date_range))  # 回归任务标签,分类任务可替换为0/1值
})
# 如果原始时间字段是字符串,先转格式:df['datetime'] = pd.to_datetime(df['datetime'])

# ---------------------- 2. 按自然月拆分数据集 ----------------------
# 提取年月分组标识
df['year_month'] = df['datetime'].dt.to_period('M')

train_parts = []
test_parts = []
for month, group in df.groupby('year_month'):
    # 单月内按顺序8:2拆分
    split_idx = int(len(group) * 0.8)
    train_parts.append(group.iloc[:split_idx])
    test_parts.append(group.iloc[split_idx:])

# 合并得到全局训练、测试集
train_df = pd.concat(train_parts, ignore_index=True)
test_df = pd.concat(test_parts, ignore_index=True)

# ---------------------- 3. XGBoost训练评估 ----------------------
# 构造输入特征和标签
drop_cols = ['datetime', 'year_month', 'label']
X_train = train_df.drop(drop_cols, axis=1)
y_train = train_df['label']
X_test = test_df.drop(drop_cols, axis=1)
y_test = test_df['label']

# 转换为XGBoost专属数据格式
dtrain = xgb.DMatrix(X_train, label=y_train)
dtest = xgb.DMatrix(X_test, label=y_test)

# 模型参数(回归任务示例,分类任务调整objective为binary:logistic即可)
xgb_params = {
    'objective': 'reg:squarederror',
    'max_depth': 3,
    'learning_rate': 0.1,
    'random_state': 42
}

# 训练+预测
model = xgb.train(xgb_params, dtrain, num_boost_round=100)
y_pred = model.predict(dtest)

# 效果评估
print(f"测试集均方误差: {mean_squared_error(y_test, y_pred):.4f}")
注意事项
  • 如果单个自然月的样本量极少(比如不足10条),可以适当调整当月拆分比例,或者跳过该月,避免测试集样本太少导致评估结果波动过大
  • 如果是分类任务,单月拆分时可改用分层抽样,保证训练、测试集的标签分布和整月分布一致,回归任务直接按顺序拆分即可
  • 拆分过程全程不要对任何分组做shuffle操作,时间序列的时间顺序是核心特征,打乱会引入严重的数据泄露

内容的提问来源于stack exchange,提问作者Herwini

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 02:24:03