Sklearn plot_tree plot is too small

Art*_*tur 20 python graphics sklearn-pandas

I have this simple code:

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

tree.plot_tree(clf.fit(X, y))
plt.show()
Run Code Online (Sandbox Code Playgroud)

And the result I get is this graph: 在此处输入图片说明

How do I make this graph legible? I'm using PyCharm Professional 2019.3 as my IDE.

Ren*_*ski 30

我认为您正在寻找的设置是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()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

如果您想捕获整棵树的结构,我想用小字体和高 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)
Run Code Online (Sandbox Code Playgroud)

这是它在较大树上的外观示例。

在此处输入图片说明

在此处输入图片说明


小智 5

事先设置图像的大小怎么样:

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()
Run Code Online (Sandbox Code Playgroud)