【发布时间】: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})
但是在我有两个输出的情况下如何扩展它,其中损失和损失权重在字典中定义以及自定义损失函数?
换句话说,在losses 和loss_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