keras中不同批量大小的损失计算

问题描述 投票:3回答:1

我知道理论上,一批网络的丢失只是所有个人损失的总和。这反映在用于计算总损失的Keras code中。贴切:

            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

然而,我注意到当我使用batch_size=32batch_size=64训练网络时,每个时期的损失值仍然或多或少相同,只有~0.05%差异。但是,两个网络的准确性仍然完全相同。基本上,批量大小对网络没有太大影响。

我的问题是,当我将批量大小加倍时,假设损失实际上是相加的,那么实际上损失不应该是以前的两倍,或者至少更大?网络可能通过更大的批量大小更好地学习的借口被精确度保持完全相同的事实否定了。

无论批量大小,损失大致保持不变的事实使我认为它是平均的。

python tensorflow keras deep-learning loss
1个回答
5
投票

您发布的代码涉及多输出模型,其中每个输出可能有自己的损失和权重。因此,将不同输出层的损耗值相加在一起。但是,个别损失是批次的平均值 正如你在losses.py文件中看到的那样。例如,这是与二进制交叉熵损失相关的代码:

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

更新:在添加了这个答案的第二部分(即损失函数)之后,作为OP,我对axis=-1在损失函数的定义中感到困惑,我认为必须用axis=0表示平均值超过批量?!然后我意识到在损失函数定义中使用的所有K.mean()都适用于由多个单元组成的输出层的情况。那么批次的平均损失在哪里?我检查了代码以找到答案:获取特定损失函数的损失值,a function is called将真实和预测标签以及样本权重和掩码作为输入:

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

什么是weighted_losses[i]功能?你可能会发现,it is an element of list of (augmented) loss functions

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

fn实际上是losses.py文件中定义的损失函数之一,或者它可能是用户定义的自定义丢失函数。现在这是什么weighted_masked_objective功能?它已在training_utils.py文件中定义:

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

如您所见,首先每行样本损失在行score_array = fn(y_true, y_pred)中计算,然后在最后返回损失的平均值,即return K.mean(score_array)。因此,确认报告的损失是每批中每个样品损失的平均值。

请注意K.mean(),在使用Tensorflow作为后端的情况下,calls使用tf.reduce_mean()函数。现在,当没有K.mean()参数调用axis时(axis参数的默认值将是None),因为它在weighted_masked_objective函数中调用,相应调用tf.reduce_mean() computes the mean over all the axes and returns one single value。这就是为什么无论输出层的形状和使用的损耗函数,Keras只使用和报告一个单一的损耗值(它应该是这样的,因为优化算法需要最小化标量值,而不是矢量或张量) 。

© www.soinside.com 2019 - 2024. All rights reserved.