【问题标题】:Output dimension of Keras modelKeras模型的输出维度
【发布时间】:2020-07-13 17:18:51
【问题描述】:

我使用 ImageDataGenerator 加载我的训练数据

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。为什么会这样?

【问题讨论】:

  • 您使用的是哪个版本的 Keras/Tensorflow?最新的 keras 版本不接受 output_dim 作为 Dense 层的参数。
  • @Bob 我正在使用 v. 2.3.1 但是它只是警告在 v. 2.3.1 中使用“output_dim =”并删除它会产生相同的错误。

标签: python tensorflow keras


【解决方案1】:

您可以简单地将损失从sparse_categorical_crossentropy 更改为categorical_crossentropy

生成器中的“分类”模式将一次性编码标签,这不适合sparse_categorical_crossentropy

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-25
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 2018-09-30
    • 1970-01-01
    相关资源
    最近更新 更多