原文地址:https://blog.csdn.net/yj1556492839/article/details/80363034
在sklearn的官網上已經對決策樹的實現進行了詳細介紹,這里主要講一下可視化的過程。
安裝和配置GraphViz
首先去下載軟件,我的版本是graphviz-2.38.msi。然后就是配置環境變量,把\bin文件夾放到path中就行了。最后在終端命令行中輸入:dot -version
,檢測一下有沒有設置成功。
決策樹可視化
需要先安裝一些python庫,如graphviz等。可以用pip或者conda命令安裝,如:pip install graphviz
,也可以在anaconda navigator中直接搜索安裝。
決策樹的具體用法參考官網,這里只貼一部分代碼:
clf_tree = tree.DecisionTreeClassifier()
clf_tree.fit(x_train, y_train)
y_tree = clf_tree.predict(x_test)
dot_data = tree.export_graphviz(clf_tree, out_file='tree.dot', feature_names=['overdue_days', 'bank_card_count', 'latest_earliest_loan_interval', 'latest_login_loan_interval', 'average_loan_interval'], class_names=['1', '2', '3'], filled=True, rounded=True, special_characters=True) graph = graphviz.Source(dot_data)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
執行完以后,可以生成一個叫 ‘tree.dot’ 的 dot 文件。然后在終端命令行中輸入:
dot -Tpng tree.dot -o loan_tree.png #png dot -Tpdf tree.dot -o loan_tree.pdf #pdf
- 1
- 2
將dot文件轉化成png格式的圖片,或者生成pdf文件。