如何在Keras中创建自定义损失函数,每个样本都有所不同

问题描述 投票:1回答:1

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

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

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

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

问题是我无法得到索引(j)。

python keras loss
1个回答
0
投票

这可能没有进一步的相关性,但您可以使用输入层创建第二个网络。朝着那个输入层传递一个代表你的权重的数组。

现在包装你的模型:

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

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

def customloss(y_true,y_pred):
    return K.binary_crossentropy(y_true,y_pred) + weight_layer
m2.compile(optimizer='adam',loss=customloss,...)
© www.soinside.com 2019 - 2024. All rights reserved.