Sklearn绘制的决策树图太小了。

47

我有这段简单的代码:

clf = tree.DecisionTreeClassifier()
clf = clf.fit(X, y)

tree.plot_tree(clf.fit(X, y))
plt.show()

我得到的结果是这个图表:enter image description here

如何使这个图表更易读? 我正在使用 PyCharm Professional 2019.3 作为我的 IDE。

4个回答

64

我认为您要查找的设置是fontsize。为了获得可读的图表,您需要平衡它与max_depthfigsize。这是一个例子。

from sklearn import tree
from sklearn.datasets import load_iris
import matplotlib.pyplot as plt

# load data
X, y = load_iris(return_X_y=True)

# create and train model
clf = tree.DecisionTreeClassifier(max_depth=4)  # set hyperparameter
clf.fit(X, y)

# plot tree
plt.figure(figsize=(12,12))  # set plot size (denoted in inches)
tree.plot_tree(clf, fontsize=10)
plt.show()

enter image description here

如果您想捕获整个树的结构,我猜保存小字体和高dpi的绘图是解决方案。然后,您可以打开图片并缩放到特定节点以进行检查。

# create and train model
clf = tree.DecisionTreeClassifier()
clf.fit(X, y)

# save plot
plt.figure(figsize=(12,12))
tree.plot_tree(clf, fontsize=6)
plt.savefig('tree_high_dpi', dpi=100)

这是在更大的树上看起来的例子。

输入图片描述

输入图片描述


我从一个链接的答案中看到,你可以在plot_tree上设置max_depth,例如tree.plot_tree(decision_tree=clf, max_depth=4),而不是在分类器上设置,我认为这是更好的选择,因为在分类器上设置会影响你的决策树的结果,而不仅仅是可视化。 - undefined

10

那么,提前设置图片的尺寸怎么样:

clf = tree.DecisionTreeClassifier()
clf = clf.fit(X, y)

fig, ax = plt.subplots(figsize=(10, 10))  # whatever size you want
tree.plot_tree(clf.fit(X, y), ax=ax)
plt.show()

这并没有真正使 plot_tree 适合 OP 想要的可读性。 所有这做的只是扩展子图,使其适合更多的项目,但并没有将子图扩展到任何可读的程度,就像动态方式那样。 - Vaidøtas I.

0

试试这个:

plt.figure(figsize=(12,12))
tree.plot_tree(clf, fontsize=10)
plt.show()

1
你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心中找到有关如何编写良好答案的更多信息。 - Community

0
如果您在预先设置大小,则可以解决问题:
from sklearn.tree import plot_tree, export_text
fig = plt.figure(figsize=(25,20))
_ = plot_tree(clf)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接