gpt4 book ai didi

Python - Graphviz - 删除 DecisionTreeClassifier 节点上的图例

转载 作者:太空宇宙 更新时间:2023-11-04 00:34:06 25 4
gpt4 key购买 nike

我有一个来自 sklearn 的决策树分类器,我使用 pydotplus 来展示它。然而,当我的演示文稿(熵、样本和值)的每个节点上有很多信息时,我真的不喜欢。

enter image description here

为了更容易向人们解释,我只想保留决定和类(class)。我在哪里可以修改代码来执行此操作?

谢谢。

最佳答案

根据documentation , 不可能避免在框内设置附加信息。唯一可以隐式省略的是 impurity 参数。

但是,我用另一种有点歪曲的显式方式完成了它。首先,我保存 .dot 文件,将杂质设置为 False。然后,我打开它并将其转换为字符串格式。我使用正则表达式减去冗余标签并重新保存。

代码是这样的:

import pydotplus  # pydot library: install it via pip install pydot
from sklearn.tree import DecisionTreeClassifier
from sklearn.tree import export_graphviz
from sklearn.datasets import load_iris

data = load_iris()
clf = DecisionTreeClassifier()
clf.fit(data.data, data.target)

export_graphviz(clf, out_file='tree.dot', impurity=False, class_names=True)

PATH = '/path/to/dotfile/tree.dot'
f = pydot.graph_from_dot_file(PATH).to_string()
f = re.sub('(\\\\nsamples = [0-9]+)(\\\\nvalue = \[[0-9]+, [0-9]+, [0-9]+\])', '', f)
f = re.sub('(samples = [0-9]+)(\\\\nvalue = \[[0-9]+, [0-9]+, [0-9]+\])\\\\n', '', f)

with open('tree_modified.dot', 'w') as file:
file.write(f)

修改前后对比如下:

enter image description here enter image description here

在您的情况下,框中似乎有更多参数,因此您可能需要稍微调整一下代码。

希望对您有所帮助!

关于Python - Graphviz - 删除 DecisionTreeClassifier 节点上的图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44821349/

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