在Keras中,如何将精度定义为损失函数?

在Keras中,如何将精度定义为损失函数?,keras,loss-function,Keras,Loss Function,众所周知,keras中的稀疏类交叉熵可以得到各类之间的平均损失函数。但如果我最关心的只是某一类呢?比如,如果我想将基于该类别的精度(=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")

众所周知,keras中的稀疏类交叉熵可以得到各类之间的平均损失函数。但如果我最关心的只是某一类呢?比如,如果我想将基于该类别的精度(=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

您可以向fit方法传递一个参数
class\u weight
,确定哪些类更重要

它应该是一本字典:

{
    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

不能使用argmax,因为它不可微。这意味着,如果不能区分损失函数,backprop将不起作用


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

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

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

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

谢谢,但答案可能不是我想要的。也许是错误的描述误导了你。所以我重新编辑了这个问题。你能给我一个新的答案吗?谢谢!