開始使用免費開始

我是不是在欠擬合?

你正在建立一個隨機森林模型,來預測你是否會在未來的井字遊戲中獲勝。使用 tic_tac_toe 資料集,你已經建立了訓練與測試資料集 X_trainX_testy_trainy_test

你決定建立多個具有不同樹數的隨機森林模型(1、2、3、4、5、10、20、50)。樹越多,隨機森林模型執行所需時間越長。然而,如果樹不夠多,就有欠擬合的風險。你已建立一個 for 迴圈,在不同的樹數下測試模型。

本練習屬於課程

Python 的模型驗證

檢視課程

練習說明

  • 在每次迴圈中,對 X_trainX_test 兩個資料集進行預測。
  • 在每次迴圈中,將 y_train 與其對應預測的 accuracy_score() 加到 train_scores
  • 在每次迴圈中,將 y_test 與其對應預測的 accuracy_score() 加到 test_scores
  • 使用提供的列印敘述印出訓練與測試分數。

動手互動練習

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

from sklearn.metrics import accuracy_score

test_scores, train_scores = [], []
for i in [1, 2, 3, 4, 5, 10, 20, 50]:
    rfc = RandomForestClassifier(n_estimators=i, random_state=1111)
    rfc.fit(X_train, y_train)
    # Create predictions for the X_train and X_test datasets.
    train_predictions = rfc.predict(____)
    test_predictions = rfc.predict(____)
    # Append the accuracy score for the test and train predictions.
    train_scores.append(round(____(____, ____), 2))
    test_scores.append(round(____(____, ____), 2))
# Print the train and test scores.
print("The training scores were: {}".format(____))
print("The testing scores were: {}".format(____))
編輯並執行程式碼