Keras中的自定义损失函数,用于对未分类样本进行加权

时间:2018-11-20 14:32:36

标签: python keras classification regression loss-function

假设y_truey_pred在[-1,1]中。我想要一个加权均方误差损失函数,其中对y_true中为正值和y_pred中为负值或反之亦然的样本的损失由exp(alpha)加权。这是我的代码:

import keras.backend as K
alpha = 1.0
def custom_loss(y_true, y_pred):
     se = K.square(y_pred-y_true)
     true_label = K.less_equal(y_true,0.0)
     pred_label = K.less_equal(y_pred,0.0)
     return K.mean(se * K.exp(alpha*K.cast(K.not_equal(true_label,pred_label), tf.float32)))

这是此损失函数的图。 y_true的不同曲线表示不同的值。 enter image description here

我想知道:

  • 这是否是有效的损失函数,因为它不能在0中微分?
  • 我的代码正确吗?

1 个答案:

答案 0 :(得分:0)

我建议您使用这种损失函数来处理不平衡数据集

def focal_loss(y_true, y_pred):
   gamma = 2.0, alpha = 0.25
   pt_1 = tf.where(tf.equal(y_true, 1), y_pred, tf.ones_like(y_pred))
   pt_0 = tf.where(tf.equal(y_true, 0), y_pred, tf.zeros_like(y_pred))
   return -K.sum(alpha * K.pow(1. - pt_1, gamma) * K.log(pt_1))-K.sum((1-alpha) * K.pow(pt_0, gamma) * K.log(1. - pt_0))

来自this来源

相关问题