简体   繁体   English

从 ResNet50 网络中删除最后 n 层

[英]Remove n last layers from ResNet50 network

I have the following network that will be used for binary classification on medical image data.我有以下网络,将用于医学图像数据的二进制分类。 However, I would like to use only the 80 first layers of this model as I currently don't have a lot of data and my model is overfitting.但是,我只想使用这个 model 的 80 个第一层,因为我目前没有很多数据,而且我的 model 过拟合。 I would like to delete all layers from block 4 or 5, and only keep blocks 1, 2 and 3. I have tried using layer.pop() but it does not work.我想从块 4 或 5 中删除所有层,只保留块 1、2 和 3。我尝试使用 layer.pop() 但它不起作用。

from keras.applications.resnet50 import ResNet50

resnet = ResNet50(include_top=False, weights='imagenet', input_shape=(im_size,im_size,3))

headModel = AveragePooling2D(pool_size=(7, 7))(resnet.output)
headModel = Flatten(name="flatten")(headModel)
headModel = Dense(256, activation="relu")(headModel)
headModel = Dropout(0.5)(headModel)
headModel = Dense(1, activation="sigmoid")(headModel)

Solution 1: You could use model.summary() to quickly check the names of the layers (80th).解决方案 1:您可以使用model.summary()快速检查层的名称(第 80 层)。

layer_name = 'name_of_the_80th_layer'
intermediate_model = Model(inputs=resnet.input,
                           outputs=resnet.get_layer(layer_name).output)
final_model = AveragePooling2D(pool_size=(7, 7))(intermediate_model.output)
final_model = Flatten(name="flatten")(final_model)
final_model = Dense(256, activation="relu")(final_model)
final_model = Dropout(0.5)(final_model)
final_model = Dense(1, activation="sigmoid")(final_model)

Solution 2:解决方案2:

You could directly get it like:你可以直接得到它:

intermediate_model = Model(inputs=resnet.input,
                           outputs=resnet.layers[80].output)
...
  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM