Keras:如何加载具有两个输出和自定义损失函数的模型?
Keras: How to load a model having two outputs and a custom loss function?
我已经训练了一个 Keras(带有 Tensorflow 后端)模型,它有两个带有自定义损失函数的输出。我需要帮助使用 custom_objects
参数从磁盘加载模型。
编译模型时我使用了损失和 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)
模型正在训练,没有任何问题。我保存模型如下:
model.save(model_path)
我没有在这里定义 "custom_loss_fn" 的原因是因为 custom_loss_fn 是在另一个自定义 Keras 层中定义的。
我的问题是如何加载推理期间持久保存到磁盘的模型。如果它是一个单一的输出模型,我会使用 custom_objects 加载模型,如这个 Whosebug 问题中所述:
model = keras.models.load_model(model_path, custom_objects={'custom_loss_fn':custom_loss_fn})
但是,如果我有两个输出,其中损失和损失权重在字典中定义,还有一个自定义损失函数,那么如何扩展它呢?
换句话说,在losses
和loss_weights
被定义为字典的情况下,custom_objects
应该如何填充?
我正在使用 Keras v2.1.6 和 Tensorflow 后端 v1.8.0。
如果您可以在加载端重新编译模型,最简单的方法是只保存权重:model.save_weights()
。如果您想使用 save_model 并拥有自定义 Keras 层,请确保它们实现了 get_config
方法(请参阅 this 参考)。
至于没有梯度的操作,我在混合使用 tensorflow 和 Keras 时看到了这一点,但没有正确使用 keras.backend
函数,但如果没有模型代码本身,我将无能为力。
我已经训练了一个 Keras(带有 Tensorflow 后端)模型,它有两个带有自定义损失函数的输出。我需要帮助使用 custom_objects
参数从磁盘加载模型。
编译模型时我使用了损失和 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)
模型正在训练,没有任何问题。我保存模型如下:
model.save(model_path)
我没有在这里定义 "custom_loss_fn" 的原因是因为 custom_loss_fn 是在另一个自定义 Keras 层中定义的。
我的问题是如何加载推理期间持久保存到磁盘的模型。如果它是一个单一的输出模型,我会使用 custom_objects 加载模型,如这个 Whosebug 问题中所述:
model = keras.models.load_model(model_path, custom_objects={'custom_loss_fn':custom_loss_fn})
但是,如果我有两个输出,其中损失和损失权重在字典中定义,还有一个自定义损失函数,那么如何扩展它呢?
换句话说,在losses
和loss_weights
被定义为字典的情况下,custom_objects
应该如何填充?
我正在使用 Keras v2.1.6 和 Tensorflow 后端 v1.8.0。
如果您可以在加载端重新编译模型,最简单的方法是只保存权重:model.save_weights()
。如果您想使用 save_model 并拥有自定义 Keras 层,请确保它们实现了 get_config
方法(请参阅 this 参考)。
至于没有梯度的操作,我在混合使用 tensorflow 和 Keras 时看到了这一点,但没有正确使用 keras.backend
函数,但如果没有模型代码本身,我将无能为力。