【发布时间】:2021-08-11 15:10:01
【问题描述】:
所以,我正在尝试为我的 keras 模型编写自定义损失函数。损失函数需要一个全局变量,该变量在每个 epoch 后都会发生变化来计算损失,但我无法获得动态损失。使用 tf.print() 它打印一个静态值。所以,任何人都可以指向一些资源/解决方案,以便我可以在损失函数中使用一个全局变量,该变量在每个时期都会发生变化。谢谢。
【问题讨论】:
标签: keras tf.keras loss-function
所以,我正在尝试为我的 keras 模型编写自定义损失函数。损失函数需要一个全局变量,该变量在每个 epoch 后都会发生变化来计算损失,但我无法获得动态损失。使用 tf.print() 它打印一个静态值。所以,任何人都可以指向一些资源/解决方案,以便我可以在损失函数中使用一个全局变量,该变量在每个时期都会发生变化。谢谢。
【问题讨论】:
标签: keras tf.keras loss-function
我也有同样的问题。我找到了多个可以解决上述问题的参考资料。但是,我仍在努力用自己的代码实现它。
方案一(推荐):使用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
【讨论】: