首页 文章

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

提问于
浏览
1

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

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

我正在处理224x224图像,3个通道,批量大小为24,并尝试将它们分为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')

1 回答

  • 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 ,用您自己的替换它们 .

相关问题