Ada*_*dam 8 python module function python-itertools anaconda
我将自定义函数保存在一个单独的模块中,我可以在需要时调用它.我的一个新函数使用itertools,但我不断收到名称错误.
NameError: name 'itertools' is not defined
Run Code Online (Sandbox Code Playgroud)
这真的很奇怪.我可以在控制台中导入itertools,但是当我调用我的函数时,我得到一个名称错误.通常,只要我先导入库,我就可以在自定义函数中使用其他库(pandas,sklearn等)中的函数.
但是如果我在控制台中导入itertools,将我的函数复制并粘贴到控制台,然后调用该函数,它工作正常.
它让我发疯,但我想也许我只是不理解模块或其他东西的规则.
这是我在模块中使用的功能.它只是从一个sklearn示例中复制并粘贴:
import itertools
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues):
import itertools
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print("Normalized confusion matrix")
else:
print('Confusion matrix, without normalization')
print(cm)
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, cm[i, j],
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
Run Code Online (Sandbox Code Playgroud)
我尝试在函数内部,模块内部以及我调用它的文件中导入它 - 一切都没有运气.如果我在控制台中导入它很好.即使它已经在控制台中导入,如果我在我正在处理的文件中运行它,它也会出现同样的错误.