Tensorflow 尝试用班级权重修改keras中的分类_交叉熵损失,但在训练期间不起作用

Tensorflow 尝试用班级权重修改keras中的分类_交叉熵损失,但在训练期间不起作用,tensorflow,keras,weighted,loss,cross-entropy,Tensorflow,Keras,Weighted,Loss,Cross Entropy,我在keras中进行语义分割,并试图修改分类的交叉熵损失,使损失具有类权重 这是我的密码: def class_weighted_categorical_crossentropy(output, target, from_logits=False): """Categorical crossentropy between an output tensor and a target tensor. parameter = TrainingParameters() # create ones

我在keras中进行语义分割,并试图修改分类的交叉熵损失,使损失具有类权重

这是我的密码:

def class_weighted_categorical_crossentropy(output, target, from_logits=False):
"""Categorical crossentropy between an output tensor and a target tensor.

parameter = TrainingParameters()
   # create ones array with shape of target tensor
   # multiply class weight array with inverse class_accuracies for each label
class_weights = tf.convert_to_tensor(parameter.class_weights, dtype=floatx())
   # weight targets with class weights and create pattern with which loss can be multiplied
class_weights_pattern = tf.multiply(target, class_weights)
class_weights_pattern = tf.reduce_sum(class_weights_pattern, reduction_indices=len(class_weights_pattern.get_shape())-1)#, keep_dims=True)
if not from_logits:
    # scale preds so that the class probas of each sample sum to 1
    output /= tf.reduce_sum(output,
                            reduction_indices=len(output.get_shape()) - 1,
                            keep_dims=True)
    # manual computation of crossentropy
    epsilon = _to_tensor(_EPSILON, output.dtype.base_dtype)
    output = tf.clip_by_value(output, epsilon, 1. - epsilon)
    loss = - tf.reduce_sum(target * tf.log(output), reduction_indices=len(output.get_shape()) - 1)
    return tf.multiply(loss, class_weights_pattern)
else:
    loss = tf.nn.softmax_cross_entropy_with_logits(labels=target, logits=output)
    return tf.multiply(loss, class_weights_pattern)
我只是在最后改变了损失乘以class_权重模式。 类权重模式包含每个像素对应的类权重,因此应加权正常的分类熵损失。 然而,如果我用修正的损失来训练我的模型,结果会比只使用keras分类熵损失差得多。即使我将所有类权重设置为1,这样我的类加权分类交叉熵损失应该与keras的分类交叉熵损失完全相同,结果也会更糟。我已经用一些样本图像打印了这两种损耗,损耗完全相同

有人能帮我吗?为什么它不起作用? 提前谢谢