我想将预先训练的ResNet50模型从keras.application转换为顺序模型,但是会出现input_shape错误。
输入0与图层res2a_branch1不兼容:输入形状的预期轴-1的值为64,但形状为(无,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'))
答案 0 :(得分:1)
使用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)