Output dimension of Keras model

岁酱吖の 提交于 2021-02-10 18:07:14

问题


I use ImageDataGenerator to load my training data

train_generator = train_datagen.flow_from_directory(
    directory= TRAIN_PATH,
    target_size=(224, 224),
    color_mode="rgb",
    batch_size=32,
    class_mode="categorical",
    shuffle=True,
    seed=42
)  

After that I get a message

Found 6552 images belonging to 102 classes.

When I define the model the way

model1 = MobileNetV2(include_top=False, input_shape=(224, 224, 3))
flat1 = Flatten()(model1.outputs)
class1 = Dense(1024, activation='relu')(flat1)
output = Dense(output_dim = 102, activation='softmax')(class1)
model = Model(inputs=model1.inputs, outputs=output)

model.compile(optimizer=keras.optimizers.Adam(),
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

history = model.fit_generator(
      train_generator,
      steps_per_epoch=100,
      epochs=100,
      verbose=2)

I've got the following error

ValueError: Error when checking target: expected dense_2 to have shape (1,) but got array with shape (102,)

But my output layer has shape 102. Why does this happen?


回答1:


you can solve simply changing the loss from sparse_categorical_crossentropy to categorical_crossentropy.

"categorical" mode in a generator will one-hot encode labels and this not suits with sparse_categorical_crossentropy



来源:https://stackoverflow.com/questions/62872581/output-dimension-of-keras-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!