简体   繁体   中英

Sklearn plot_tree plot is too small

I have this simple code:

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

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

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.

I think the setting you are looking for is fontsize . You have to balance it with max_depth and figsize to get a readable plot. Here is an example

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()

在此处输入图片说明

If you want to capture structure of the whole tree I guess saving the plot with small font and high dpi is the solution. Then you can open a picture and zoom to the specific nodes to inspect them.

# 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)

Here is an example of how it looks like on the bigger tree.

在此处输入图片说明

在此处输入图片说明

What about setting the size of the image before hand:

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()

Try this:

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

The problem is solved if you set the size before-hand :

from sklearn.tree import plot_tree, export_text
fig = plt.figure(figsize=(25,20))
_ = plot_tree(clf)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM