python - 在 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'
关于我将如何做这件事的任何想法?
解决方案
最后一层应该有一个'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
类的数量。
推荐阅读
- java - 如何在 Firebase Android 中获取当前用户的 Push id?
- python - 一个python函数抵消了其他
- java - Java Socket 编程异常
- generics - 我什么时候需要实现不同类型的通用接口?
- javascript - Reactjs - 组件作为道具
- ios - 在点击返回之前运行一个函数。iOS,斯威夫特,
- javascript - d3.event 的 x 和 y 坐标在显示工具提示时不正确
- c++ - 整个母类的导入范围
- c# - 当连接丢失或是否有连接状态更改的处理程序时调用什么 SignalR 方法?
- php - Laravel Ratchet 在供应商:发布后未读取配置文件