開始使用免費開始

嘗試不同的 max depth

我們總是希望把機器學習模型最佳化,讓預測盡可能準確。你可以透過調整超參數(hyperparameters)來做到這點,也就是模型的各種設定。我們會在後面的章節更深入說明其作用,現在先把它想成可以微調預測結果的旋鈕即可。

對一般的[決策樹](https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeRegressor.html#sklearn.tree.DecisionTreeRegressor)來說,最重要的超參數大概就是 max_depth。它會限制決策樹的切分次數。讓我們根據模型在測試集上的 R\(^2\) 分數,找出最好的 max_depth 值;你可以使用決策樹模型的 score() 方法取得這個分數。

本練習屬於課程

Python 金融 Machine Learning

檢視課程

練習說明

  • 以 3、5、10 這三個值迴圈嘗試作為決策樹模型的 max_depth 參數。
  • 在每次迴圈中,將 DecisionTreeRegressor 的 max_depth 參數設為 d
  • 印出模型在 train_featurestrain_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')
編輯並執行程式碼