飞桨中softmax_with_cross_entropy的用法

本文详细介绍了PaddlePaddle 1.8.5环境下softmax_with_cross_entropy函数的用法,包括其输入参数、适用场景、错误示例及正确用法。重点在于理解该函数如何处理硬标签和软标签,以及如何确保正确调用以避免数值不稳定问题。

飞桨中softmax_with_cross_entropy的用法


本文只作为笔记用。
环境:paddle 1.8.5

一直以来不太清楚这个如何调用,只知道例程里是这样用,不知所以然。
下面记录一下它的用法。
源码如下:

def softmax_with_cross_entropy(logits,
                               label,
                               soft_label=False,
                               ignore_index=kIgnoreIndex,
                               numeric_stable_mode=True,
                               return_softmax=False,
                               axis=-1):
    """
    This operator implements the cross entropy loss function with softmax. This function 
    combines the calculation of the softmax operation and the cross entropy loss function 
    to provide a more numerically stable gradient.

    Because this operator performs a softmax on logits internally, it expects
    unscaled logits. This operator should not be used with the output of
    softmax operator since that would produce incorrect results.

    When the attribute :attr:`soft_label` is set :attr:`False`, this operators 
    expects mutually exclusive hard labels, each sample in a batch is in exactly 
    one class with a probability of 1.0. Each sample in the batch will have a 
    single label.

    The equation is as follows:

    1) Hard label (one-hot label, so every sample has exactly one class)

    .. math::

        loss_j =  -\\text{logits}_{label_j} +
        \\log\\left(\\sum_{i=0}^{K}\\exp(\\text{logits}_i)\\right), j = 1,..., K

    2) Soft label (each sample can have a distribution over all classes)

    .. math::

        loss_j =  -\\sum_{i=0}^{K}\\text{label}_i
        \\left(\\text{logits}_i - \\log\\left(\\sum_{i=0}^{K}
        \\exp(\\text{logits}_i)\\right)\\right), j = 1,...,K

    3) If :attr:`numeric_stable_mode` is :attr:`True`, softmax is calculated first by:

    .. math::

        max_j &= \\max_{i=0}^{K}{\\text{logits}_i}

        log\\_max\\_sum_j &= \\log\\sum_{i=0}^{K}\\exp(logits_i - max_j)

        softmax_j &= \\exp(logits_j - max_j - {log\\_max\\_sum}_j)

    and then cross entropy loss is calculated by softmax and label.

    Args:
        logits (Variable): A multi-dimension ``Tensor`` , and the data type is float32 or float64. The input tensor of unscaled log probabilities.
        label (Variable): The ground truth  ``Tensor`` , data type is the same
            as the ``logits`` . If :attr:`soft_label` is set to :attr:`True`, 
            Label is a ``Tensor``  in the same shape with :attr:`logits`. 
            If :attr:`soft_label` is set to :attr:`True`, Label is a ``Tensor`` 
            in the same shape with :attr:`logits` expect shape in dimension :attr:`axis` as 1.
        soft_label (bool, optional): A flag to indicate whether to interpretant the given
            labels as soft labels. Default False.
        ignore_index (int, optional): Specifies a target value that is ignored and does
                                      not contribute to the input gradient. Only valid
                                      if :attr:`soft_label` is set to :attr:`False`. 
                                      Default: kIgnoreIndex(-100).
        numeric_stable_mode (bool, optional): A flag to indicate whether to use a more
                                              numerically stable algorithm. Only valid
                                              when :attr:`soft_label` is :attr:`False` 
                                              and GPU is used. When :attr:`soft_label` 
                                              is :attr:`True` or CPU is used, the 
                                              algorithm is always numerically stable.
                                              Note that the speed may be slower when use
                                              stable algorithm. Default: True.
        return_softmax (bool, optional): A flag indicating whether to return the softmax
                                         along with the cross entropy loss. Default: False.
        axis (int, optional): The index of dimension to perform softmax calculations. It 
                              should be in range :math:`[-1, rank - 1]`, while :math:`rank`
                              is the rank of input :attr:`logits`. Default: -1.

    Returns:
        ``Variable`` or Tuple of two ``Variable`` : Return the cross entropy loss if \
                                                    `return_softmax` is False, otherwise the tuple \
                                                    (loss, softmax), softmax is in the same shape \
                                                    with input logits and cross entropy loss is in \
                                                    the same shape with input logits except shape \
                                                    in dimension :attr:`axis` as 1.

    Examples:
        .. code-block:: python

            import paddle.fluid as fluid

            data = fluid.data(name='data', shape=[-1, 128], dtype='float32')
            label = fluid.data(name='label', shape=[-1, 1], dtype='int64')
            fc = fluid.layers.fc(input=data, size=100)
            out = fluid.layers.softmax_with_cross_entropy(
                logits=fc, label=label)
    """
    if in_dygraph_mode():
        softmax, loss = core.ops.softmax_with_cross_entropy(
            logits, label, 'soft_label', soft_label, 'ignore_index',
            ignore_index, 'numeric_stable_mode', numeric_stable_mode, 'axis',
            axis)
        if not return_softmax:
            return loss
        else:
            return loss
