I'm trying to visulise a decision tree i've just constructed, however the figure is always low quality and you can't read the labels! Just wondering if there is a fix for this?
My code for brining up the graph is below, I can't zoom in using the figure viewer either.
from sklearn.tree import plot_tree
plt.figure()
plot_tree(model, filled=True)
plt.title("Decision tree")
plt.savefig('testfig.svg', format='svg', dpi=1200)
plt.show()
The model is a standard decison tree classifer as shown below.
X_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.3, random_state=20)
from sklearn.tree import DecisionTreeClassifier
model = DecisionTreeClassifier()
model.fit(X_train, y_train)
I've tried messing with the dpi and file type, as well as saving directly from the figure viewer but nothing has worked, I just need it so that I can export it and see the labels.
CodePudding user response:
For moderate-sized trees, the .svg
rendering should be a good option to produce vector graphic outputs.
Here's a minimal example showing the original figure and a zoomed-in portion at the bottom right:
from sklearn.datasets import make_classification
from sklearn.tree import DecisionTreeClassifier
from sklearn.tree import plot_tree
import matplotlib.pyplot as plt
X, y = make_classification(n_samples=1000)
clf = DecisionTreeClassifier(max_leaf_nodes=40).fit(X, y)
plt.figure()
plot_tree(clf, filled=True)
plt.savefig('testfig.svg', format='svg')
Alternatively, if you have a copy of graphviz
available, you can export the tree as a graphviz string and render the tree separately.
from sklearn.tree import export_graphviz
with open("testdot.dot", "w") as fh:
fh.write(export_graphviz(clf, filled=True))
# dot -Tpng testdot.dot -o testdot.png