Keras ZeroDivisionError:整数除法或模数为零

时间:2017-07-09 16:48:47

标签: python tensorflow keras

我尝试使用Keras和Tensorflow实现卷积神经网络。

我有以下代码:

from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense

model = Sequential()
model.add(Conv2D(32, (2, 2), input_shape=(3, 150, 150), padding='SAME'))
model.add(Activation('relu'))
# model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(MaxPooling2D(pool_size=(2, 2), data_format="channels_first"))

model.add(Conv2D(32, (2, 2), padding='SAME'))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2), data_format="channels_first"))

model.add(Conv2D(64, (2, 2), padding='SAME'))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2), data_format="channels_first"))

print("after declaring models")

model.add(Flatten())  # this converts our 3D feature maps to 1D feature vectors
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(1))
model.add(Activation('sigmoid'))

model.compile(loss='binary_crossentropy',
              optimizer='rmsprop',
              metrics=['accuracy'])

print("After creating the model\n")


batch_size = 16

# this is the augmentation configuration we will use for training
train_datagen = ImageDataGenerator(
        rescale=1./255,
        shear_range=0.2,
        zoom_range=0.2,
        horizontal_flip=True)

# this is the augmentation configuration we will use for testing:
# only rescaling
test_datagen = ImageDataGenerator(rescale=1./255)

# this is a generator that will read pictures found in
# subfolers of 'data/train', and indefinitely generate
# batches of augmented image data
train_generator = train_datagen.flow_from_directory(
        '../input/train',  # this is the target directory
        target_size=(150, 150),  # all images will be resized to 150x150
        batch_size=batch_size,
        class_mode='binary')  # since we use binary_crossentropy loss, we need binary labels            

model.fit_generator(
        train_generator,
        steps_per_epoch=2000 // batch_size,
        epochs=50)

问题是在最后一行我得到了:

Epoch 1/50
17.3s
6
Exception in thread Thread-20:
Traceback (most recent call last):
  File "/opt/conda/lib/python3.6/threading.py", line 916, in _bootstrap_inner
    self.run()
  File "/opt/conda/lib/python3.6/threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
  File "/opt/conda/lib/python3.6/site-packages/Keras-2.0.5-py3.6.egg/keras/utils/data_utils.py", line 590, in data_generator_task
    generator_output = next(self._generator)
  File "/opt/conda/lib/python3.6/site-packages/Keras-2.0.5-py3.6.egg/keras/preprocessing/image.py", line 737, in __next__
    return self.next(*args, **kwargs)
  File "/opt/conda/lib/python3.6/site-packages/Keras-2.0.5-py3.6.egg/keras/preprocessing/image.py", line 1026, in next
    index_array, current_index, current_batch_size = next(self.index_generator)
  File "/opt/conda/lib/python3.6/site-packages/Keras-2.0.5-py3.6.egg/keras/preprocessing/image.py", line 720, in _flow_index
    current_index = (self.batch_index * batch_size) % n
ZeroDivisionError: integer division or modulo by zero

17.3s
7
Traceback (most recent call last):
  File "../src/script.py", line 115, in <module>
    epochs=50)
  File "/opt/conda/lib/python3.6/site-packages/Keras-2.0.5-py3.6.egg/keras/legacy/interfaces.py", line 87, in wrapper
  File "/opt/conda/lib/python3.6/site-packages/Keras-2.0.5-py3.6.egg/keras/models.py", line 1117, in fit_generator
  File "/opt/conda/lib/python3.6/site-packages/Keras-2.0.5-py3.6.egg/keras/legacy/interfaces.py", line 87, in wrapper
  File "/opt/conda/lib/python3.6/site-packages/Keras-2.0.5-py3.6.egg/keras/engine/training.py", line 1809, in fit_generator
StopIteration

如何划分为0? 我不知道任何变量如何都是0。

2 个答案:

答案 0 :(得分:14)

除以零来自n等于零的事实。 n是要循环的数据集中的样本总数,因此这意味着您的图像生成器无法提供任何数据。最有可能的原因是训练数据的排列方式。 Keras希望将图像排列在每个图像类包含一个子目录的目录中,例如

input/
    train/
        class_0/
            class_0_0.jpg
            class_0_1.jpg
            ...
        class_1/
            class_1_0.jpg
            class_1_1.jpg
            ...
        ...

请注意,这甚至适用于非分类任务。当flow_from_directoryclass_mode时,None仍然需要包含带图片的子目录的目录。

答案 1 :(得分:0)

我的情况略有不同,但与您的错误消息一样,消息中也有答案。我的问题是在Tensorboard回调中。我试图用update_freq=0禁用它:

tf.keras.callbacks.TensorBoard(
        log_dir=logdir,
        update_freq=0)

这给了我错误消息:

if self.update_freq != 'epoch' and batch % self.update_freq == 0:
ZeroDivisionError: integer division or modulo by zero

赠品在batch % self.update_freq == 0中。

在读取docs for Tensorboard callback之后,我意识到我使用的是无效值。