Python object is not an iterator

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fit_generator TypeError: function object is not an iterator #8321

fit_generator TypeError: function object is not an iterator #8321

Comments

When I’m using fit_generator function with my own generator, I got the error code here.
Exception in thread Thread-1: Traceback (most recent call last): File «/opt/software/anaconda2/lib/python2.7/threading.py», line 801, in __bootstrap_innerself.run() File «/opt/software/anaconda2/lib/python2.7/threading.py», line 754, in run self.__target(*self.__args, **self.__kwargs) File «/opt/software/anaconda2/lib/python2.7/site-packages/keras/utils/data_utils.py», line 568, in data_generator_task generator_output = next(self._generator) TypeError: function object is not an iterator Epoch 1/100 Traceback (most recent call last): File «xception.py», line 85, in model.fit_generator(train_gen, steps_per_epoch=5380, epochs=100, callbacks=[checkpoint], verbose=1) File «/opt/software/anaconda2/lib/python2.7/site-packages/keras/legacy/interfaces.py», line 87, in wrapper return func(*args, **kwargs) File «/opt/software/anaconda2/lib/python2.7/site-packages/keras/engine/training.py», line 2011, in fit_generator generator_output = next(output_generator) StopIteration

Читайте также:  Html как накладывать изображения

while my generator is coded like this:

def data_generator():
datapath = ‘../images/crop_train_images/’
csvpath = ‘../images/crop_train_images.csv’
csvfile = pd.read_csv(csvpath)

train_images = [] train_labels = [] while True: for index, (image_id,label_id) in csvfile.iterrows(): index = int(index) image_id = str(image_id) label_id = int(label_id) print(index) furl = datapath + image_id.replace('.jpg', '.npy') images = np.load(furl) for idx in range(len(images)): train_images.append(images[idx]) train_labels.append(np.squeeze(to_categorical(label_id, 80))) if index !=0 and index % 10 == 0 or index == len(csvfile)-1: train_images = np.array(train_images) train_labels = np.array(train_labels) N = train_images.shape[0] choice = random.sample(range(N), N) train_images = train_images[choice] train_labels = train_labels[choice] yield (train_images, train_labels) train_images = [] train_labels = [] 

