gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:58:32 27 4
gpt4 key购买 nike

我有一个在鸢尾花数据集上训练的决策树的 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com