[英]Keras: How to load a model having two outputs and a custom loss function?
I have trained a Keras (with Tensorflow backend) model which has two outputs with a custom loss function.我已经训练了一个 Keras(带有 Tensorflow 后端)模型,它有两个带有自定义损失函数的输出。 I need help in loading the model from disk using the custom_objects
argument.我需要帮助使用custom_objects
参数从磁盘加载模型。
When compiling the model I have used the loss and loss_weights argument as follows:编译模型时,我使用了 loss 和 loss_weights 参数,如下所示:
losses = {
'output_layer_1':custom_loss_fn,
'output_layer_2':custom_loss_fn
}
loss_weights = {
'output_layer_1': 1.0,
'output_layer_2': 1.0
}
model.compile(loss=losses, loss_weights=loss_weights, optimizer=opt)
The model is training without any problems.该模型正在训练,没有任何问题。 I save the model as follows:我将模型保存如下:
model.save(model_path)
The reason I haven't defined "custom_loss_fn" here is because custom_loss_fn is defined inside another custom Keras layer.我在这里没有定义“custom_loss_fn”的原因是因为 custom_loss_fn 是在另一个自定义 Keras 层中定义的。
My question is how do I load the model which is persisted to disk during inference.我的问题是如何加载在推理过程中持久保存到磁盘的模型。 If it was a single ouput model I would load the model using custom_objects as described in this stackoverflow question: Loading model with custom loss + keras如果它是单个输出模型,我将使用 custom_objects 加载模型,如此 stackoverflow 问题中所述: Loading model with custom loss + keras
model = keras.models.load_model(model_path, custom_objects={'custom_loss_fn':custom_loss_fn})
But how to extend this in my case where I have two outputs with the losses and loss weights defined in a dictionary along with a custom loss function?但是在我有两个输出的情况下,如何扩展它,其中的损失和损失权重在字典中定义以及自定义损失函数?
In other words, how should custom_objects
be populated in this case where losses
and loss_weights
are defined as dictionaries?换句话说,应该如何custom_objects
可以在此情况下填充losses
和loss_weights
定义词典?
I'm using Keras v2.1.6 with Tensorflow backend v1.8.0.我将 Keras v2.1.6 与 Tensorflow 后端 v1.8.0 一起使用。
If you can recompile the model on the loading side, the easiest way is to save just the weights: model.save_weights()
.如果您可以在加载端重新编译模型,最简单的方法是只保存权重: model.save_weights()
。 If you want to use save_model and have custom Keras layers, be sure they implement the get_config
method (see this reference).如果您想使用 save_model 并拥有自定义 Keras 层,请确保它们实现了get_config
方法(请参阅此参考资料)。 As for the ops without gradient, I have seen this while mixing tensorflow and Keras without using properly the keras.backend
functions, but I can't help any more without the model code itself.至于没有梯度的操作,我在没有正确使用keras.backend
函数的情况下混合 tensorflow 和 Keras 时看到了这一点,但如果没有模型代码本身,我就keras.backend
了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.