如何在Keras中计算多个类别的总损失?

时间:2018-08-27 08:00:59

标签: python tensorflow machine-learning keras deep-learning

假设我具有以下参数的网络:

  1. 用于语义分割的全卷积网络
  2. loss =加权二进制交叉熵(但可以是任何损失函数,无关紧要)
  3. 5类-输入是图像,地面真理是二进制掩码
  4. 批量大小= 16

现在,我知道损失是以以下方式计算的:关于每个类别,二进制交叉熵应用于图像中的每个像素。因此,基本上每个像素都会有5个损耗值

此步骤后会发生什么?

当我训练我的网络时,它只显示一个时期的单个损失值。 产生单个值需要发生许多级别的损失累积,而在文档/代码中根本不清楚如何发生。

  1. 首先组合的内容-(1)该类别的损耗值(例如,每个像素组合5个值(每个类别一个)),然后是图像中的所有像素,或者(2)像素中的所有像素每个类别的图像,然后将所有类别的损失相加?
  2. 这些不同的像素组合到底发生了什么-求和在哪里/平均在哪里?
  3. Keras's binary_crossentropy的平均值超过axis=-1。那么,这是每个类别的所有像素的平均值还是所有类别的平均值,或者两者都是?

以不同的方式陈述它:如何将不同类别的损失相结合以产生图像的单个损失值?

文档中没有对此进行完全解释,这对不管网络类型如何的人都对keras进行多类预测的人都将非常有帮助。这是keras code开头的链接,其中第一个传递损失函数。

我能找到的最接近解释的是

  

loss:字符串(目标函数的名称)或目标函数。见损失。如果模型具有多个输出,则可以通过传递字典或损失列表来对每个输出使用不同的损失。该模型将使损失值最小化,将是所有单个损失的总和

来自keras。那么这是否意味着图像中每个类别的损失都可以简单地求和?

示例代码,供其他人尝试。这是从Kaggle借用并针对多标签预测进行修改的基本实现:

# Build U-Net model
num_classes = 5
IMG_DIM = 256
IMG_CHAN = 3
weights = {0: 1, 1: 1, 2: 1, 3: 1, 4: 1000} #chose an extreme value just to check for any reaction
inputs = Input((IMG_DIM, IMG_DIM, IMG_CHAN))
s = Lambda(lambda x: x / 255) (inputs)

c1 = Conv2D(8, (3, 3), activation='relu', padding='same') (s)
c1 = Conv2D(8, (3, 3), activation='relu', padding='same') (c1)
p1 = MaxPooling2D((2, 2)) (c1)

c2 = Conv2D(16, (3, 3), activation='relu', padding='same') (p1)
c2 = Conv2D(16, (3, 3), activation='relu', padding='same') (c2)
p2 = MaxPooling2D((2, 2)) (c2)

c3 = Conv2D(32, (3, 3), activation='relu', padding='same') (p2)
c3 = Conv2D(32, (3, 3), activation='relu', padding='same') (c3)
p3 = MaxPooling2D((2, 2)) (c3)

c4 = Conv2D(64, (3, 3), activation='relu', padding='same') (p3)
c4 = Conv2D(64, (3, 3), activation='relu', padding='same') (c4)
p4 = MaxPooling2D(pool_size=(2, 2)) (c4)

c5 = Conv2D(128, (3, 3), activation='relu', padding='same') (p4)
c5 = Conv2D(128, (3, 3), activation='relu', padding='same') (c5)

u6 = Conv2DTranspose(64, (2, 2), strides=(2, 2), padding='same') (c5)
u6 = concatenate([u6, c4])
c6 = Conv2D(64, (3, 3), activation='relu', padding='same') (u6)
c6 = Conv2D(64, (3, 3), activation='relu', padding='same') (c6)

u7 = Conv2DTranspose(32, (2, 2), strides=(2, 2), padding='same') (c6)
u7 = concatenate([u7, c3])
c7 = Conv2D(32, (3, 3), activation='relu', padding='same') (u7)
c7 = Conv2D(32, (3, 3), activation='relu', padding='same') (c7)

u8 = Conv2DTranspose(16, (2, 2), strides=(2, 2), padding='same') (c7)
u8 = concatenate([u8, c2])
c8 = Conv2D(16, (3, 3), activation='relu', padding='same') (u8)
c8 = Conv2D(16, (3, 3), activation='relu', padding='same') (c8)

u9 = Conv2DTranspose(8, (2, 2), strides=(2, 2), padding='same') (c8)
u9 = concatenate([u9, c1], axis=3)
c9 = Conv2D(8, (3, 3), activation='relu', padding='same') (u9)
c9 = Conv2D(8, (3, 3), activation='relu', padding='same') (c9)

outputs = Conv2D(num_classes, (1, 1), activation='sigmoid') (c9)

model = Model(inputs=[inputs], outputs=[outputs])
model.compile(optimizer='adam', loss=weighted_loss(weights), metrics=[mean_iou])

