在定制损失函数中访问y_pred的一部分以计算损失

时间:2019-07-07 15:22:34

标签: python keras embedding

我想开发一个具有三个输入pos,anc,neg和三个输出pos_out,anc_out,neg_out的神经网络。在我在keras中定制的损失函数中计算损失时,我想在y_pred中访问pos_out,anc_out,neg_out。我可以整体访问y_pred。但是如何访问各个部分pos_out,anc_out和neg_out

我已将max函数应用于y_pred。它可以正确计算最大值。如果我在模型中仅传递一个输出作为Model(input = [pos,anc,neg],output = pos_out),那么它也可以正确计算最大值。但是,在自定义函数中分别访问pos_out,anc_out和neg_out的最大值时,它将无法正常工作。

def testmodel(input_shape):

    pos = Input(shape=(14,300))
    anc = Input(shape=(14,300))
    neg = Input(shape=(14,300))

    model = Sequential()
    model.add(Flatten(batch_input_shape=(1,14,300)))

    pos_out = model(pos)
    anc_out = model(anc)
    neg_out = model(neg)


    model = Model(input=[pos,anc,neg], output=[pos_out,anc_out,neg_out])

    return model

def customloss(y_true,y_pred):
  print((K.int_shape(y_pred)[1]))
  #loss = K.max((y_pred))
  loss = K.max[pos_out]
  return loss

2 个答案:

答案 0 :(得分:0)

您可以创建一个损失函数,该函数包含一个用于访问模型的闭包,从而可以访问目标以及模型层的输出。

class ExampleCustomLoss(object):
  """ The loss function can access model.inputs, model.targets and the outputs
  of specific layers. These are all tensors and will have the expected results
  for the batch.
  """
  def __init__(self, model):
    self.model = model

  def loss(self, y_true, y_pred, **kwargs):
    ...
    return loss


model = Model(..., ...)
loss_calculator = ExampleCustomLoss(model)
model.compile('adam', loss_calculator.loss)


但是,进行逆运算可能会更简单。即只有一个模型输出

out = Concatenate(axis=1)([pos_out, anc_out, neg_out])

然后在损失函数切片y_true和y_pred中。

从变量名称来看,好像您正在尝试使用三元组损失。您可能会发现其他问题很有用: How to deal with triplet loss when at time of input i have only two files i.e. at time of testing

答案 1 :(得分:0)

您的损失函数有2个参数,即模型输出和true标签,模型输出将具有定义网络时定义的形状。损失函数需要在训练时输出模型输出与标签真实值之间的单个差值。

还请在模型中添加一些可训练的图层,因为自定义损失功能否则将毫无用处。