python - Keras 多类模型尺寸错误

标签 python deep-learning keras

Keras 新手,尝试重新实现以下二进制图像分类示例:https://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html

它对我来说适用于二元分类。 为 3 类分类重建它,我收到以下尺寸不匹配错误:

     60         epochs=50,
     61         validation_data=validation_generator,
---> 62         validation_steps=250 // batch_size)
ValueError: Error when checking target: expected activation_50 to have shape (None, 1) but got array with shape (16, 3)

这是我当前的实现:

from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras import backend as K
K.set_image_dim_ordering('th')
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(
        'F://train_data//',  # this is the target directory
        target_size=(150, 150),  # all images will be resized to 150x150
        batch_size=batch_size,
        class_mode='categorical')  # since we use binary_crossentropy loss, we need binary labels

# this is a similar generator, for validation data
validation_generator = test_datagen.flow_from_directory(
        'F://validation_data//',
        target_size=(150, 150),
        batch_size=batch_size,
        class_mode='categorical')

model = Sequential()

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

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

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

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('softmax')) # instead of sigmoid

model.compile(loss='mean_squared_error',
              optimizer='adam',
              metrics=['accuracy'])

# another loss: sparse_categorical_crossentropy

model.fit_generator(
        train_generator,
        steps_per_epoch=1800 // batch_size,
        epochs=50,
        validation_data=validation_generator,
        validation_steps=250 // batch_size)

到目前为止,我已将输出层的激活函数从sigmoid更改为softmax。将 class_mode 从二进制更改为分类。似乎找不到问题所在。

此外,我知道 StackOverflow 上也有类似的问题: Multi-Output Multi-Class Keras Model

Train multi-class image classifier in Keras

Multi-class classification using keras

但是这些解决方案都没有帮助我。

最佳答案

您需要将最终的Dense层更改为model.add(Dense(3))。 Softmax 激活期望Dense 层中的单位与类的数量相匹配。

此外,如果您要使用 loss='sparse_categorical_crossentropy',请记住将 class_mode 更改为 'sparse'。您当前的设置 class_mode='categorical' 应与 loss='categorical_crossentropy' 一起使用。

关于python - Keras 多类模型尺寸错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45995498/

相关文章:

python - 关闭 matplotlib 中的 Spanselector

python - 如何在 TensorFlow 数字识别中使用自己的手绘图像

python - Keras/Tensorflow 中不同时期的训练率如何变化

image-processing - Convert_imageset.cpp 指南

python - Keras:将元数据连接到 CNN 中

machine-learning - 向 Keras 中 Flatten() 层的输出添加新功能

python - tensorflow_core._api.v2.config中缺少experimental_list_devices属性

python - 在 python 中反转 _ 的显式赋值?

python - 如何从 Keras 的 model.predict 函数获取预测标签?

python - 不要用 Python 字符串 split() 拆分双引号单词?