Pytorch实用教程:多分类任务中使用的交叉熵损失函数nn.CrossEntropyLoss

nn.CrossEntropyLoss 在 PyTorch 中是处理多分类问题的常用损失函数,它是两个函数 nn.LogSoftmaxnn.NLLLoss(Negative Log Likelihood Loss)的组合。使用这个损失函数可以直接从模型得到原始的输出分数(logits),而不需要单独对输出进行 Softmax 处理。下面详细介绍这个损失函数的关键特点、工作原理和使用方式。

工作原理

nn.CrossEntropyLoss 首先对网络的输出应用 LogSoftmax。这意味着网络输出的 logits(原始预测值)被转换成概率的对数形式。然后,它使用这些对数概率和真实标签计算 NLLLoss。

具体来说,公式可以表示为:

[ \text{Loss}(x, \text{class}) = -\log\left(\frac{\exp(x[\text{class}])}{\sum_j \exp(x[j])}\right) ]
[ \text{Loss}(x, \text{class}) = -x[\text{class}] + \log\left(\sum_j \exp(x[j])\right) ]

其中:

  • ( x ) 是模型输出的 logits。
  • ( \text{class} ) 是真实的类别标签(非 one-hot 编码)。

参数详解

  • weight (Tensor, optional): 手动指定每个类的权重。如果给定,必须是一个长度为 C 的 Te

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-06-07 23:14:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-06-07 23:14:03       101 阅读
  3. 在Django里面运行非项目文件

    2024-06-07 23:14:03       82 阅读
  4. Python语言-面向对象

    2024-06-07 23:14:03       91 阅读

热门阅读

  1. Python基础总结之functools.partial

    2024-06-07 23:14:03       24 阅读
  2. LeetCode hot100-64-Y

    2024-06-07 23:14:03       30 阅读
  3. Flink mongo & Kafka

    2024-06-07 23:14:03       24 阅读
  4. 51.线程池大小

    2024-06-07 23:14:03       28 阅读
  5. Switch刷机:安装Android系统和Linux系统

    2024-06-07 23:14:03       131 阅读
  6. 【微信小程序】处理蓝牙数据相关函数

    2024-06-07 23:14:03       31 阅读
  7. 聊聊App在安卓设备中所使用的内存

    2024-06-07 23:14:03       33 阅读