【问题标题】:How to define precision as loss Function in Keras?如何在 Keras 中将精度定义为损失函数?
【发布时间】:2018-10-06 01:45:47
【问题描述】:

众所周知,keras 中的 sparse_categorical_crossentropy 可以得到每个类别之间的平均损失函数。但是,如果我最关心的只是一个特定的类别呢?就像如果我想将基于这个类别的精度(=TP/(TP+FP))定义为损失函数,我该怎么写呢?谢谢!

我的代码是这样的:

from keras import backend as K
def my_loss(y_true,y_pred):
    y_true = K.cast(y_true,"float32")
    y_pred = K.cast(K.argmax(y_pred),"float32")
    nominator = K.sum(K.cast(K.equal(y_true,y_pred) & K.equal(y_true, 0),"float32"))
    denominator = K.sum(K.cast(K.equal(y_pred,0),"float32"))
    return -(nominator + K.epsilon()) / (denominator + K.epsilon())

错误是这样的:

argmax is not differentiable

【问题讨论】:

    标签: keras loss-function


    【解决方案1】:

    我不建议你使用精度作为损失函数。

    • 无法设置为 nn 的损失函数是不可微分的。
    • 您可以通过将所有实例预测为负类来最大化它,这是没有意义的。

    另一种解决方案是使用 F1 作为损失函数,然后手动调整概率截止以获得理想的精度水平,并且召回率不会太低。

    【讨论】:

      【解决方案2】:

      您可以将参数 class_weight 传递给 fit 方法,您可以在其中确定哪些类更重要。

      应该是字典:

      {
          0: 1, #class 0 has weight 1
          1: 0.5, #class 1 has half the importance of class 0
          2: 0.7, #....
          ...
      }
      

      自定义损失

      如果这不是您所需要的,您可以创建如下损失函数:

      import keras.backend as K
      
      def customLoss(yTrue,yPred):
      
          create operations with yTrue and yPred
              - yTrue = the true output data (equal to y_train in most examples)        
              - yPred = the model's calculated output
      
              - yTrue and yPred have exactly the same shape: (batch_size,output_dimensions,....) 
                   - according to the output shape of the last layer
                   - also according to the shape of y_train    
      
          all operations must be like +, -, *, / or operations from K (backend)
      
          return someResultingTensor
      

      【讨论】:

      • 谢谢,但答案可能不是我要找的答案。也许是错误的描述误导了你。所以我重新编辑了这个问题。你能给我一个新的答案吗?非常感谢!
      【解决方案3】:

      您不能使用 argmax,因为它不可微。这意味着如果无法区分损失函数,反向传播将不起作用。

      不要使用 argmax,而是执行 y_true * y_pred。

      【讨论】:

        猜你喜欢
        • 2018-04-03
        • 2019-01-23
        • 2019-11-10
        • 2020-11-26
        • 2020-12-19
        • 2017-12-18
        • 2020-03-27
        • 1970-01-01
        • 2021-02-24
        相关资源
        最近更新 更多