### ### 定义与数学表达 `tf.nn.sparse_softmax_cross_entropy_with_logits` 是 TensorFlow 中用于多分类任务的损失函数。该函数接受两个输入:`logits` 和 `labels`。其中,`logits` 是神经网络输出层的原始输出(未经过 softmax 函数),形状为 `(batch_size, num_classes)`,而 `labels` 是一个一维整数张量,形状为 `(batch_size,)`,表示每个样本所属类别的索引。该函数内部会自动对 `logits` 进行 softmax 操作,并与自动转换为 one-hot 编码的 `labels` 进行交叉熵计算[^2]。 交叉熵损失函数的数学表达式如下: $$ \text{Loss} = -\sum_{i=1}^{C} y_i \cdot \log(\hat{y}_i) $$ 其中,$ y_i $ 是真实标签(one-hot 编码后的形式),$ \hat{y}_i $ 是预测的概率分布(经过 softmax 后的输出)。由于 `sparse_softmax_cross_entropy_with_logits` 会自动将标签转换为 one-hot 形式,因此在使用时只需传入整数标签即可,无需手动进行 one-hot 编码[^3]。 ### ### 与 `softmax_cross_entropy_with_logits` 的区别 与 `tf.nn.softmax_cross_entropy_with_logits` 不同,后者要求标签必须是 one-hot 编码形式,即每个样本的标签是一个长度为 `num_classes` 的向量,其中只有一个元素为 1,其余为 0。而 `sparse_softmax_cross_entropy_with_logits` 则适用于标签为整数索引的情况,避免了手动转换 one-hot 编码的步骤,提高了代码的简洁性和运行效率[^1]。 例如,在三分类问题中,若某个样本的真实类别为第 3 类,则使用 `softmax_cross_entropy_with_logits` 时需传入标签 `[0, 0, 1]`,而使用 `sparse_softmax_cross_entropy_with_logits` 时只需传入整数 `2`。该函数会自动将其转换为对应的 one-hot 向量并与预测值进行计算。 ### ### 使用示例 以下是一个使用 `sparse_softmax_cross_entropy_with_logits` 的简单示例: ```python import tensorflow as tf # 假设 batch_size = 2, num_classes = 3 logits = tf.constant([[2.0, 1.0, 0.1], [0.5, 1.0, 2.0]], dtype=tf.float32) # 对应的真实类别标签(整数形式) labels = tf.constant([0, 2], dtype=tf.int32) # 计算交叉熵损失 loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=labels, logits=logits) # 计算平均损失 mean_loss = tf.reduce_mean(loss) print("Loss per sample:", loss.numpy()) print("Mean loss:", mean_loss.numpy()) ``` 在上述代码中,`logits` 是模型输出的原始值,`labels` 是类别索引。函数会自动计算每个样本的交叉熵损失,并返回一个形状为 `(batch_size,)` 的张量。最后通过 `reduce_mean` 得到整个批次的平均损失值[^2]。 ### ### 在深度学习中的作用 在深度学习中,`sparse_softmax_cross_entropy_with_logits` 被广泛用于多分类任务,如图像分类、文本分类等。其主要作用是衡量模型预测的概率分布与真实标签之间的差异,并通过反向传播优化模型参数,使预测结果更接近真实标签。由于其对标签格式的灵活性和计算效率的优势,该损失函数成为分类任务中首选的损失函数之一[^1]。 此外,该函数还避免了手动进行 one-hot 编码的繁琐步骤,减少了数据预处理的工作量,同时降低了内存占用,尤其适用于类别数量较大的场景。 ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值