具有动态全局变量的 Keras 自定义损失

Keras custom loss with dynamic global variable

所以,我正在尝试为我的 keras 模型编写自定义损失函数。损失函数需要一个全局变量,该变量在每个时期后都会发生变化以计算损失,但我无法获得动态损失。使用 tf.print() 它打印一个静态值.. 所以,任何人都可以指向一些 resource/solution 以便我可以在损失函数中使用一个全局变量,该变量在每个纪元后都会发生变化。谢谢。

我也有同样的疑问。我找到了多个可以解决上述问题的参考资料。但是,我仍在努力用自己的代码实现它。

方案一(推荐):使用model.add_loss添加自定义损失函数。对于参考,您可以查看这些来源:

解决方案二:子类化损失函数(对于您的情况可能不是一个好的解决方案)

How to custom losses by subclass tf.keras.losses.Loss class in Tensorflow2.x

  • 另一个子分类示例:
  • 请参阅此来源的以下注释:
    def loss_carrier(extra_param1, extra_param2):
        def loss(y_true, y_pred):
            #x = complicated math involving extra_param1, extraparam2, y_true, y_pred
            #remember to use tensor objects, so for example keras.sum, keras.square, keras.mean
            #also remember that if extra_param1, extra_maram2 are variable tensors instead of simple floats,
            #you need to have them defined as inputs=(main,extra_param1, extraparam2) in your keras.model instantiation.
            #and have them defind as keras.Input or tf.placeholder with the right shape.
            return x
        return loss

    model.compile(optimizer='adam', loss=loss_carrier