【问题标题】:Error when using fit_generator mismatched shape (Keras)使用 fit_generator 形状不匹配时出错 (Keras)
【发布时间】:2020-06-08 02:08:53
【问题描述】:

我正在尝试构建一个简单的分类 CNN,它将使用以下代码将一组 1233 张图像分为 4 个类别:

unclassified_datagen = keras.preprocessing.image.ImageDataGenerator(
    rescale=1. / 255,
    horizontal_flip=True
)
unclassified_generator = train_datagen.flow_from_directory(
    'data/unclassified',
    target_size=(120, 120),
    batch_size=1233,
    class_mode='input',
    shuffle=False,
)

model_unclassified = keras.Sequential()
model_unclassified.add(layers.Conv2D(1233, (3, 3), input_shape=(120, 120, 3), padding="SAME"))
model_unclassified.add(layers.Dense(64, activation='relu'))
model_unclassified.add(layers.Dense(4, activation='sigmoid'))

model_unclassified.compile(loss='sparse_categorical_crossentropy',
                           optimizer='rmsprop',
                           metrics=['accuracy'])
model_unclassified.fit_generator(unclassified_generator, epochs=1)

但我收到以下错误:ValueError: Error when checking target: expected dense_2 to have shape (120, 120, 1) but got array with shape (120, 120, 3)

我做错了什么?

【问题讨论】:

    标签: python machine-learning keras neural-network


    【解决方案1】:

    您应该添加Flatten 层,因为Conv2D 会为每个样本返回 3D 数组:

    model_unclassified = keras.Sequential()
    model_unclassified.add(layers.Conv2D(1233, (3, 3), input_shape=(120, 120, 3), padding="SAME"))
    model_unclassified.add(layers.Flatten())
    model_unclassified.add(layers.Dense(64, activation='relu'))
    model_unclassified.add(layers.Dense(4, activation='sigmoid'))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-17
      • 1970-01-01
      • 2018-10-18
      • 2018-11-04
      • 1970-01-01
      • 2018-07-19
      相关资源
      最近更新 更多