Keras模型的输出尺寸 [英] Output dimension of Keras model

查看:125
本文介绍了Keras模型的输出尺寸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用ImageDataGenerator加载训练数据

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
)  

那之后我收到一条消息

Found 6552 images belonging to 102 classes.

当我定义模型的方式

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)

我遇到以下错误

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

但是我的输出层的形状是102.为什么会发生这种情况?

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

推荐答案

您可以解决,只需将损耗从sparse_categorical_crossentropy更改为categorical_crossentropy.

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

类别"生成器中的模式会一键编码标签,这不适用于sparse_categorical_crossentropy

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

这篇关于Keras模型的输出尺寸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