简体   繁体   中英

Error when using fit_generator mismatched shape (Keras)

I'm trying to build a simple classification CNN that would divide a set of 1233 images into 4 categories using this code:

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)

But I get a following error: ValueError: Error when checking target: expected dense_2 to have shape (120, 120, 1) but got array with shape (120, 120, 3)

What am I doing wrong?

You should add Flatten layer, because Conv2D returns 3D array for each sample:

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'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM