Visualising the decision tree in sklearn

Roshan picture Roshan · Sep 6, 2019 · Viewed 14.8k times · Source

When I want to visualise the tree I got this error.

I have shown the required libraries imported. Is there expected reason with jupiter-notebook ?

from sklearn import tree
import matplotlib.pyplot
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_breast_cancer
cancer=load_breast_cancer()
x=cancer.data
y=cancer.target
clf=DecisionTreeClassifier(max_depth=1000)
x_train,x_test,y_train,y_test=train_test_split(x,y)
clf=clf.fit(x_train,y_train)
tree.plot_tree(clf.fit(x_train,y_train))

AttributeError: module 'sklearn.tree' has no attribute 'plot_tree'

Answer

Anna Yashina picture Anna Yashina · Sep 6, 2019

I assigned the tree to an object and added plt.show(). This works for me.

%matplotlib inline
from sklearn import tree
import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_breast_cancer
cancer = load_breast_cancer()
x = cancer.data
y = cancer.target
clf = DecisionTreeClassifier(max_depth = 1000)
x_train,x_test,y_train,y_test = train_test_split(x,y)

fig = clf.fit(x_train,y_train)
tree.plot_tree(fig)
plt.show()

But I recommend using graphviz, it's much more flexible.