【问题标题】:Visualizing decision tree not using graphviz/web不使用 graphviz/web 可视化决策树
【发布时间】:2019-03-10 07:00:36
【问题描述】:

由于某些限制,我无法使用 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

【问题讨论】:

标签: python scikit-learn visualization decision-tree


【解决方案1】:

这是一个不使用 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')

下图是保存的内容。

代码改编自post

【讨论】:

    猜你喜欢
    • 2022-08-24
    • 1970-01-01
    • 2021-05-13
    • 1970-01-01
    • 2012-07-03
    • 2019-11-03
    • 2016-03-12
    • 2019-05-14
    相关资源
    最近更新 更多