在 Tensorflow 2.0 中实现自定义损失函数

Implement custom loss function in Tensorflow 2.0

我正在构建时间序列分类模型。数据非常不平衡,所以我决定使用加权交叉熵函数作为我的损失。

Tensorflow 提供 tf.nn.weighted_cross_entropy_with_logits 但我不确定如何在 TF 2.0 中使用它。因为我的模型是使用 tf.keras API 构建的,所以我正在考虑像这样创建自定义损失函数:

pos_weight=10
def weighted_cross_entropy_with_logits(y_true,y_pred):
  return tf.nn.weighted_cross_entropy_with_logits(y_true,y_pred,pos_weight)

# .....
model.compile(loss=weighted_cross_entropy_with_logits,optimizer="adam",metrics=["acc"])

我的问题是:有没有办法直接将 tf.nn.weighted_cross_entropy_with_logits 与 tf.keras API 一起使用?

您可以将 class 权重直接传递给 model.fit 函数。

class_weight: Optional dictionary mapping class indices (integers) to a weight (float) value, used for weighting the loss function (during training only). This can be useful to tell the model to "pay more attention" to samples from an under-represented class.

如:

{
    0: 0.31, 
    1: 0.33, 
    2: 0.36, 
    3: 0.42, 
    4: 0.48
}

Source


编辑: JL Meunier answer 很好地解释了如何将 logits 与 class 权重相乘。