【问题标题】:Keras custom loss with dynamic global variable具有动态全局变量的 Keras 自定义损失
【发布时间】:2021-08-11 15:10:01
【问题描述】:

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

【问题讨论】:

    标签: keras tf.keras loss-function


    【解决方案1】:

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

    方案一(推荐):使用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   
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-23
      • 1970-01-01
      • 2018-06-25
      • 2018-12-30
      • 2021-03-16
      • 1970-01-01
      • 2014-05-12
      相关资源
      最近更新 更多