在 sklearn 中可视化决策树

Ros*_*han 7 python tree sklearn-pandas jupyter-notebook

当我想可视化这棵树时,我收到了这个错误。

我已经展示了导入的所需库。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))
Run Code Online (Sandbox Code Playgroud)

AttributeError: 模块“sklearn.tree”没有属性“plot_tree”

Ann*_*ina 7

我将树分配给一个对象并添加了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()
Run Code Online (Sandbox Code Playgroud)

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

  • 这不是一个答案。你只是说“我没有这个问题”。 (3认同)