在sklearn中可视化决策树

8

当我想要可视化树时,出现了这个错误。

我已经展示了所需的导入库。是否与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))

属性错误:模块'sklearn.tree'没有属性'plot_tree'


请点击此处查看:https://scikit-learn.org/stable/modules/tree.html - PV8
请确保您的 matplotlib 版本大于等于 1.5,并尝试在将其放入绘图函数之前将拟合结果保存到一个对象中。 - Anna Yashina
matplotlib 版本为 3.0.3。 - Roshan
3
plot_tree 是在 0.21 版本中新增的。也许需要检查您的 scikit-learn 版本。 - Josmoor98
非常感谢,这就是我的sklearn版本。 - Roshan
4个回答

8

我将树分配给一个对象并添加了plt.show()。这对我有效。

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

但我建议使用graphviz,因为它更加灵活。


1
当前版本为0.21.3。如果您使用的是Anaconda,可以通过运行“conda upgrade scikit-learn”或“!pip install -U scikit-learn”进行升级。 - Anna Yashina
非常感谢,我在升级后得到了它。 - Roshan
3
这不是一个答案。你只是在说“我没有这个问题”。 - Nicolas Gervais

4

升级 sklearn 包:

pip install --upgrade sklearn

2
这是因为在sklearn版本0.21中,plot_tree是新功能,详见文档。请运行以下代码检查您的版本是否足够:
import sklearn

print(sklearn.__version__)

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

如果您收到错误消息,则需要更新sklearn
pip install --upgrade sklearn

1

因为plot_tree是在sklearn版本0.21之后定义的

检查版本 打开任何Python IDE 运行以下程序。

import sklearn
print (sklearn.__version__)

如果版本显示小于0.21,则需要升级sklearn库。
打开Anaconda提示符并输入以下命令。
pip install --upgrade scikit-learn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接