python - 如何指定决策树的 graphviz 表示形式的 figsize?

标签 python scikit-learn graphviz

我有一个在鸢尾花数据集上训练的决策树的 GraphViz 表示。

import graphviz 

dot_data = tree.export_graphviz(clf, out_file=None, 
                     feature_names=iris.feature_names,  
                     class_names=iris.target_names,  
                     filled=True, rounded=True,  
                     special_characters=True)

graph = graphviz.Source(dot_data)
graph

我正在使用上面的代码生成 GraphViz 图,但它创建了一个大图。

我想手动控制这个图的figzise。我该怎么做?

最佳答案

在最初编写我自己的函数来修改 DOT 源代码字符串以添加大小属性后,我在 pydotplus.graphviz.Graph documentation 中偶然发现了这一部分。 :

All the attributes defined in the Graphviz dot language should be supported.

Attributes can be set through the dynamically generated methods:

 set_[attribute name], i.e. set_size, set_fontname

您可以在下面看到使用它的示例。请注意调用函数时的语法,因为 DOT 源代码需要在宽度和高度周围加上双引号。感叹号表示它将强制调整图像大小,直到其中一个维度与指定维度之一相匹配,这似乎只有在指定维度大于图形的原始大小时才有意义。

import pydotplus
from sklearn.datasets import load_breast_cancer
from sklearn.tree import DecisionTreeClassifier, export_graphviz

# Load in the dataset from sklearn
dataset = load_breast_cancer()
X = dataset.data
y = dataset.target
col_names = dataset.feature_names

# Create and fit the decision tree
clf_dt = DecisionTreeClassifier(criterion = 'gini', max_depth = 3)
clf_dt.fit(X_train, y_train)

# Export resulting tree to DOT source code string
dot_data = export_graphviz(clf_dt,
                                feature_names=col_names,
                                out_file=None,
                                filled=True,
                                rounded=True)

pydot_graph = pydotplus.graph_from_dot_data(dot_data)
pydot_graph.write_png('original_tree.png')
pydot_graph.set_size('"5,5!"')
pydot_graph.write_png('resized_tree.png')

单击图片以了解大小,因为它似乎无法在浏览器中正确显示。

original_tree.png: original tree

resized_tree.png:
resized tree

还要注意 pydotplus.graphviz.Graph 对象有一个 to_string() 方法,它返回树的 DOT 源代码字符串,它也可以与graphviz.Source 问题中的对象:

import graphviz
gvz_graph = graphviz.Source(pydot_graph.to_string())
gvz_graph

关于python - 如何指定决策树的 graphviz 表示形式的 figsize?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51346827/

相关文章:

python - 如何打印字符之间有一点延迟的字符串?

python - 如何在 heroku 上部署使用 python 脚本的 nodejs 应用程序

python - 如何获取 Python Pillow (PIL) 版本?

graphviz - graphviz中框的宽度相等

c++ - boost bgl write_graphviz VertexPropertyWriter 和 EdgePropertyWriter

python - 在读取此 xml 之前,如何检查特定元素值 - django python

python - 在循环内部或外部创建极其随机的树分类器

python-3.x - ML 模型无法正确预测

python - 计数向量化器中是否可以有无序二元组

graph - 如何在点中的节点上强制排名?