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

Python - Graphviz - Remove legend on nodes of DecisionTreeClassifier

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

为了更容易向人们解释,我只想保留决定和 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)

修改前后的图片如下:

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

希望对您有所帮助!