`
I’ve tried to use the data_generator function to load data and it goes well. But when using the fit_generator function , there threw an exception and i don’t know where goes wrong . can someone help me figure out what had happened?

The text was updated successfully, but these errors were encountered:

Источник

How to resolve TypeError: ‘list’ object is not an iterator in Python

If you are looking for a solution to the TypeError: ‘list’ object is not an iterator error in Python, then this is the article for you. The cause of the error is that the list is used as iterator and I will fix it by passing the list. book to iter method or use generator. Post details below.

What causes the TypeError: ‘list’ object is not an iterator error?

Iterator are objects that allow us to get each element in it, which can be done iteratively. For example, using a loop over an iterator.

In Python, the iterator implements two particular protocols, the __iter__ protocol and the __next__ protocol.

  • The __iter__ method returns the iterator object itself. The method must be implemented if you want to use the for loop or the print command on the iterator object.
  • The __next__ method returns the next element. If the iterator runs out of elements, the program will throw a StopIteration error.

The TypeError: ‘list’ object is not an iterator error that happens because the list is used as an iterator.

listCities = ['Frankfurt', 'Amsterdam', 'Venice'] # Using the __next__ method causes an error print(next(listInfor)) print(next(listInfor)) print(next(listInfor))
Traceback (most recent call last): File "./prog.py", line 4, in TypeError: 'list' object is not an iterator

How to solve this error?

Pass the list to the __iter__ method.

  • Pass the list to the __iter__ method to get the iterator object itself.
  • The result is an iterator, this time using the __next__ method to return the next elements.
listCities = ['Frankfurt', 'Amsterdam', 'Venice'] # The __iter__ method returns the iterator object itself iteratorObj = iter(listCities) # Use the __next__ method to get elements in the list print(next(iteratorObj)) print(next(iteratorObj)) print(next(iteratorObj))
Frankfurt Amsterdam Venice

One problem when you use the next() method is that when the iterator runs out of program elements, it will throw a StopIteration error. To prevent the program from stopping, use the try/except block.

listCities = ['Frankfurt', 'Amsterdam', 'Venice'] # The __iter__ method returns the iterator object itself iteratorObj = iter(listCities) try: # Use the __next__ method to get elements in the list print(next(iteratorObj)) print(next(iteratorObj)) print(next(iteratorObj)) print(next(iteratorObj)) except StopIteration: print('Out of return value')
Frankfurt Amsterdam Venice Out of return value

Use generator.

The generator is a simple way to create iterators. Without a generator, creating an iterator goes through quite a few steps, such as implementing the class with __iter()__ and __next()__ methods, keeping track of the internal conditions, keeping track of the StopIteration that occurs when no value is returned. Simplified, a Generator is a function that returns an iterator object that we can iterate over. In creating a Generator, you still use the ‘def’ keyword like a function, but instead of ‘return’ as a function, the generator uses the ‘yield’ statement to return the elements.

listCities = ['Frankfurt', 'Amsterdam', 'Venice'] def myGenerator(): for i in range(len(listCities)): yield listCities[i] gen = myGenerator() try: print(next(gen)) print(next(gen)) print(next(gen)) print(next(gen)) except StopIteration: print('Out of return value')
Frankfurt Amsterdam Venice Out of return value

Summary

The problem TypeError: ‘list’ object is not an iterator in Python is probably solved. If you have any questions or have a more creative way, I hope you will share it with everyone by commenting below. Thank you for reading my article.

My name is Jason Wilson, you can call me Jason. My major is information technology, and I am proficient in C++, Python, and Java. I hope my writings are useful to you while you study programming languages.

Name of the university: HHAU
Major: IT
Programming Languages: C++, Python, Java

Источник

Обойти строку в for in можно, но ‘str’ object is not an iterator. Не все, что в for in — итераторы?

Если тип можно использовать в for-in, то он итерируем и можно применить next() — сколько читал про механизм получения следующего объекта, данный метод ее реализует, а тут его нет, при этом b итерируется. оО?

sim3x

aRegius

>>> s = 'ABC' #iterable, но не iterator >>> for char in s: print(char) A B C
>>> s = 'ABC' >>> it = iter(s) #а вот уже iterator, созданный из iterable >>> for i in range(4): print(next(it)) A B C Traceback (most recent call last): File "", line 2, in print(next(it)) StopIteration >>>

#1.
>>s = ‘abc’
>>print(next(s))
TypeError: ‘str’ object is not an iterator

В первом случае next() пытается вывести первый элемент контейнера s, но ему передается вместо этого адрес самого контейнера, поэтому он выдает исключение?
Метод iter() нужен для того, чтобы обращаться внутрь контейнера и выдавать адреса элементов?

aRegius

nevro: В первом случае причина исключения в том, что строковый объект (в данном случае ‘abc’) НЕ является Итератором. А функцию next() поддерживают Только Итераторы.

Метод iter нужен для того, чтобы из итерируемого объекта (читай «последовательности») создать Итератор, который и будет поддерживать функцию next().

aRegius: iter возращает self — это адрес на последовательность или на объект в этой последовательности? В данном примере на объект str.

Источник

TypeError: ‘list’ object is not an iterator

We have covered off many TypeErrors on this website, here we will go through which using a list with and it is not an iterator gives you errors.

In order to understand this error better, we need to first understand what is an iterator in Python?

An iterator is a Python object that has the following characteristics:

  • You can count the no of values that are contained within it.
  • It also can be iterated through, so you need to apply an iteration method to it.

How does this error occur?

Normally this error occurs when you try to iterate over a list, but you have not made the list iterable.

There are two things required to make this happen:

(A) The iter() returns an iterator object

(B) The next() method moves to the next value.

Without both the code will fail and the error you are about will occur!

In the below code we have a list:

a = ['q', 'w', 'e', 'r', 't', 'y'] with the following: b = next(a) b = next(a) b = next(a) b = next(a) b = next(a) b = next(a)

As can be seen in the above code we have one component for the iteration , we expect two as per the above.

As a result we get the error:

Traceback (most recent call last): File "list_object_is_not_an_iterator.py", line 13, in b = next(a) TypeError: 'list' object is not an iterator 

In order to fix this ,all we need to do is apply the iterator to the list as follows:

a = iter(['q', 'w', 'e', 'r', 't', 'y']) ====> We added in the iter() here, enclosing the list within it b = next(a) b = next(a) b = next(a) b = next(a) b = next(a) b = next(a) #b = next(a) print(b) Giving output: y

As a result of this, we now have the two required methods that will not give this error.

What is going on within the iterator?

In the above code we have asked to print b. What the iterator is doing is going to the first value of b, in this case q and print.

But because we have a variable b on multiple lines, with the method “next()” in it, the logic is moving through each value of the list till it gets to the end.

What can be done though is , reduce the length of the returned b variables to print as follows:

a = iter(['q', 'w', 'e', 'r', 't', 'y']) b = next(a) print(b) returns: q BUT a = iter(['q', 'w', 'e', 'r', 't', 'y']) b = next(a) b = next(a) print(b) returns: w

As can be seen it returns the next value in the list. You can keep adding the b variables.

What happens when you get to the end of the list?

So now we have the below, and we are returning the last value:

a = iter(['q', 'w', 'e', 'r', 't', 'y']) b = next(a) b = next(a) b = next(a) b = next(a) b = next(a) b = next(a) Returns: y

The reason for this is that we have the required no of variables with the next method, which equals the length of the list.

If we add in one more b variable:

a = iter(['q', 'w', 'e', 'r', 't', 'y']) b = next(a) b = next(a) b = next(a) b = next(a) b = next(a) b = next(a) b = next(a) ===> Additional b variable Returns: Traceback (most recent call last): File "list_object_is_not_an_iterator.py", line 19, in b = next(a) StopIteration

The purpose of StopIteration is to not allow a continuous loop and recognise that the end of the list has been reached.

Implementing Iterators

Iterators could be used in the following circumstances:

(A) You have a defined list of object values to work with.

(B) If sequence is important an iterator will help to process values in the order they appear in a list.

Источник

Оцените статью