NameError: name 'pydotplus' is not defined

NameError: name 'pydotplus' is not defined

我正在使用 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()

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

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

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

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,但无法让它在那里工作。我更改为 import graphiz 而不是 import 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