开始使用免费开始使用

我是在欠拟合吗?

您正在创建一个随机森林模型,用来预测您在未来的一局井字棋中是否会获胜。使用 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(____))
编辑并运行代码