開始使用免費開始

使用 KFold 索引

你已經建立了 splits,其中包含 candy-data 資料集用於完成 5 折交叉驗證的索引。為了更精確估計同事的隨機森林模型在新資料上的表現,你想在剛剛建立的 5 組不同的訓練與驗證索引上執行這個模型。

在本練習中,你會使用這些索引,透過 5 次不同的切分來檢查此模型的準確率。已提供 for 迴圈來協助你完成這個流程。

本練習屬於課程

Python 的模型驗證

檢視課程

練習說明

  • 使用 train_indexval_index,在建立訓練與驗證資料時,索引到正確的 Xy
  • 使用訓練資料集來訓練 rfc
  • 使用 rfc 為驗證資料集產生預測,並印出驗證準確率。

動手互動練習

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

from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error

rfc = RandomForestRegressor(n_estimators=25, random_state=1111)

# Access the training and validation indices of splits
for train_index, val_index in splits:
    # Setup the training and validation data
    X_train, y_train = X[____], y[____]
    X_val, y_val = X[____], y[____]
    # Fit the random forest model
    rfc.____(____, ____)
    # Make predictions, and print the accuracy
    predictions = rfc.____(____)
    print("Split accuracy: " + str(mean_squared_error(y_val, predictions)))
編輯並執行程式碼