def weighted_loss(weightsList):
    def lossFunc(true, pred):

        axis = -1 #if channels last 
        #axis=  1 #if channels first        
        classSelectors = K.argmax(true, axis=axis) 
        classSelectors = [K.equal(tf.cast(i, tf.int64), tf.cast(classSelectors, tf.int64)) for i in range(len(weightsList))]
        classSelectors = [K.cast(x, K.floatx()) for x in classSelectors]
        weights = [sel * w for sel,w in zip(classSelectors, weightsList)] 

        weightMultiplier = weights[0]
        for i in range(1, len(weights)):
            weightMultiplier = weightMultiplier + weights[i]

        loss = BCE_loss(true, pred) - (1+dice_coef(true, pred))
        loss = loss * weightMultiplier
        return loss
    return lossFunc
model.summary()

在这里可以找到实际的BCE-DICE丢失功能。

问题的动机:根据上述代码,在20个时期后,网络的总验证损失约为1%;但是,前4个类别的联合得分平均交集率均高于95%,而最后4个类别的联合得分均值大于23%。清楚地表明5年级的学生表现不佳。但是,这种准确性上的损失根本没有反映在损失中。因此,这意味着样本的单个损失被合并在一起,从而完全抵消了我们在第五类中看到的巨大损失。而且,因此,如果将每个样本的损失分批合并,则它仍然非常低。我不确定如何协调此信息。

2 个答案:

答案 0 :(得分:2)

尽管我已经在related answer中提到了此答案的一部分,但让我们逐步检查源代码,以获取更多详细信息,以具体找到答案。

首先,让我们前馈(!):there is a callweighted_loss函数,该函数将y_truey_predsample_weightmask作为输入:

weighted_loss = weighted_losses[i]
# ...
output_loss = weighted_loss(y_true, y_pred, sample_weight, mask)

weighted_loss实际上是an element of a list,其中包含传递给fit方法的所有(增强的)损失函数:

weighted_losses = [
    weighted_masked_objective(fn) for fn in loss_functions]

我提到的“增强”一词在这里很重要。这是因为,如您在上面看到的那样,实际损失函数由另一个称为weighted_masked_objective的函数包装,该函数定义如下:

def weighted_masked_objective(fn):
    """Adds support for masking and sample-weighting to an objective function.
    It transforms an objective function `fn(y_true, y_pred)`
    into a sample-weighted, cost-masked objective function
    `fn(y_true, y_pred, weights, mask)`.
    # Arguments
        fn: The objective function to wrap,
            with signature `fn(y_true, y_pred)`.
    # Returns
        A function with signature `fn(y_true, y_pred, weights, mask)`.
    """
    if fn is None:
        return None

    def weighted(y_true, y_pred, weights, mask=None):
        """Wrapper function.
        # Arguments
            y_true: `y_true` argument of `fn`.
            y_pred: `y_pred` argument of `fn`.
            weights: Weights tensor.
            mask: Mask tensor.
        # Returns
            Scalar tensor.
        """
        # score_array has ndim >= 2
        score_array = fn(y_true, y_pred)
        if mask is not None:
            # Cast the mask to floatX to avoid float64 upcasting in Theano
            mask = K.cast(mask, K.floatx())
            # mask should have the same shape as score_array
            score_array *= mask
            #  the loss per batch should be proportional
            #  to the number of unmasked samples.
            score_array /= K.mean(mask)

        # apply sample weighting
        if weights is not None:
            # reduce score_array to same ndim as weight array
            ndim = K.ndim(score_array)
            weight_ndim = K.ndim(weights)
            score_array = K.mean(score_array,
                                 axis=list(range(weight_ndim, ndim)))
            score_array *= weights
            score_array /= K.mean(K.cast(K.not_equal(weights, 0), K.floatx()))
        return K.mean(score_array)
return weighted

因此,有一个嵌套函数weighted,它实际上在行fn中调用了实损失函数score_array = fn(y_true, y_pred)。现在,具体来说,在所提供的OP的例子中,fn(即损失函数)是binary_crossentropy。因此,我们需要看一下Keras中binary_crossentropy()的定义:

def binary_crossentropy(y_true, y_pred):
    return K.mean(K.binary_crossentropy(y_true, y_pred), axis=-1)

依次调用后端函数K.binary_crossentropy()。如果使用Tensorflow作为后端,则K.binary_crossentropy()的定义如下:

def binary_crossentropy(target, output, from_logits=False):
    """Binary crossentropy between an output tensor and a target tensor.
    # Arguments
        target: A tensor with the same shape as `output`.
        output: A tensor.
        from_logits: Whether `output` is expected to be a logits tensor.
            By default, we consider that `output`
            encodes a probability distribution.
    # Returns
        A tensor.
    """
    # Note: tf.nn.sigmoid_cross_entropy_with_logits
    # expects logits, Keras expects probabilities.
    if not from_logits:
        # transform back to logits
        _epsilon = _to_tensor(epsilon(), output.dtype.base_dtype)
        output = tf.clip_by_value(output, _epsilon, 1 - _epsilon)
        output = tf.log(output / (1 - output))

    return tf.nn.sigmoid_cross_entropy_with_logits(labels=target,
                                                   logits=output)

