keras - 将 keras.applications.resnet50 转换为 Sequential 会出错
问题描述
我想将预训练的 ResNet50 模型从 keras.application 转换为 Sequential 模型,但它给出了 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'))
解决方案
使用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)
推荐阅读
- c++ - C++ Dll 库在第二次清除后在 vector.push_back 上崩溃
- kotlin - 如何在不需要时启动可以“关闭”的多个流?
- javascript - 将过滤器连接到多个图表 asp.net core mvc
- javascript - 使用startsWith()定义元素中的值范围 - jQuery
- node.js - 如何一次更新 Cloud Firebase 中某个字段的每个文档?
- android - Flutter: Json File not loading when running on connected device or built to apk
- java - How can I use a library from GitHub in android studio?
- php - 试图获取非对象的属性 'id' {"exception":"[object]
- java - 调用端点时如何在 MongoDB 中填充表?- MongoDb,SpringBoot
- html - VS 代码自动完成