keras
或tensorflow
中是否有一种方法可以为样本提供额外的权重(如果它们仅被错误分类)。 IE浏览器。类别权重和样本权重的组合,但仅对二元类中的一个结果应用样本权重?
答案 0 :(得分:3)
是的,这是可能的。您可以在下面找到如何在 true positives ,误报, true negatives 等上添加额外权重的示例:
def reweight(y_true, y_pred, tp_weight=0.2, tn_weight=0.2, fp_weight=1.2, fn_weight=1.2):
# Get predictions
y_pred_classes = K.greater_equal(y_pred, 0.5)
y_pred_classes_float = K.cast(y_pred_classes, K.floatx())
# Get misclassified examples
wrongly_classified = K.not_equal(y_true, y_pred_classes_float)
wrongly_classified_float = K.cast(wrongly_classified, K.floatx())
# Get correctly classified examples
correctly_classified = K.equal(y_true, y_pred_classes_float)
correctly_classified_float = K.cast(wrongly_classified, K.floatx())
# Get tp, fp, tn, fn
tp = correctly_classified_float * y_true
tn = correctly_classified_float * (1 - y_true)
fp = wrongly_classified_float * y_true
fn = wrongly_classified_float * (1 - y_true)
# Get weights
weight_tensor = tp_weight * tp + fp_weight * fp + tn_weight * tn + fn_weight * fn
loss = K.binary_crossentropy(y_true, y_pred)
weighted_loss = loss * weight_tensor
return weighted_loss