不使用graphviz / web可视化决策树

时间:2018-10-04 19:58:50

标签: python scikit-learn visualization decision-tree

由于某些限制,我无法使用graphviz,webgraphviz.com 可视化决策树(工作网络已从另一个世界关闭)。

问题:是否存在一些替代的实用工具或Python代码,至少对于非常简单的可视化而言,可能仅仅是决策树的ASCII可视化(python / sklearn)?

我的意思是,我可以特别使用sklearn:tree.export_graphviz() 产生具有树状结构的文本文件,从中可以读取一棵树, 但是用“眼睛”做这件事并不令人愉快...

PS 请注意

graph = pydotplus.graph_from_dot_data(dot_data.getvalue())  
Image(graph.create_png())

将不起作用,因为create_png使用了隐式的graphviz

1 个答案:

答案 0 :(得分:3)

这是一个不使用graphviz或在线转换器的答案。从scikit-learn 21.0版开始(大约在2019年5月),现在可以使用scikit-learn的tree.plot_tree和matplotlib来绘制决策树,而无需依赖graphviz。

import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
from sklearn import tree

X, y = load_iris(return_X_y=True)

# Make an instance of the Model
clf = DecisionTreeClassifier(max_depth = 5)

# Train the model on the data
clf.fit(X, y)

fn=['sepal length (cm)','sepal width (cm)','petal length (cm)','petal width (cm)']
cn=['setosa', 'versicolor', 'virginica']

# Setting dpi = 300 to make image clearer than default
fig, axes = plt.subplots(nrows = 1,ncols = 1,figsize = (4,4), dpi=300)

tree.plot_tree(clf,
           feature_names = fn, 
           class_names=cn,
           filled = True);

fig.savefig('imagename.png')

下面的图像是保存的图像。 enter image description here

该代码改编自此post

相关问题