我尝试在Keras中实现一个加权二元交叉熵,但我不确定代码是否正确。训练输出看起来有点混乱。几轮之后,我的准确率只有大约0.15。我认为这太低了(即使是随机猜测)。
总体来说,输出中大约有11%是1,89%是0,因此权重设置为w_zero=0.89和w_one=0.11。
我的代码:
def create_weighted_binary_crossentropy(zero_weight, one_weight): def weighted_binary_crossentropy(y_true, y_pred): # Original binary crossentropy (see losses.py): # K.mean(K.binary_crossentropy(y_true, y_pred), axis=-1) # Calculate the binary crossentropy b_ce = K.binary_crossentropy(y_true, y_pred) # Apply the weights weight_vector = y_true * one_weight + (1. - y_true) * zero_weight weighted_b_ce = weight_vector * b_ce # Return the mean error return K.mean(weighted_b_ce) return weighted_binary_crossentropy
也许有人能看出哪里出了问题?
谢谢
回答:
通常情况下,少数类别会具有更高的类别权重。最好使用one_weight=0.89, zero_weight=0.11
(顺便说一下,你可以使用class_weight={0: 0.11, 1: 0.89}
,如评论中所建议)。
在类别不平衡的情况下,你的模型会看到更多的0而不是1。它也会学会预测更多的0而不是1,因为这样可以最小化训练损失。这也是为什么你看到的准确率接近0.11的比例。如果你对模型预测取平均值,应该非常接近于零。
使用类别权重的目的是改变损失函数,使训练损失不能通过“简单解决方案”(即预测0)来最小化,这就是为什么对于1使用更高的权重会更好。
请注意,最佳权重不一定是0.89和0.11。有时候你可能需要尝试使用对数或平方根(或任何满足one_weight > zero_weight
的权重)来使其工作。