【问题标题】:Visualising the decision tree in sklearn在 sklearn 中可视化决策树
【发布时间】:2020-01-09 01:54:52
【问题描述】:

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

我已经展示了导入的所需库。 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: 模块 'sklearn.tree' 没有属性 'plot_tree'

【问题讨论】:

  • 确保您的 matplotlib 版本 >= 1.5 并在将其放入绘图功能之前尝试将其保存到对象
  • matplotlib 版本为 3.0.3
  • plot_tree 是 0.21 版中的新功能。也许检查你的 scikit-learn 版本
  • 非常感谢,这是我的 sklearn 版本

标签: python tree jupyter-notebook sklearn-pandas


【解决方案1】:

我将树分配给一个对象并添加了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,它更灵活。

【讨论】:

  • 当前版本是 0.21.3,如果你使用 anaconda,你可以升级运行 !pip install -U scikit-learnconda upgrade scikit-learn
  • 非常感谢,我升级后得到了
  • 这不是答案。你只是说“我没有这个问题”。
【解决方案2】:

升级sklearn包:

pip install --upgrade sklearn

【讨论】:

    【解决方案3】:

    这是因为plot_tree 是新的sklearn 0.21 版,如documentation 所示。通过运行以下命令检查您是否有足够的版本:

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

    如果收到错误信息,需要更新sklearn

    pip install --upgrade sklearn
    

    【讨论】:

      【解决方案4】:

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

      用于检查版本 打开任何python空闲 运行下面的程序。

      import sklearn
      print (sklearn.__version__)
      

      如果版本显示低于0.21,则需要升级sklearn库。

      打开 Anaconda 提示符并写入以下命令

      pip install --upgrade scikit-learn
      

      【讨论】:

        猜你喜欢
        • 2017-05-01
        • 2012-07-03
        • 2019-04-09
        • 2020-08-17
        • 2017-08-10
        • 2021-12-25
        • 2020-12-12
        • 2015-03-05
        相关资源
        最近更新 更多