【问题标题】:Keras: How to load a model having two outputs and a custom loss function?Keras:如何加载具有两个输出和自定义损失函数的模型?
【发布时间】:2019-07-06 22:35:32
【问题描述】:

我已经训练了一个 Keras(带有 Tensorflow 后端)模型,该模型具有两个带有自定义损失函数的输出。在使用 custom_objects 参数从磁盘加载模型时,我需要帮助。

在编译模型时,我使用了 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)

模型正在训练,没有任何问题。我保存模型如下:

model.save(model_path)

我没有在这里定义“custom_loss_fn”的原因是因为 custom_loss_fn 是在另一个自定义 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})

但是在我有两个输出的情况下如何扩展它,其中损失和损失权重在字典中定义以及自定义损失函数?

换句话说,在lossesloss_weights 被定义为字典的情况下,应该如何填充custom_objects

我正在使用带有 Tensorflow 后端 v1.8.0 的 Keras v2.1.6。

【问题讨论】:

  • 你试过custom_objects={ 'output_layer_1':custom_loss_fn, 'output_layer_2':custom_loss_fn }吗?
  • @Karl 我刚刚尝试了您的建议。但是,我得到了这个错误。 ValueError: An operation has `None` for gradient. Please make sure that all of your ops have a gradient defined (i.e. are differentiable). Common ops without gradient: K.argmax, K.round, K.eval。请注意,在具有单个输出和相同 custom_loss_fn 的另一个模型中,我没有收到此错误。

标签: python tensorflow keras keras-layer


【解决方案1】:

如果您可以在加载端重新编译模型,最简单的方法是只保存权重:model.save_weights()。如果您想使用 save_model 并拥有自定义 Keras 层,请确保它们实现了 get_config 方法(请参阅 this 参考)。 至于没有渐变的操作,我在没有正确使用 keras.backend 函数的情况下混合 tensorflow 和 Keras 时看到了这一点,但是如果没有模型代码本身,我就无能为力了。

【讨论】:

  • 我会接受这个答案。我打算重新编译模型并加载保存的权重。 get_config 的链接也很有帮助。谢谢。
猜你喜欢
  • 1970-01-01
  • 2020-04-30
  • 1970-01-01
  • 2020-06-21
  • 1970-01-01
  • 2020-08-01
  • 2020-05-14
  • 1970-01-01
  • 2020-06-15
相关资源
最近更新 更多