Я только что начал с Keras и выполнял некоторую предварительную обработку изображений, где я заметил, что генератор, полученный от ImageDataGenerator
, бесконечно повторяется в for-loop
.
image_gen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1/255, rotation_range=45)
train_data_gen = image_gen.flow_from_directory(train_dir,
shuffle=True,
target_size=(IMG_SHAPE, IMG_SHAPE),
batch_size=batch_size
)
print('Total number of batches - {}'.format(len(train_data_gen)))
for n, i in enumerate(train_data_gen):
if n >= 30:
# I have to add explicit break statement to get out of loop when done with iterating over all the items present in generator.
break
batch_data = i[0]
print(n, batch_data[0].shape)
# TRY to access element out of bound to see if there really exists more than 30 elements.
print(''.format(train_data_gen[32]))
Выходные данные
Found 2935 images belonging to 5 classes.
Total number of batches - 30
0 (150, 150, 3)
1 (150, 150, 3)
2 (150, 150, 3)
.
.
.
29 (150, 150, 3)
---------------------------------------------------------------------------
ValueError: Traceback (most recent call last)
<ipython-input-20-aed377bb98f7> in <module>
13 batch_data = i[0]
14 print(n, batch_data[0].shape)
---> 15 print(''.format(train_data_gen[32]))
~/.virtualenvs/pan_demo/lib/python3.6/site-packages/keras_preprocessing/image/iterator.py in __getitem__(self, idx)
55 'but the Sequence '
56 'has length {length}'.format(idx=idx,
---> 57 length=len(self)))
58 if self.seed is not None:
59 np.random.seed(self.seed + self.total_batches_seen)
ValueError: Asked to retrieve element 32, but the Sequence has length 30
Вопрос
- Так ли это
ImageDataGenerator
работать?Если да, могу ли я как-нибудь избежать проверки if n >=30
детали? - Я что-то упускаю при подготовке генератора, который приводит к такому поведению?
Версия Keras: tf.keras.__version__
--> 2.2.4-tf
Версия Tensorflow: tf.VERSION
---> 1.13.1