【问题标题】:How can I create custom loss function in Keras which is different for each sample如何在 Keras 中创建每个样本都不同的自定义损失函数
【发布时间】:2016-11-16 13:01:46
【问题描述】:

我有例如100 个样本(100 个输出)。我想为每个样本编写带有“权重”的自定义损失函数:

(target[j] - prediction[j])**2 + f(j),

其中 f 是自定义数值函数(例如 j**2)。我怎样才能做到这一点 现在我只能创建“通用”损失函数(没有“权重”):

def customloss(target,prediction):
   return (target - prediction)**2

问题是我无法获取索引 (j)。

【问题讨论】:

  • 为什么不添加一个额外的参数weight?每个样本的权重向量。
  • 问题是 AFAIK 权重只能乘以结果,所以我会得到这样的结果: (target[j] - prediction[j])**2 * f(j) 我想添加“权重”而不是乘以它们

标签: python keras loss


【解决方案1】:

这可能不再相关,但您可以使用输入层创建第二个网络。向那个输入层传递一个代表权重的数组。

现在包装你的模型:

weight_layer = Input(shape=(None,dim))
m2 = Model(input=[m1.inputs,weight_layer],output=m1.outputs)

由于损失函数的输出也是张量,因此您可以将 weight_layer 添加到损失中。 例如:

def customloss(y_true,y_pred):
    return K.binary_crossentropy(y_true,y_pred) + weight_layer
m2.compile(optimizer='adam',loss=customloss,...)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-20
    • 1970-01-01
    • 2019-01-18
    • 2021-01-03
    • 2021-12-15
    • 2018-09-08
    • 2021-02-22
    • 2020-12-19
    相关资源
    最近更新 更多