始める無料で始める

アンダーフィッティングしていませんか?

三目並べ(Tic-Tac-Toe)で将来の対戦に勝てるかどうかを予測する Random Forest モデルを作成します。tic_tac_toe データセットを使い、学習用とテスト用のデータセット X_trainX_testy_trainy_test を作成済みです。

木の本数を変えた複数の Random Forest モデル(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 に追加してください。
  • 用意された print 文で学習スコアとテストスコアを表示してください。

実践的なインタラクティブ演習

このサンプルコードを完成させて、この演習に挑戦してみましょう。

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(____))
コードを編集して実行