我尝试用Keras实现加权二进制交叉熵,但我不确定代码是否正确。训练输出似乎有点令人困惑。在几个时代之后,我得到的精确度为~0.15。我认为这太少了(即使是随机猜测)。
输出中通常有大约11%的零和89%的零,因此权重为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
也许有人看错了什么?
谢谢
答案 0 :(得分:6)
您可以使用sklearn module自动为每个类计算权重,如下所示:
# Import
import numpy as np
from sklearn.utils import class_weight
# Example model
model = Sequential()
model.add(Dense(32, activation='relu', input_dim=100))
model.add(Dense(1, activation='sigmoid'))
# Use binary crossentropy loss
model.compile(optimizer='rmsprop',
loss='binary_crossentropy',
metrics=['accuracy'])
# Calculate the weights for each class so that we can balance the data
weights = class_weight.compute_class_weight('balanced',
np.unique(y_train),
y_train)
# Add the class weights to the training
model.fit(x_train, y_train, epochs=10, batch_size=32, class_weight=weights)
请注意,class_weight.compute_class_weight()
的输出是一个像这样的numpy数组:[2.57569845 0.68250928]
。
答案 1 :(得分:5)
通常,少数民族阶级的体重会更高。最好使用one_weight=0.89, zero_weight=0.11
(顺便说一句,您可以按照评论中的建议使用class_weight={0: 0.11, 1: 0.89}
。)
在类不平衡下,您的模型看到的零比零更多。它还将学习预测更多的零,因为这样可以最大限度地减少训练损失。这也是为什么你会看到接近0.11比例的准确度的原因。如果你对模型预测采取平均值,它应该非常接近于零。
使用班级权重的目的是改变损失函数,以便通过简单的解决方案无法最大限度地减少培训损失。 (即预测零),这就是为什么使用更高的权重更好的原因。
请注意,最佳权重不一定是0.89和0.11。有时您可能需要尝试使用对数或平方根(或任何满足one_weight > zero_weight
的权重)来使其工作。
答案 2 :(得分:1)
在class_weights
中使用model.fit
稍有不同:它实际上是更新样本,而不是计算加权损失。
我还发现,当class_weights
作为TFDataset或生成器发送到model.fit中时,sample_weights
和x
在TF 2.0.0中都会被忽略。我相信它是在TF 2.1.0+中修复的。
这是我针对多热编码标签的加权二进制交叉熵函数。
import tensorflow as tf
import tensorflow.keras.backend as K
import numpy as np
# weighted loss functions
def weighted_binary_cross_entropy(weights: dict, from_logits: bool = False):
'''
Return a function for calculating weighted binary cross entropy
It should be used for multi-hot encoded labels
# Example
y_true = tf.convert_to_tensor([1, 0, 0, 0, 0, 0], dtype=tf.int64)
y_pred = tf.convert_to_tensor([0.6, 0.1, 0.1, 0.9, 0.1, 0.], dtype=tf.float32)
weights = {
0: 1.,
1: 2.
}
# with weights
loss_fn = get_loss_for_multilabels(weights=weights, from_logits=False)
loss = loss_fn(y_true, y_pred)
print(loss)
# tf.Tensor(0.6067193, shape=(), dtype=float32)
# without weights
loss_fn = get_loss_for_multilabels()
loss = loss_fn(y_true, y_pred)
print(loss)
# tf.Tensor(0.52158177, shape=(), dtype=float32)
# Another example
y_true = tf.convert_to_tensor([[0., 1.], [0., 0.]], dtype=tf.float32)
y_pred = tf.convert_to_tensor([[0.6, 0.4], [0.4, 0.6]], dtype=tf.float32)
weights = {
0: 1.,
1: 2.
}
# with weights
loss_fn = get_loss_for_multilabels(weights=weights, from_logits=False)
loss = loss_fn(y_true, y_pred)
print(loss)
# tf.Tensor(1.0439969, shape=(), dtype=float32)
# without weights
loss_fn = get_loss_for_multilabels()
loss = loss_fn(y_true, y_pred)
print(loss)
# tf.Tensor(0.81492424, shape=(), dtype=float32)
@param weights A dict setting weights for 0 and 1 label. e.g.
{
0: 1.
1: 8.
}
For this case, we want to emphasise those true (1) label,
because we have many false (0) label. e.g.
[
[0 1 0 0 0 0 0 0 0 1]
[0 0 0 0 1 0 0 0 0 0]
[0 0 0 0 1 0 0 0 0 0]
]
@param from_logits If False, we apply sigmoid to each logit
@return A function to calcualte (weighted) binary cross entropy
'''
assert 0 in weights
assert 1 in weights
def weighted_cross_entropy_fn(y_true, y_pred):
tf_y_true = tf.cast(y_true, dtype=y_pred.dtype)
tf_y_pred = tf.cast(y_pred, dtype=y_pred.dtype)
weights_v = tf.where(tf.equal(tf_y_true, 1), weights[1], weights[0])
ce = K.binary_crossentropy(tf_y_true, tf_y_pred, from_logits=from_logits)
loss = K.mean(tf.multiply(ce, weights_v))
return loss
return weighted_cross_entropy_fn
答案 3 :(得分:0)
我认为在model.fit中使用类权重是不正确的。 {0:0.11,1:0.89},0这里是索引,而不是0类。 Keras文档:https://keras.io/models/sequential/ class_weight:可选字典将类索引(整数)映射到权重(浮点)值,用于加权损失函数(仅限训练期间)。这可以用来告诉模型更多关注"来自代表性不足的班级的样本。
答案 4 :(得分:0)
您可以像这样计算权重,并让二进制交叉熵像这样,以编程方式将one_weight设置为0.11,将one_weight设置为0.89:
one_weight = (1-num_of_ones)/(num_of_ones + num_of_zeros)
zero_weight = (1-num_of_zeros)/(num_of_ones + num_of_zeros)
def weighted_binary_crossentropy(zero_weight, one_weight):
def weighted_binary_crossentropy(y_true, y_pred):
b_ce = K.binary_crossentropy(y_true, y_pred)
# weighted calc
weight_vector = y_true * one_weight + (1 - y_true) * zero_weight
weighted_b_ce = weight_vector * b_ce
return K.mean(weighted_b_ce)
return weighted_binary_crossentropy
答案 5 :(得分:0)
如果您需要一个加权验证损失,其权重与训练损失的权重不同,则可以通过将验证数据集作为Numpy元组使用tensorflow.keras.model.fit()的参数validation_data包含您的验证数据,标签和每个样品重量的数组。
请注意,您必须使用此技术(此处按类)将每个样本映射到其重量。
点击链接在这里: https://www.tensorflow.org/api_docs/python/tf/keras/Model#fit