【问题标题】:NameError: name 'pydotplus' is not definedNameError:名称“pydotplus”未定义
【发布时间】:2020-12-13 06:42:21
【问题描述】:

我正在使用 Anaconda 和 Jupyter Notebook 并收到以下错误:

NameError: name 'pydotplus' is not defined

在为 python3 机器学习决策树运行以下代码时:

import pandas
from sklearn import tree
import pydotplus
from sklearn.tree import DecisionTreeClassifier
import matplotlib.pyplot as plt
import matplotlib.image as pltimg

df = pandas.read_csv("shows.csv")

d = {'UK': 0, 'USA': 1, 'N': 2}
df['Nationality'] = df['Nationality'].map(d)
d = {'YES': 1, 'NO': 0}
df['Go'] = df['Go'].map(d)

features = ['Age', 'Experience', 'Rank', 'Nationality']

X = df[features]
y = df['Go']

dtree = DecisionTreeClassifier()
dtree = dtree.fit(X, y)
data = tree.export_graphviz(dtree, out_file=None, feature_names=features)
graph = pydotplus.graph_from_dot_data(data)
graph.write_png('mydecisiontree.png')

img=pltimg.imread('mydecisiontree.png')
imgplot = plt.imshow(img)
plt.show()

【问题讨论】:

  • 您可以使用import pydotplus,但是当您尝试使用它时出现NameError?这似乎不可能。
  • 我能够在 Anaconda 中解决我的问题,但后来我去 kaggle 并不能让它在那里工作。我改为导入 graphiz 的实现,根本不再唱 pydotplus。

标签: python python-3.x jupyter-notebook anaconda pydotplus


【解决方案1】:

您是否尝试过从 pydotplus 导入您需要的特定方法?

喜欢:from pydotplus import graph_from_dot_data,因为您只使用模块中的一种方法。

【讨论】:

    【解决方案2】:

    我能够实施所选答案中提供的解决方案:

    import pydotplus # <----------------------- LOOK HERE
    dtree = DecisionTreeClassifier()
    dtree = dtree.fit(X, y)
    data = tree.export_graphviz(dtree, out_file=None, feature_names=features)
    graph = pydotplus.graph_from_dot_data(data) # <-------- LOOK HERE
    graph.write_png('mydecisiontree.png')
    
    img=pltimg.imread('mydecisiontree.png')
    imgplot = plt.imshow(img)
    plt.show()
    

    我能够在 Anaconda 中解决我的问题,但后来我去 kaggle 并不能让它在那里工作。我改为导入 graphiz 的实现,根本不再唱 pydotplus。

    import graphviz
    dtree = tree.DecisionTreeClassifier(random_state = 1,max_depth = 5,min_samples_split=2)
    dtree = dtree.fit(X, y)
    data = tree.export_graphviz(dtree,feature_names=features,out_file=None)
    graph = graphviz.Source(data)
    graph
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-24
      • 1970-01-01
      • 2021-04-15
      • 2019-01-26
      • 2021-10-05
      • 2017-08-16
      相关资源
      最近更新 更多