開始使用免費開始

scikit-learn 的 KFold()

你剛執行完同事撰寫的程式碼,該程式會建立一個隨機森林模型並計算樣本外的準確率。你注意到同事的程式碼沒有設定 random state,而且你找到的錯誤與同事回報的錯誤完全不同。

為了更準確估計這個隨機森林模型在新資料上的表現,你決定產生一些索引,供 KFold 交叉驗證使用。

本練習屬於課程

Python 的模型驗證

檢視課程

練習說明

  • 呼叫 KFold(),設定為 5 個分割、啟用隨機洗牌(shuffle),並將 random state 設為 1111。
  • X 使用 KFoldsplit() 方法。
  • 列印訓練索引與驗證索引兩個清單中的索引數量。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

from sklearn.model_selection import KFold

# Use KFold
kf = KFold(____, ____, ____)

# Create splits
splits = kf.____(____)

# Print the number of indices
for train_index, val_index in splits:
    print("Number of training indices: %s" % len(____))
    print("Number of validation indices: %s" % len(____))
編輯並執行程式碼