訓練一棵決策樹
現在,來試著建立一個決策樹模型。決策樹是一連串由機器學習得到的 if-else 規則。在電信流失的案例中,它會判斷客戶是否會流失。以下是一個以知名的 Titanic 生還資料集所建立的決策樹圖。

前一個練習中的 train_X、test_X、train_Y、test_Y 已為你載入。同時,sklearn 函式庫中的 tree 模組與 accuracy_score 函式也已載入。你現在要建立模型,並在未看過的資料上檢視其表現。
本練習屬於課程
Python 的行銷機器學習
練習說明
- 以
max_depth設為 5 來初始化決策樹模型。 - 在訓練資料上訓練模型,先放
train_X,再放train_Y。 - 對測試資料進行預測,在此為
test_X。 - 透過比較實際的測試標籤與預測標籤,量測模型在測試資料上的表現。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Initialize the model with max_depth set at 5
mytree = tree.___(max_depth = ___)
# Fit the model on the training data
treemodel = mytree.___(___, ___)
# Predict values on the testing data
pred_Y = treemodel.___(___)
# Measure model performance on testing data
accuracy_score(___, ___)