我是在欠拟合吗?
您正在创建一个随机森林模型,用来预测您在未来的一局井字棋中是否会获胜。使用 tic_tac_toe 数据集,您已经创建了训练集和测试集:X_train、X_test、y_train 和 y_test。
您决定训练多组随机森林模型,设置不同的树数量(1、2、3、4、5、10、20、50)。树越多,模型运行时间越长;但是如果树太少,就有欠拟合的风险。您已经编写了一个 for 循环,用不同的树数量来测试模型。
本练习是课程的一部分
Python 中的模型验证
练习说明
- 在每次循环中,分别对
X_train和X_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(____))