找出最佳樹深度
現在你要調整決策樹的 max_depth 參數,找出能降低過度擬合、同時維持良好模型效能指標的設定。你會用 for 迴圈跑過多個 max_depth 參數值,對每個值各自訓練一棵決策樹,然後計算效能指標。
系統已為你載入包含參數候選值的 depth_list。depth_tuning 陣列也已建立好,包含 2 欄:第一欄填入深度候選值,第二欄是 recall 分數的佔位欄。此外,特徵與目標變數已分別以 train_X、train_Y 表示訓練資料,以 test_X、test_Y 表示測試資料。numpy 與 pandas 函式庫也已分別以 np 與 pd 載入。
本練習屬於課程
Python 的行銷機器學習
練習說明
- 對
depth_list串列長度從 0 開始的範圍執行for迴圈。 - 對每個深度候選值,初始化並訓練一個決策樹分類器,並在測試資料上預測流失。
- 對每個深度候選值,使用
recall_score()函式計算 recall 分數,並將結果存入depth_tunning的第二欄。 - 將
depth_tuning轉成pandas的 DataFrame,並設定合適的欄名。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Run a for loop over the range of depth list length
for index in ___(0, len(depth_list)):
# Initialize and fit decision tree with the `max_depth` candidate
mytree = DecisionTreeClassifier(___=depth_list[index])
mytree.fit(___, train_Y)
# Predict churn on the testing data
pred_test_Y = mytree.predict(___)
# Calculate the recall score
depth_tuning[index,1] = ___(test_Y, ___)
# Name the columns and print the array as pandas DataFrame
col_names = ['Max_Depth','Recall']
print(pd.DataFrame(depth_tuning, columns=___))