Keras 替换输入层 [英] Keras replacing input layer
问题描述
我拥有的代码(我无法更改)使用带有 my_input_tensor
作为 input_tensor 的 Resnet.
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屋!