graphviz是一款开源的可视化图形工具,在sklearn中,用于画决策树也很方便,其安装流程如下:
下载
链接:https://graphviz.gitlab.io/_pages/Download/windows/graphviz-2.38.msi
安装
双击下载好的安装包,根据提示安装,记住安装目录
添加环境变量
将一下目录添加到环境变量中即可
# Graphviz的安装目录/bin
D:\Program Files (x86)\Graphviz2.38\bin
检查是否安装成功
打开命令行,输入dot -version
,如果出现如下图所示的版本信息,说明安装成功。
代码测试
运行如下代码,即可看到通过graphviz画出的决策树
from sklearn import tree
from sklearn.datasets import load_wine # 红酒数据
from sklearn.model_selection import train_test_split
wine = load_wine()
X_train, X_test, Y_train, Y_test = train_test_split(wine.data, wine.target, test_size=0.3)
clf = tree.DecisionTreeClassifier(criterion="entropy")
clf = clf.fit(X_train, Y_train)
score = clf.score(X_test, Y_test) # 返回准确度
import graphviz
dot_data = tree.export_graphviz(clf
,feature_names = wine.feature_names # 特征名
,class_names = wine.target_names # 标签名
,filled = True # 颜色填充
,rounded = True # 圆角边框
)
graph = graphviz.Source(dot_data)
graph