首页 > 解决方案 > 在 keras 中从 pytorch 实现 BCEWithLogitsLoss

问题描述

我有一个模型,我正在尝试在具有类不平衡的数据集上进行训练。该问题是一个多标签分类问题(每个样本有 1 个或多个标签)。我还有为我的数据集计算的每个类的权重。我确实看到了这个实现: BCEWithLogitsLoss in Keras

这是 pytorch 中的等价物:

criterion = nn.BCEWithLogitsLoss(pos_weight=trainset.labels_weights.to(DEVICE))

所以我尝试将其传递给我的模型:

def get_weighted_loss(weights):
    def weighted_loss(y_true, y_pred):
        xent = tf.compat.v2.losses.BinaryCrossentropy(from_logits=False, reduction=tf.compat.v2.keras.losses.Reduction.NONE)
        weighted_loss = tf.reduce_mean(xent(y_true, y_pred) * weights)
    return weighted_loss

并编译模型如下:

model.compile(optimizer=optim, loss=get_weighted_loss(list(train_generatorLat.labels_weights.values())), metrics=[full_multi_label_metric])

其中list(train_generatorLat.labels_weights.values())是从 1.0 到 5.0 范围内的每个类的浮点数(权重)列表,其中 1 赋予示例最多的标签,5.0 赋予示例最少的标签

但我收到以下错误:

AttributeError                            Traceback (most recent call last)
<ipython-input-108-98496152ec7d> in <module>
----> 1 model.compile(optimizer=optim, loss=get_weighted_loss(list(train_generatorLat.labels_weights.values())), metrics=[full_multi_label_metric])
      2 model.summary()

/gpfs/ysm/project/kl533/conda_envs/dlnn/lib/python3.6/site-packages/keras/engine/training.py in compile(self, optimizer, loss, metrics, loss_weights, sample_weight_mode, weighted_metrics, target_tensors, **kwargs)
    340                 with K.name_scope(self.output_names[i] + '_loss'):
    341                     output_loss = weighted_loss(y_true, y_pred,
--> 342                                                 sample_weight, mask)
    343                 if len(self.outputs) > 1:
    344                     self.metrics_tensors.append(output_loss)

/gpfs/ysm/project/kl533/conda_envs/dlnn/lib/python3.6/site-packages/keras/engine/training_utils.py in weighted(y_true, y_pred, weights, mask)
    415         if weights is not None:
    416             # reduce score_array to same ndim as weight array
--> 417             ndim = K.ndim(score_array)
    418             weight_ndim = K.ndim(weights)
    419             score_array = K.mean(score_array,

/gpfs/ysm/project/kl533/conda_envs/dlnn/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py in ndim(x)
    617     ```
    618     """
--> 619     dims = x.get_shape()._dims
    620     if dims is not None:
    621         return len(dims)

AttributeError: 'NoneType' object has no attribute 'get_shape'

关于我将如何做这件事的任何想法?

标签: pythonkerasloss-functionmultilabel-classification

解决方案


最后一层应该有一个'sigmoid'激活。

compile你的损失应该是loss='binary_crossentropy'

fit否则fit_generator你会通过class_weight=dictionary_of_weights

dictionary_of_weights类似的东西在哪里:

dictionary_of_weights = { 0: weight0,
                          1: weight1, 
                          ....
                          n: weightN }

n+1类的数量。


推荐阅读