将 keras.applications.resnet50 转换为 Sequential 会出错

Converting keras.applications.resnet50 to a Sequential gives error

我想将预训练的 ResNet50 模型从 keras.application 转换为顺序模型,但它给出了 input_shape 错误。

Input 0 is incompatible with layer res2a_branch1: expected axis -1 of input shape to have value 64 but got shape (None, 25, 25, 256)

我读了这个 https://github.com/keras-team/keras/issues/9721 并且据我了解错误的原因是 skip_connections。

有没有办法将其转换为顺序模型,或者如何将我的自定义模型添加到此 ResNet 模型的末尾。

这是我试过的代码。

from keras.applications import ResNet50

height = 100 #dimensions of image
width = 100
channel = 3 #RGB

# Create pre-trained ResNet50 without top layer
model = ResNet50(include_top=False, weights="imagenet", input_shape=(height, width, channel))
# Get the ResNet50 layers up to res5c_branch2c
model = Model(input=model.input, output=model.get_layer('res5c_branch2c').output)

model.trainable = False
for layer in model.layers:
    layer.trainable = False

model = Sequential(model.layers)

我想把它加到最后。我可以从哪里开始?

model.add(Conv2D(32, (3,3), activation = 'relu', input_shape = inputShape))
model.add(MaxPooling2D(2,2))
model.add(BatchNormalization(axis = chanDim))
model.add(Dropout(0.2))

model.add(Conv2D(32, (3,3), activation = 'relu'))
model.add(MaxPooling2D(2,2))
model.add(BatchNormalization(axis = chanDim))
model.add(Dropout(0.2))

model.add(Conv2D(64, (3,3), activation = 'relu'))
model.add(MaxPooling2D(2,2))
model.add(BatchNormalization(axis = chanDim))
model.add(Dropout(0.2))

model.add(Flatten())

model.add(Dense(64, activation = 'relu'))
model.add(BatchNormalization(axis = chanDim))
model.add(Dropout(0.5))
model.add(Dense(classes, activation = 'softmax'))

使用 Keras 的 functionl API

先取ResNet50,

from keras.models import Model
from keras.applications import ResNet50

height = 100 #dimensions of image
width = 100
channel = 3 #RGB

# Create pre-trained ResNet50 without top layer
model_resnet = ResNet50(include_top=False, weights="imagenet", input_shape=(height, width, channel))

并如下添加模型模块,并将ResNet的输出用于下一层的输入

conv1 = Conv2D(32, (3,3), activation = 'relu')(model_resnet.output)
pool1 = MaxPooling2D(2,2)(conv1)
bn1 = BatchNormalization(axis=chanDim)(pool1)
drop1 = Dropout(0.2)(bn1)

以这种方式添加所有图层,最后例如,

flatten1 = Flatten()(drop1)
fc2 = Dense(classes, activation='softmax')(flatten1)

然后,使用 Model() 创建最终模型。

model = Model(inputs=model_resnet.input, outputs=fc2)