始める無料で始める

Time K-fold

「Store Item Demand Forecasting Challenge」を覚えていますか?店舗×商品の売上データが与えられ、将来の売上を予測する課題です。

これは時系列データのコンペなので、time K-fold クロスバリデーションを適用する必要があります。ここでは、この検証戦略を作成し、期待どおりに動作することを確認しましょう。

なお、train データフレームはワークスペースにすでに用意されており、TimeSeriesSplitsklearn.model_selection からインポート済みです。

この演習はコースの一部です

Pythonで挑むKaggleコンペティション

コースを見る

演習の手順

  • 分割数を 3 として TimeSeriesSplit オブジェクトを作成します。
  • time K-fold を適用するために、学習データを "date" 列でソートします。
  • 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
コードを編集して実行