修剪樹模型
過度擬合是分析中的經典問題,特別是對決策樹演算法而言。當樹長到最大時,對訓練樣本的預測可能非常準確,但在測試集上的表現卻不佳。因此,通常會透過以下方式來控制決策樹的成長:
- 「修剪」樹,並對最大深度設置上限。
- 限制每個葉節點中的最少觀測數。
在本練習中,你將:
- 修剪樹,並將樹的最大深度限制為 5 層
- 將模型配適到員工資料
- 在訓練集與測試集上檢驗預測結果。
變數 features_train、target_train、features_test 與 target_test 已經在你的工作環境中可用。
本練習屬於課程
HR 分析:用 Python 預測員工流失
練習說明
- 初始化
DecisionTreeClassifier,並將樹的最大深度限制為 5。 - 使用訓練集中的
features與target來配適決策樹模型。 - 檢查模型在訓練集與測試集的預測準確率。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Initialize the DecisionTreeClassifier while limiting the depth of the tree to 5
model_depth_5 = DecisionTreeClassifier(____=5, random_state=42)
# Fit the model
____.fit(features_train,target_train)
# Print the accuracy of the prediction for the training set
print(____.____(features_train,target_train)*100)
# Print the accuracy of the prediction for the test set
print(model_depth_5.score(____,____)*100)