tf.nn.sigmoid_cross_entropy_with_logits返回:

  

logits形状相同的张量,具有逻辑对数损失。

现在,让我们反向传播(!):考虑以上注意事项,K.binray_crossentropy的输出形状将与y_pred(或y_true)相同。如OP所述,y_true的形状为(batch_size, img_dim, img_dim, num_classes)。因此,将K.mean(..., axis=-1)应用于形状为(batch_size, img_dim, img_dim, num_classes)的张量上,这将导致输出形状为(batch_size, img_dim, img_dim)的张量。因此,对于图像中的每个像素,对所有类别的损耗值进行平均。因此,上述score_array函数中weighted的形状将为(batch_size, img_dim, img_dim)。还有一个步骤:weighted函数中的return语句再次取均值,即return K.mean(score_array)。那么它如何计算均值?如果您查看mean后端函数的定义,您会发现axis参数默认为None

def mean(x, axis=None, keepdims=False):
    """Mean of a tensor, alongside the specified axis.
    # Arguments
        x: A tensor or variable.
        axis: A list of integer. Axes to compute the mean.
        keepdims: A boolean, whether to keep the dimensions or not.
            If `keepdims` is `False`, the rank of the tensor is reduced
            by 1 for each entry in `axis`. If `keepdims` is `True`,
            the reduced dimensions are retained with length 1.
    # Returns
        A tensor with the mean of elements of `x`.
    """
    if x.dtype.base_dtype == tf.bool:
        x = tf.cast(x, floatx())
return tf.reduce_mean(x, axis, keepdims)

它调用给定axis=None参数的tf.reduce_mean(),取输入张量的所有轴的均值并返回一个值。因此,计算形状为(batch_size, img_dim, img_dim)的整个张量的平均值,这意味着对批次中的所有标签及其所有像素取平均值,并作为代表损失值的单个标量值返回。然后,该损失值由Keras报告,并用于优化。


奖金:如果我们的模型具有多个输出层并因此使用了多个损失函数,该怎么办?

记住我在此答案中提到的第一段代码:

weighted_loss = weighted_losses[i]
# ...
output_loss = weighted_loss(y_true, y_pred, sample_weight, mask)

如您所见,有一个i变量用于索引数组。您可能已经猜对了:它实际上是循环的一部分,该循环使用其指定的损耗函数为每个输出层计算损耗值,然后将所有这些损耗值的(加权)和取为compute the total loss

# Compute total loss.
total_loss = None
with K.name_scope('loss'):
    for i in range(len(self.outputs)):
        if i in skip_target_indices:
            continue
        y_true = self.targets[i]
        y_pred = self.outputs[i]
        weighted_loss = weighted_losses[i]
        sample_weight = sample_weights[i]
        mask = masks[i]
        loss_weight = loss_weights_list[i]
        with K.name_scope(self.output_names[i] + '_loss'):
            output_loss = weighted_loss(y_true, y_pred,
                                        sample_weight, mask)
        if len(self.outputs) > 1:
            self.metrics_tensors.append(output_loss)
            self.metrics_names.append(self.output_names[i] + '_loss')
        if total_loss is None:
            total_loss = loss_weight * output_loss
        else:
            total_loss += loss_weight * output_loss
    if total_loss is None:
        if not self.losses:
            raise ValueError('The model cannot be compiled '
                                'because it has no loss to optimize.')
        else:
            total_loss = 0.

    # Add regularization penalties
    # and other layer-specific losses.
    for loss_tensor in self.losses:
        total_loss += loss_tensor  

答案 1 :(得分:0)

1) What gets combined first - (1) the loss values of the class(for instance 10 values(one for each class) get combined per pixel) and
     

则图像中的所有像素或(2)图像中的所有像素   每个班级,那么所有班级损失是加在一起的?       2)这些不同的像素组合到底发生了什么-在何处求和/在何处取平均值?

我对(1)的回答: 训练一批图像时,通过计算非线性函数,损失和优化(更新权重)来训练由像素值组成的数组。 未针对每个像素值计算损失;而是针对每张图片完成

在S形中(对于非线性的最简单示例)使用像素值(X_train),权重和偏差(b)来计算预测的y值。这与y_train(一次批处理)一起用于计算损失,并使用SGD,动量,Adam等优化方法之一进行了优化,以更新权重和偏差。

我对(2)的回答: 在非线性操作期间,像素值(X_train)与权重组合(通过点积)并相加以偏置以形成预测目标值。

一批中可能有属于不同班级的训练示例。将对应的目标值(针对每个类别)与对应的预测值进行比较,以计算损失。因此,将所有损失相加是完全可以的。

只要您将其与正确类别的对应目标进行比较,则它们属于一个类别还是多个类别确实无关紧要。有道理吗?