【发布时间】:2021-03-08 08:39:20
【问题描述】:
我在 keras 中有一个模型,它接受两个输入并返回 3 个输出,我想计算自定义损失。我遇到的问题是我不知道如何在损失中使用中间层的输出。到目前为止,该模型由两个子模型(图中的 submodel1 和 submodel2)组成,最终损失由 loss1 和 loss2 之和组成。这很容易,因为 loss1 将 output1 与数据生成器的 label1 进行比较,将 output2 与数据生成器的 label2 进行比较。
当我在模型中包含 submodel3 时问题就来了,因为 loss3 将 output1 与 output3 进行比较,输出 1 是模型的一层的输出,而不是数据生成器的 label3 的输出。我试过这种方式:
input1 = Input(shape=input1_shape)
input2 = Input(shape=input2_shape)
output1 = submodel1()([input1,input2]) #do not pay attention to the code notation, as it is a code to explain the problem.
output2 = submodel2()(output1)
output3 = submodel3()(output1)
@tf.function
def MyLoss(y_true, y_pred):
out1, out2, out3 = y_pred
inp1, inp2 = y_true
loss1 = tf.keras.losses.some_loss1(out1,inp1)
loss2 = tf.keras.losses.some_loss2(out2, inp2)
loss3 = tf.keras.losses.some_loss3(out2,out3)
loss = loss1 + loss2 + loss3
return loss
model = Model([input1,input2],[output1,output2,output3])
model.compile(optimizer='adam',loss = MyLoss)
但我收到此错误:
OperatorNotAllowedInGraphError: iterating over `tf.Tensor` is not allowed: AutoGraph did convert this function. This might indicate you are trying to use an unsupported feature.
我正在使用 TensorFlow 2.3.0-rc0 版本。
【问题讨论】:
标签: tensorflow keras deep-learning loss-function