尝试不同的最大深度
我们总是希望优化机器学习模型,以尽可能做出更好的预测。可以通过调整超参数来实现,超参数是模型的配置项。我们将在后续章节更详细地介绍它们的作用,但现在您可以将它们理解为可调的"旋钮",用来把预测调到尽可能好。
对于常规的 决策树,可能最重要的超参数是 max_depth。它限制决策树中的划分次数。让我们基于模型在测试集上的 R\(^2\) 分数来寻找最佳的 max_depth 值,该分数可以通过决策树模型的 score() 方法获得。
本练习是课程的一部分
Python 金融机器学习
练习说明
- 遍历 3、5、10 这几个值,作为决策树模型的
max_depth参数。 - 在每次循环中,将 DecisionTreeRegressor 的
max_depth参数设置为当前的d。 - 打印模型在
train_features和train_targets上的分数。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Loop through a few different max depths and check the performance
for d in [____]:
# Create the tree and fit it
decision_tree = DecisionTreeRegressor(____)
decision_tree.fit(train_features, train_targets)
# Print out the scores on train and test
print('max_depth=', str(d))
print(decision_tree.score(____))
print(decision_tree.score(test_features, test_targets), '\n')