【问题标题】:MobileNet ValueError: Error when checking target: expected dense_1 to have 4 dimensions, but got array with shape (24, 2)MobileNet ValueError:检查目标时出错:预期dense_1 有4 维,但得到了形状为(24, 2) 的数组
【发布时间】:2018-04-11 06:20:07
【问题描述】:

我正在尝试使用 Keras 应用程序实现多个网络。在这里我附上了一段代码,这段代码适用于 ResNet50 和 VGG16,但是当涉及到 MobileNet 时,它会产生错误:

ValueError: 检查目标时出错:预期 dense_1 有 4 个维度,但得到的数组形状为 (24, 2)

我正在处理具有 3 个通道和 24 批量大小的 224x224 图像,并尝试将它们分类为 2 个类,因此错误中提到的数字 24 是批量大小,但我不确定数字 2,可能是班数。

顺便说一句,有没有人知道我为什么会收到keras.applications.mobilenet 的此错误?

# basic_model = ResNet50()
# basic_model = VGG16()
basic_model = MobileNet()
classes = list(iter(train_generator.class_indices))
basic_model.layers.pop()
for layer in basic_model.layers[:25]:
    layer.trainable = False
last = basic_model.layers[-1].output
temp = Dense(len(classes), activation="softmax")(last)

fineTuned_model = Model(basic_model.input, temp)
fineTuned_model.classes = classes
fineTuned_model.compile(optimizer=Adam(lr=0.0001), loss='categorical_crossentropy', metrics=['accuracy'])
fineTuned_model.fit_generator(
        train_generator,
        steps_per_epoch=3764 // batch_size,
        epochs=100,
        validation_data=validation_generator,
        validation_steps=900 // batch_size)
fineTuned_model.save('mobile_model.h5')

【问题讨论】:

    标签: python tensorflow deep-learning keras


    【解决方案1】:

    从源代码中,我们可以看到您正在弹出一个Reshape() 层。正是将卷积的输出 (4D) 转换为类张量 (2D) 的那个。

    Source code:

    if include_top:
        if K.image_data_format() == 'channels_first':
            shape = (int(1024 * alpha), 1, 1)
        else:
            shape = (1, 1, int(1024 * alpha))
    
        x = GlobalAveragePooling2D()(x)
        x = Reshape(shape, name='reshape_1')(x)
        x = Dropout(dropout, name='dropout')(x)
        x = Conv2D(classes, (1, 1),
                   padding='same', name='conv_preds')(x)
        x = Activation('softmax', name='act_softmax')(x)
        x = Reshape((classes,), name='reshape_2')(x)
    

    但所有 keras 卷积模型都意味着以不同的方式使用。如果您想要自己的类数,您应该使用include_top=False 创建这些模型。这样,模型的最后一部分(类部分)将根本不存在,您只需添加自己的层:

    basic_model = MobileNet(include_top=False)
    for layer in basic_model.layers:
        layers.trainable=False
    
    furtherOutputs = YourOwnLayers()(basic_model.outputs)
    

    您可能应该尝试复制 keras 代码中显示的最后一部分,将 classes 更改为您自己的类数。或者尝试从完整模型中弹出 3 层,ReshapeActivationConv2D,用您自己的替换它们。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-07
    • 2019-01-16
    • 2019-04-17
    • 1970-01-01
    • 2019-11-13
    • 2019-03-02
    相关资源
    最近更新 更多