Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

itertools not defined when used inside module

I save my custom functions in a separate module that I can call when I need to. One of my new functions uses itertools, but I keep getting a name error.

NameError: name 'itertools' is not defined

It's really weird. I can import itertools in the console just fine, but when I call my function, I get a name error. Usually I can use functions from other libraries (pandas, sklearn, etc.) inside a custom function just fine as long as I import the library first.

BUT if I import itertools in the console, copy and paste my function into the console, and then call the function, it works fine.

It's making me crazy, but I'm thinking maybe I'm just not understanding the rules of modules or something.

here's the function i'm using in the module. it's simply copy and pasted from one of the sklearn examples:

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')

I tried importing it inside the function, inside the module, and inside the file where I am calling it - all with no luck. If I import it in the console its fine. Even after it's been imported in the console, if I run it inside the file I'm working on again, it gives the same error.

like image 569
Adam Avatar asked Dec 20 '16 22:12

Adam


People also ask

How do you define Itertools?

Itertools is a module in Python, it is used to iterate over data structures that can be stepped over using a for-loop. Such data structures are also known as iterables. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra.

Is Itertools in Python standard library?

Itertools is a Python module that is part of the Python 3 standard libraries. It lets us perform memory and computation efficient tasks on iterators. It is inspired by constructs from APL, Haskell, and SML.

Do you have to import Itertools?

The itertools module needs to be imported prior to using it in the code.


2 Answers

It works now.

IMPORTANT LESSON: If you edit a module, you must close and reopen spyder/ipython/whatever. Simply resetting the kernel is not sufficient. Stupid of me, I know, but maybe maybe this answer will save someone time.

like image 120
Adam Avatar answered Sep 18 '22 11:09

Adam


You just change
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):

To:

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

like image 33
Vong Ho Avatar answered Sep 20 '22 11:09

Vong Ho