Python 不同的错误分类权重不同

Python 不同的错误分类权重不同,python,tensorflow,keras,Python,Tensorflow,Keras,我希望我的模型在训练时通过创建自定义损失函数来增加误报预测的损失。 model.fit()中的class_weight参数不适用于此问题。类的权重已经设置为{0:1,1:23},因为我已经扭曲了训练数据,其中非真标签的数量是真标签的23倍 我在使用keras后端时没有太多经验。我主要使用功能模型 我想创建的是: def weighted_binary_crossentropy(y_true, y_pred): #where y_true == 0 and y_pred == 1:

我希望我的模型在训练时通过创建自定义损失函数来增加误报预测的损失。
model.fit()中的class_weight参数不适用于此问题。类的权重已经设置为{0:1,1:23},因为我已经扭曲了训练数据,其中非真标签的数量是真标签的23倍

我在使用keras后端时没有太多经验。我主要使用功能模型

我想创建的是:

def weighted_binary_crossentropy(y_true, y_pred):
    #where y_true == 0 and y_pred == 1:
    #   weight this loss and make it 50 times larger
    #return loss
我可以用张量做一些简单的事情,比如得到均方误差,但我不知道如何做逻辑的事情。
我尝试了一些不起作用且感觉完全错误的黑客解决方案:

def weighted_binary_crossentropy(y_true, y_pred):
    false_positive_weight = 50        
    thresh = 0.5
    y_pred_true = K.greater_equal(thresh,y_pred)
    y_not_true = K.less_equal(thresh,y_true)
    false_positive_tensor = K.equal(y_pred_true,y_not_true)

    loss_weights = K.ones_like(y_pred) + false_positive_weight*false_positive_tensor

    return K.binary_crossentropy(y_true, y_pred)*loss_weights
我使用Python3,Keras2和tensorflow作为后端


提前谢谢

我想你就快到了

from keras.losses import binary_crossentropy

def weighted_binary_crossentropy(y_true, y_pred):
    false_positive_weight = 50        
    thresh = 0.5
    y_pred_true = K.greater_equal(thresh,y_pred)
    y_not_true = K.less_equal(thresh,y_true)
    false_positive_tensor = K.equal(y_pred_true,y_not_true)


    #changing from here

    #first let's transform the bool tensor in numbers - maybe you need float64 depending on your configuration
    false_positive_tensor = K.cast(false_positive_tensor,'float32') 

    #and let's create it's complement (the non false positives)
    complement = 1 - false_positive_tensor

    #now we're going to separate two groups
    falsePosGroupTrue = y_true * false_positive_tensor
    falsePosGroupPred = y_pred * false_positive_tensor

    nonFalseGroupTrue = y_true * complement
    nonFalseGroupPred = y_pred * complement


    #let's calculate one crossentropy loss for each group
    #(directly from the keras loss functions imported above)
    falsePosLoss = binary_crossentropy(falsePosGroupTrue,falsePosGroupPred)
    nonFalseLoss = binary_crossentropy(nonFalseGroupTrue,nonFalseGroupPred)

    #return them weighted:
    return (false_positive_weight*falsePosLoss) + nonFalseLoss

请注意,这里的权重应用于预测值,而不是损失,因此,如果您希望它出现在损失值中,可能会有一个更正。嘿!谢谢你的快速回答。将权重应用于预测的问题是,K.binary_交叉熵将y_pred的值剪辑为EPSILON,1-EPSILON,因此删除了此处所做的调整。相反,我想将K.binary_crossentropy返回的损失值乘以一定的权重,K.binary_crossentropy对应于一个假阳性。知道怎么做吗?
weighted\u falses=(false\u positive\u weight-1)*false\u positive\u tensor
这一行在model.compile()中编译失败。它说它期望bool,但得到了intI更新的代码,这次我正确地测试了它。我还将其更改为仅在最后应用权重。