在 keras 中从 pytorch 实现 BCEWithLogitsLoss
Implementing BCEWithLogitsLoss from pytorch in keras
我有一个模型,我正在尝试在具有 class 不平衡的数据集上进行训练。该问题是一个多标签 class 化问题(每个样本有 1 个或多个标签)。我还为我的数据集计算了每个 class 的权重。我确实看到了这个实现:
这在 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())
是每个 classes 的浮点数(权重)列表,范围从 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
类的个数。
我有一个模型,我正在尝试在具有 class 不平衡的数据集上进行训练。该问题是一个多标签 class 化问题(每个样本有 1 个或多个标签)。我还为我的数据集计算了每个 class 的权重。我确实看到了这个实现:
这在 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())
是每个 classes 的浮点数(权重)列表,范围从 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
类的个数。