【问题标题】:Custom loss function in Keras for weighting missclassified samplesKeras 中用于称重错误分类样本的自定义损失函数
【发布时间】:2019-04-23 00:45:56
【问题描述】:

假设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 的不同值。

我想知道:

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

【问题讨论】:

    标签: python keras classification regression loss-function


    【解决方案1】:

    我建议你使用这种类型的损失函数来处理不平衡数据集

    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来源

    【讨论】:

      猜你喜欢
      • 2021-12-15
      • 2019-03-10
      • 2017-12-20
      • 1970-01-01
      • 1970-01-01
      • 2020-06-09
      • 2020-12-19
      • 2017-12-18
      • 2020-03-27
      相关资源
      最近更新 更多