简体   繁体   English

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

[英]How can I create custom loss function in Keras which is different for each sample

I have eg 100 samples (100 outputs). 我有100个样本(100个输出)。 I would like to write custom loss function with a "weight" for each sample: 我想为每个样本编写带有“权重”的自定义丢失函数:

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

Where f is a custom numeric function (eg j**2 ). 其中f是自定义数字函数(例如j**2 )。 How can I do this Now I am only able to create "universal" loss function (without "weights"): 我怎么能这样做现在我只能创建“通用”损失功能(没有“权重”):

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

The problem is I cannot get the index (j). 问题是我无法得到索引(j)。

This might not be further relevant, but you can create a second network with an Input Layer. 这可能没有进一步的相关性,但您可以使用输入层创建第二个网络。 Towards that Input Layer you pass an Array that represents your weights. 朝着那个输入层传递一个代表你的权重的数组。

Now wrap your model: 现在包装你的模型:

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

Since the output of a loss functions is also a Tensor you can add the weight_layer to your loss. 由于损失函数的输出也是Tensor,因此您可以将weight_layer添加到损失中。 eg: 例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 keras 中创建自定义损失函数? (自定义加权二元交叉熵) - How can I create a custom loss function in keras ? (Custom Weighted Binary Cross Entropy) 如何编写此自定义损失 function 以便为每个样本产生损失? - How to write this custom loss function so it produces a loss for each sample? 如何访问生成器提供的 Keras 自定义损失函数中的样本权重? - How to access sample weights in a Keras custom loss function supplied by a generator? 如何在自定义Keras / Tensorflow Loss函数中对值进行排序? - How can I sort the values in a custom Keras / Tensorflow Loss Function? 如何在 Keras 中实现此自定义损失 function? - How can I implement this custom loss function in Keras? 带有样本权重的 Keras 中的自定义损失函数 - Custom Loss Function in Keras with Sample Weights 如何制作在keras中使用模型的自定义损失函数 - how to make a custom loss function which use model in keras 如何创建在Keras中随时间变化的损失函数 - How to create a loss function which changes over epoch in Keras 自定义损失函数中的 Keras 实时样本权重计算 - Keras on-the-fly sample weights calculation in a custom loss function 如何在 Keras 中使用自定义损失函数加快模型的训练速度? - How can I speed the training up for a model with a custom loss function in Keras?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM