Keras:在`flow_from_directory`中使用`crossentropy`

时间:2017-07-16 04:08:43

标签: python keras

我正在尝试使用flow_from_directory来训练我的模型。我使用的损失是binary_crossentropy,需要在to_categorical数据上调用Y_train函数。我不知道如何为flow_from_directory执行此操作,程序会抛出以下错误:

Traceback (most recent call last):
  File "vgg16-sim-conn-rmsprop-2-main.py", line 316, in <module>
    epochs=25
  File "/home/yx96/anaconda2/lib/python2.7/site-packages/keras/legacy/interfaces.py", line 8
8, in wrapper
    return func(*args, **kwargs)
  File "/home/yx96/anaconda2/lib/python2.7/site-packages/keras/engine/training.py", line 187
6, in fit_generator
    class_weight=class_weight)
  File "/home/yx96/anaconda2/lib/python2.7/site-packages/keras/engine/training.py", line 161
4, in train_on_batch
    check_batch_axis=True)
  File "/home/yx96/anaconda2/lib/python2.7/site-packages/keras/engine/training.py", line 129
9, in _standardize_user_data
    exception_prefix='model target')
  File "/home/yx96/anaconda2/lib/python2.7/site-packages/keras/engine/training.py", line 133
, in _standardize_input_data
    str(array.shape))
ValueError: Error when checking model target: expected predictions to have shape (None, 2) b
ut got array with shape (100, 1)

我使用的数据生成器是:

train_datagen = ImageDataGenerator(
    featurewise_center=True,
    horizontal_flip=True,
    zoom_range=0.2,
    data_format="channels_last"
)

train_generator = train_datagen.flow_from_directory(
    './train',
    target_size=(224, 224),
    batch_size=100,
    class_mode='binary'
)

fit_generator是:

model.fit_generator(
    train_generator,
    steps_per_epoch=2500,
    epochs=25
)

1 个答案:

答案 0 :(得分:1)

如果您使用binary_crossentropy进行损失,则可以设置class_mode='binary'

虽然您可能失败了,但由于您没有向我们展示模型,因此未在您的帖子中显示,而是在模型的最后一层。

你可能有Dense(2, activation='softmax')。这是“一热”或分类的交叉版本。如果你想工作二进制,你只输出一个介于0和1之间的值。你这样做:

Dense(1, activation = 'sigmoid')

我希望这可以解决你的问题: - )