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

标签 python scikit-learn decision-tree

我有一个来自 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/

相关文章:

python - 代码仍然使用旧版本的Python运行

python - 向 Numpy 数组添加新列/数组

python - 是否可以将 PCA 应用于任何文本分类?

python - 预期和预测的数组最终在 scikit 学习随机森林模型中相同

python - Maya 的 python 模块的 Eclipse 环境

Python Pandas 根据条件更改值

python - sci-kit learn 中 SVC 概率输出的网格搜索交叉验证

r - 将决策树的输出保存到文本文件中

python - 构建决策树

python - 如何手动创建 scikit-learn 树?