如何更优雅地可视化决策树


scikit-learn vs spark-tree-plotting vs dtreeviz
在开始本文之前,我们先来做个简单的对比,



<<< 左右滑动见更多 >>>
第二幅是之前介绍过的 spark-tree-plotting。
更多效果图









<<< 左右滑动见更多 >>>
dtreeviz 简介
dtreeviz[1] 不仅可以用来可视化决策树,还可以用于解释决策树模型。dtreeviz 不仅支持 scikit-learn, Spark MLlib 还支持 XGBoost。使用 dtreeviz,您可以可视化如何在决策节点上分割特征空间,如何在叶节点上分布训练样本,树如何针对特定观察进行预测等等。这些操作对于理解分类或回归决策树的工作方式至关重要。
安装 dtreeviz
conda(推荐)
该方法会自动安装所需组件,包括 graphviz(官方教程需要更新了)。
conda install -y -c conda-forge dtreeviz
pip
pip install dtreeviz
graphviz
请确认是否已经安装了较新版本的 graphviz(10.13, 10.14 验证有效)
macOS
brew reinstall graphviz
Ubuntu
sudo apt install graphviz
Windows 10
下载安装graphviz-2.38.msi[2]我的另外一篇文章比较详细介绍了 Windows 下的 graphviz 的安装以及注意事项。
使用 dtreeviz
导入所需库
from sklearn.datasets import *from sklearn import treefrom dtreeviz.trees import *
回归决策树
regr = tree.DecisionTreeRegressor(max_depth=2)boston = load_boston()regr.fit(boston.data, boston.target)viz = dtreeviz(regr,               boston.data,               boston.target,               target_name='price',               feature_names=boston.feature_names)viz.view()

分类决策树
classifier = tree.DecisionTreeClassifier(max_depth=2)  # limit depth of treeiris = load_iris()classifier.fit(iris.data, iris.target)viz = dtreeviz(classifier,               iris.data,               iris.target,               target_name='variety',               feature_names=iris.feature_names,               class_names=["setosa", "versicolor", "virginica"]  # need class_names for classifier              )viz.view()

更多例子,可以参考官方文档,另外官方还提供了多个 notebook,详细介绍了 dtreeviz 在 scikit, spark 和 xgboost 下的使用教程。
参考资料
[1]
dtreeviz: https://github.com/parrt/dtreeviz[2]
graphviz-2.38.msi: https://graphviz.gitlab.io/_pages/Download/Download_windows.html
到顶部