簡體   English   中英

在模塊內部使用時未定義itertools

[英]itertools not defined when used inside module

我將自定義函數保存在一個單獨的模塊中,我可以在需要時調用它。 我的一個新函數使用itertools,但我不斷收到名稱錯誤。

NameError: name 'itertools' is not defined

這真的很奇怪。 我可以在控制台中導入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')

我嘗試在函數內部,模塊內部以及我調用它的文件中導入它 - 一切都沒有運氣。 如果我在控制台中導入它很好。 即使它已經在控制台中導入,如果我在我正在處理的文件中運行它,它也會出現同樣的錯誤。

它現在有效。

重要課程:如果編輯模塊,則必須關閉並重新打開spyder / ipython /等等。 僅僅重置內核是不夠的。 我知道,愚蠢的我,但也許這個答案會節省一些時間。

你改變了
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):

至:

for i in range (cm.shape[0]): for j in range (cm.shape[1]):

您可以先使用itertools導入產品 ,然后將itertools.product更改為簡單的產品 這應該工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM