拆解決策樹規則
在這個練習中,你將從決策樹擷取 if-else 規則,並將其視覺化,以找出影響退訂(churn)的主要因素。
已訓練好的決策樹物件以 mytree 載入,經標準化的特徵以名為 train_X 的 pandas DataFrame 載入。sklearn 函式庫中的 tree 模組與 graphviz 函式庫也都已為你載入。
注意:我們使用自有的 display_image() 函式來取代 display(graph),讓你更容易查看輸出結果。
本練習屬於課程
Python 的行銷機器學習
練習說明
- 從訓練好的決策樹匯出
graphviz物件。 - 指定特徵名稱。
- 將 precision 設為 1,並加入類別名稱。
- 呼叫
graphviz的Source()函式,並傳入匯出的graphviz物件。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Export graphviz object from the trained decision tree
exported = tree.___(decision_tree=mytree,
# Assign feature names
out_file=None, ___=train_X.columns,
# Set precision to 1 and add class names
precision=1, ___=['Not churn','Churn'], filled = True)
# Call the Source function and pass the exported graphviz object
graph = graphviz.___(exported)
# Display the decision tree
display_image("/usr/local/share/datasets/decision_tree_rules.png")