在重新训练预训练模型时,得到:ValueError: Input 0 is incompatible with layer flatten_1: expected min_ndim=3, found ndim=2

数据挖掘 神经网络 深度学习 喀拉斯
2022-03-09 22:57:27

我的模型总结是:

Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 62, 62, 32)        896       
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 31, 31, 32)        0         
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 29, 29, 32)        9248      
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 14, 14, 32)        0         
_________________________________________________________________
flatten_1 (Flatten)          (None, 6272)              0         
_________________________________________________________________
dense_1 (Dense)              (None, 128)               802944    
_________________________________________________________________
dense_2 (Dense)              (None, 4)                 516       

当我使用以下函数重新训练这个模型时:

在此处输入图像描述

我面临这个错误:

ValueError: Input 0 is incompatible with layer flatten_1: expected min_ndim=3, found ndim=2
1个回答

此错误的原因是您试图展平已经平坦的图层。您的模型的输出是(batch_size, 4),不能进一步展平。要简单地修复错误,请从代码中删除 flatten 层。

但是,在微调预训练模型时,您应该先删除该模型的顶层,然后再添加您自己的模型。原因是这些层是针对与您不同的任务进行分类的训练。

如果我是你,我会放弃你的预训练模型的最后两层:

# code same as before ...

x = model.layers[-3].output  # Flatten layer output

# don't add flatten again

for fc in fc_layers:
    x = Dense(fc, activation='relu')(x)
    x = Dropout(dropout)(x)

predictions = Dense(num_classes, activation='softmax')(x)

finetune_model = Model(inputs=model.input, outputs=predictions)