问题描述
我想将预先训练的ResNet50模型从keras.application转换为顺序模型,但是会出现input_shape错误.
I want to convert pretrained ResNet50 model from keras.application to a Sequential model but it gives input_shape error.
我阅读了此 https://github.com/keras-team/keras/Issues/9721 ,据我了解,错误的原因是skip_connections.
I read this https://github.com/keras-team/keras/issues/9721 and as I understand the reason of error is skip_connections.
是否可以将其转换为顺序模型,或者如何将自定义模型添加到此ResNet模型的末尾.
Is there a way to convert it to a Sequential or how can I add my custom model to end of this ResNet Model.
这是我尝试过的代码.
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)
我想将此添加到它的末尾.我可以从哪里开始?
I want to add this to end of it. Where can I start?
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'))
推荐答案
使用功能API 凯拉斯.
首先服用ResNet50,
First take 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的输出作为下一层的输入
And add module of your model as follows, and use output of ResNet to input of the next layer
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)
以这种方式在您的所有图层中添加,最后,例如,
Add this way all of your layer and at last for example,
flatten1 = Flatten()(drop1)
fc2 = Dense(classes, activation='softmax')(flatten1)
然后,使用Model()
创建最终模型.
And, use Model()
to create the final model.
model = Model(inputs=model_resnet.input, outputs=fc2)
这篇关于将keras.applications.resnet50转换为Sequential会产生错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!