简体   繁体   中英

Visualising the decision tree in sklearn

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'

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.

升级sklearn包:

pip install --upgrade sklearn

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

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

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