【发布时间】:2021-07-31 16:08:04
【问题描述】:
之前在另一篇文章 (Keras multioutput custom loss with intermediate layers output) 中,我讨论了我遇到的问题。最后,这个问题是这样解决的:
def MyLoss(true1, true2, out1, out2, out3):
loss1 = tf.keras.losses.someloss1(out1, true1)
loss2 = tf.keras.losses.someloss2(out2, true2)
loss3 = tf.keras.losses.someloss3(out2, out3)
loss = loss1 + loss2 + loss3
return loss
input1 = Input(shape=input1_shape)
input2 = Input(shape=input2_shape)
# do not take into account the notation, only the idea
output1 = Submodel1()([input1,input2])
output2 = Submodel2()(output1)
output3 = Sumbodel3()(output1)
true1 = Input(shape=true1shape)
true2 = Input(shape=true2shape)
model = Model([input1,input2,true1,true2], [output1,output2,output3])
model.add_loss(MyLoss(true1, true2, output1, output2, output3))
model.compile(optimizer='adam', loss=None)
model.fit(x=[input1 ,input2 ,true1,true2], y=None, epochs=n_epochs)
在那个问题中,我使用的所有损失都是 keras 损失(即tf.keras.losss.someloss),但现在我想添加更多损失,我想将自定义损失与 keras 损失结合起来。也就是说,现在我有了这个方案:
为了添加这两个损失,即 SSIM 损失,我尝试了这个:
def SSIMLoss(y_true, y_pred):
return 1-tf.reduce_mean(tf.image.ssim(y_true, y_pred, 1.0))
def MyLoss(true1, true2, out1, out2, out3):
loss1 = tf.keras.losses.someloss1(out1, true1)
customloss1 = SSIMLoss(out1,true1)
loss2 = tf.keras.losses.someloss2(out2, true2)
loss3 = tf.keras.losses.someloss3(out2, out3)
customloss2 = SSIMLoss(out2,out3)
loss = loss1 + loss2 + loss3 + customloss1 + customloss2
return loss
但我收到此错误:
OperatorNotAllowedInGraphError: using a `tf.Tensor` as a Python `bool` is not allowed in Graph execution. Use Eager execution or decorate this function with @tf.function.
我尝试使用@tf.function 装饰函数,但出现此错误:
_SymbolicException: Inputs to eager execution function cannot be Keras symbolic tensors, but found [<tf.Tensor 'input_43:0' shape=(None, 128, 128, 1) dtype=float32>, <tf.Tensor 'conv2d_109/Sigmoid:0' shape=(None, 128, 128, 1) dtype=float32>]
我发现这个 (https://github.com/tensorflow/tensorflow/issues/32127) 将 keras 损失与 add_loss 结合起来,也许这是问题所在,但我不知道如何解决。
【问题讨论】:
-
您能否就给定的答案提供一些反馈?
-
嗨@M.Innat,是的,对不起。这些天我有点忙,我无法检查您的解决方案。我现在已经开始了,它似乎正在工作,尽管我遇到了与此无关的其他错误。非常感谢!
标签: python tensorflow machine-learning keras deep-learning