开始使用免费开始使用

时间 K 折

还记得 "Store Item Demand Forecasting Challenge" 吗?在这个挑战中,给定门店-商品的历史销量数据,要求您预测未来销量。

这是一项时间序列数据的竞赛,因此需要应用时间 K 折交叉验证。您的目标是创建这种交叉验证策略,并确保其按预期工作。

请注意,train DataFrame 已在您的工作区中可用,且 TimeSeriesSplit 已从 sklearn.model_selection 导入。

本练习是课程的一部分

用 Python 赢下 Kaggle 竞赛

查看课程

练习说明

  • 创建一个包含 3 个折的 TimeSeriesSplit 对象。
  • 按照 "date" 列对训练数据进行排序,以便应用时间 K 折。
  • 使用 time_kfold 对象遍历每一次时间切分。
  • 在每一次切分中,使用 train_indextest_index 选择训练折与测试折。

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Create TimeSeriesSplit object
time_kfold = TimeSeriesSplit(n_splits=____)

# Sort train data by date
train = train.sort_values(____)

# Iterate through each split
fold = 0
for train_index, test_index in ____.____(____):
    cv_train, cv_test = ____.____[____], ____.____[____]
    
    print('Fold :', fold)
    print('Train date range: from {} to {}'.format(cv_train.date.min(), cv_train.date.max()))
    print('Test date range: from {} to {}\n'.format(cv_test.date.min(), cv_test.date.max()))
    fold += 1
编辑并运行代码