[英]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]我从这里使用预训练的 ResNet18 我想使用从层 [4] 到 [-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". ValueError:图形断开连接:无法在层“bn_data”处获取张量 Tensor("data_5:0", shape=(None, 224, 224, 3), dtype=float32) 的值。 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. ValueError:应在输入列表上调用合并层。
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.从你的代码来看,我猜你正试图从 resnet18 的最后 4 层获取输出。 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:要做到这一点首先定义一个resnet50模型,然后创建,其输入从resnet50模型的输入抽头和输出从resnet50 14日被挖掘的新模式:
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:如果您不确定 resnet50 中所有层的名称或 Keras 中的任何预建模型,您可以使用:
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)
要获取第 14 层的名称,您可以使用print(base_model.layers[13].name)
Happy Coding快乐编码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.