我希望我的模型在训练时通过创建自定义损失函数来增加误报预测的损失。
model.fit() 中的 class_weight 参数不适用于此问题。 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
我可以用张量做简单的事情,例如获取均方误差,但我不知道如何做逻辑事情。
我尝试过一些 hacky 解决方案,但不起作用并且感觉完全错误:
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
我使用 python 3 和 keras 2 以及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
关于python - 对不同的错误分类进行不同的权重 keras,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46202839/