8

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'

Nicolas Gervais
  • 33,817
  • 13
  • 115
  • 143
Roshan
  • 101
  • 1
  • 1
  • 6

4 Answers4

8

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.

Anna Yashina
  • 514
  • 8
  • 18
4

upgrade sklearn package:

pip install --upgrade sklearn
Mohammad Nazari
  • 2,535
  • 1
  • 18
  • 29
2

This is because plot_tree is new is sklearn version 0.21, as indicated in the documentation. Check if you have a version sufficient by running this:

import sklearn

print(sklearn.__version__)

assert float(sklearn.__version__[2:]) >= 21, 'sklearn version insufficient.'

If you get an error message, you need to update sklearn

pip install --upgrade sklearn
Nicolas Gervais
  • 33,817
  • 13
  • 115
  • 143
1

Because plot_tree is defined after sklearn version 0.21

For checking Version Open any python idle Running below program.

import sklearn
print (sklearn.__version__)

If the version shows less than 0.21 then you need to upgrade the sklearn library.

Open Anaconda prompt and write below command

pip install --upgrade scikit-learn