简体   繁体   中英

Keras use part of pretrained models (ResNet 18)

I'm using pretraind ResNet18 from here I want to use part of the model from layer [4] to [-4]

I tried to create a new model using wanted layers like

res_net = ResNet18((224, 224, 3), weights='imagenet')

model = Model(res_net.layers[4].input, res_net.layers[-4].output)

but this error show

ValueError: Graph disconnected: cannot obtain value for tensor Tensor("data_5:0", shape=(None, 224, 224, 3), dtype=float32) at layer "bn_data". The following previous layers were accessed without issue: []

also try this

res_net = ResNet18((224, 224, 3), weights='imagenet', include_top=False)

x = Input(shape=(192, 640, 6))

conv1 = layers.Conv2D(64, kernel_size=7, strides=2, padding='same', input_shape=(192, 640, 6),name='conv1')(x)

l = res_net.layers[4](conv1) 
for i in range(5, len(res_net.layers[:-4])):
    l = res_net.layers[i](l)

model = Model(inputs=x,outputs=l)
model.summary()

but this error show

ValueError: A merge layer should be called on a list of inputs.

You probably wanna use

model = Model(res_net.layers[4].input, res_net.layers[0:-4].output)

Also worth noting is the fact that the above practice is discouraged. Judging by your code I guess you are trying to take the output from the 4th last layer of resnet18. To do this first define a resnet50 model as then create a new model whose inputs are tapped from the inputs of the resnet50 model and outputs are tapped from the 14th of resnet50:

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

base_model = ResNet50(weights='imagenet', include_top=True)
ResNet14 = Model(inputs = base_model.input,outputs = base_model.get_layer('conv2_block1_0_conv').output)

If you are not sure about the name of all the layers in resnet50 or any prebuilt models in Keras you can use:

for layer in base_model.layers:
     print(layer.name)

To get the name of the 14th layer you can use print(base_model.layers[13].name)

Happy Coding

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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