Keras替换输入层 [英] Keras replacing input layer
问题描述
我拥有的代码(我无法更改)使用带有my_input_tensor
的Resnet作为input_tensor.
The code that I have (that I can't change) uses the Resnet with my_input_tensor
as the input_tensor.
model1 = keras.applications.resnet50.ResNet50(input_tensor=my_input_tensor, weights='imagenet')
调查源代码,ResNet50函数使用my_input_tensor
创建一个新的keras输入层,然后创建模型的其余部分.这是我要用自己的模型复制的行为.我从h5文件加载模型.
Investigating the source code, ResNet50 function creates a new keras Input Layer with my_input_tensor
and then create the rest of the model. This is the behavior that I want to copy with my own model. I load my model from h5 file.
model2 = keras.models.load_model('my_model.h5')
由于该模型已经具有输入层,所以我想用用my_input_tensor
定义的新输入层替换它.
Since this model already has an Input Layer, I want to replace it with a new Input Layer defined with my_input_tensor
.
如何替换输入层?
推荐答案
使用以下方法保存模型时:
When you saved your model using:
old_model.save('my_model.h5')
它将保存以下内容:
- 模型的体系结构,允许创建模型.
- 模型的权重.
- 模型的训练配置(损失,优化器).
- 优化程序的状态,可以使培训从您之前离开的位置恢复.
因此,当您加载模型时:
So then, when you load the model:
res50_model = load_model('my_model.h5')
您应该找回相同的模型,您可以使用以下方法验证相同的模型:
you should get the same model back, you can verify the same using:
res50_model.summary()
res50_model.get_weights()
现在,您可以弹出输入层,并使用以下内容添加自己的内容:
Now you can, pop the input layer and add your own using:
res50_model.layers.pop(0)
res50_model.summary()
添加新的输入层:
newInput = Input(batch_shape=(0,299,299,3)) # let us say this new InputLayer
newOutputs = res50_model(newInput)
newModel = Model(newInput, newOutputs)
newModel.summary()
res50_model.summary()
这篇关于Keras替换输入层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!