【问题标题】:accessing specific elements in custom loss function?访问自定义损失函数中的特定元素?
【发布时间】:2019-12-05 09:16:38
【问题描述】:

在为分类问题定义自定义损失函数时,有没有办法访问 y_true 和 y_pred 的特定元素?

用例:多标签分类问题,如果我预测第 5 类的误报即y_true[5] == 0y_pred[5] == 1,我想额外惩罚模型

我将损失定义为:

def loss(y_true, y_pred):
      wt = 10 if (y_true[5]==0 and y_pred[5]==1) else 1
      return wt * binary_crossentropy(y_true, y_pred)

我也试过检查K.gather(y_true, 5) == 0,但似乎不行。

我的批量大小是 > 1 (256) 并且我正在使用 fit_generator - 如果这有什么不同的话。谢谢!

【问题讨论】:

    标签: python machine-learning keras neural-network deep-learning


    【解决方案1】:

    有没有办法访问 y_true 和 y_pred 的特定元素?

    Keras 张量的索引与 numpy 数组的索引类似。唯一的区别是结果是一个 Keras 张量。因此,您应该随后使用 Keras 操作。


    损失函数的可能实现

    例如,以下是您的损失函数的实现方式:

    def loss(y_true, y_pred):
        a = K.equal(y_true[:, 5], 0)
        b = K.greater(y_pred[:, 5], 0.5)
        condition = K.cast(a, 'float') * K.cast(b, 'float')
        wt = 10 * condition + (1 - condition)
        return K.mean(wt[:, None] * K.binary_crossentropy(y_true, y_pred), axis=-1)
    

    注意:未经测试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-17
      • 2019-01-15
      • 2018-03-18
      • 2015-09-22
      • 1970-01-01
      • 2020-12-19
      • 2017-04-04
      相关资源
      最近更新 更多