【问题标题】:Accessing part of y_pred in customized loss function for calculating loss访问自定义损失函数中 y_pred 的一部分以计算损失
【发布时间】:2019-11-17 07:03:42
【问题描述】:

我想开发一个具有三个输入 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

【问题讨论】:

  • 您的模型中没有任何可训练的层...

标签: python keras embedding


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    另外请为您的模型添加一些可训练的层,否则您的自定义损失函数将毫无用处。

    【讨论】:

      猜你喜欢
      • 2018-06-10
      • 2020-12-05
      • 2016-12-05
      • 2020-09-27
      • 2020-10-12
      • 2018-04-02
      • 2019-12-05
      • 1970-01-01
      • 2020-09-21
      相关资源
      最近更新 更多