# cross_entropy

Python API: `luxonis_train.attached_modules.losses.cross_entropy`

原始 logits 上的交叉熵。

## 类

### CrossEntropyLoss

logits 和类目标之间的交叉熵。

 * `输入:`: * `predictions` (`Tensor`): `[B, C, ...]` logits
    * `target` (`Tensor`): `[B, C, ...]` one-hot 或 `[B, ...]` 类索引
 * `输出:`: * `Tensor`: 标量，或当 `reduction` 为 `"none"` 时为 `[B, ...]`
 * `公式:`: one-hot 目标首先通过对类维度进行 `argmax` 变为类索引。对于一个元素的 logits x，其类索引 t，类数 C，以及 `label_smoothing` ε，损失为 ℓ = − C∑c = 1wc
   qclog(exc)/(C∑k = 1exk)，qc = (1 − ε) [c = t] + (ε)/(C) 其中 wc 是类 c 的 `weight`，如果没有 `weight` 则为 `1`。目标为 `ignore_index`
   的元素不增加任何内容。`"mean"` 归约将 ℓ 的和除以所有没有此目标的元素的 wt 之和。

> **参考**
> * 来源：封装 [torch.nn.CrossEntropyLoss](https://docs.pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html) (BSD-3-Clause)。
 * 许可证：Apache-2.0（本项目）

> **注意**
> 当 `predictions` 和 `target` 具有相同维度数时，损失会适应单个通道。当 `predictions` 的类维度大小为 `1` 时，损失会在其前面放置一个零 logits 通道。具有一个通道的目标 y 变为两个通道 1 − y 和 y。在没有 `weight` 和 `label_smoothing` 的情况下，目标 `0` 或 `1` 会给出单个 logit 的二元交叉熵。损失会在第一次此类调用时记录警告。[BCEWithLogitsLoss](/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/attached_modules/losses/bce_with_logits.md) 直接处理一个类。

> **示例**
> 附加到 `model.nodes` 中的 `DDRNetSegmentationHead`：

```yaml
- name: DDRNetSegmentationHead
  inputs: [DDRNet]
  losses:
    - name: CrossEntropyLoss
```

 * `兼容:`: *
   使用者：[ClassificationModel](/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/config/predefined_models/classification/v1/model.md)
    * 节点: *
      [BiSeNetHead](/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/nodes/heads/bisenet_head.md)
       * [ClassificationHead](/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/nodes/heads/classification_head.md)
       * [DDRNetSegmentationHead](/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/nodes/heads/ddrnet_segmentation_head.md)
       * [SegmentationHead](/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/nodes/heads/segmentation_head.md)
       * [TransformerClassificationHead](/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/nodes/heads/transformer_classification_head.md)
       * [TransformerSegmentationHead](article://software-v3.ai-inference.model-source.train.luxonis-train-api-reference.nodes.heads.transformer_segmentation_head)

#### 方法

##### init

```python
def __init__(weight: list[float] | None = None, ignore_index: int = -100, reduction: Literal['none', 'mean', 'sum'] = 'mean', label_smoothing: float = 0.0, **kwargs):
```

初始化损失和封装的 `nn.CrossEntropyLoss`。

参数

 * `weight` (`list[float] | None`): 每个类的因子 wc，每个类一个值。`None` 会给每个类因子 `1`。
 * `ignore_index` (`int`): 一个类索引，它不增加损失和梯度。one-hot 目标变为从 `0` 到 `C - 1` 的索引。因此，默认的 `-100` 只影响类索引的目标。
 * `reduction` (`Literal['none', 'mean', 'sum']`): 如何减少元素的损失： * `"none"`：返回每个元素的损失。
    * `"mean"`：返回加权平均值，如类公式所述。
    * `"sum"`：返回所有元素的总和。
 * `label_smoothing` (`float`): 值 ε，在 `[0, 1]` 之间。目标保留其质量的 1 − ε，并将 ε 平均分布到所有类中，如 [Rethinking the Inception Architecture for
   Computer Vision](https://arxiv.org/abs/1512.00567) 中所述。
 * `**kwargs`: 转发给
   [BaseLoss](/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/attached_modules/losses/base_loss.md)
   的关键字参数，例如 `final_loss_weight` 和 `node`。

##### forward

```python
def forward(predictions: Tensor, target: Tensor) -> Tensor:
```

计算 logits 和类目标之间的交叉熵。

当两个张量具有相同维度数时，该方法将 `target` 视为 one-hot。类维度为 `1`，对于只有一个维度的张量则为 `0`。当 `predictions` 具有一个通道时，该方法首先添加第二个通道，如类注释所述。然后它通过对类维度进行 `argmax`
将 `target` 转换为类索引。对于 multi-hot 目标，`argmax` 选择具有最高值的第一个类。

> **示例**
> one-hot 目标和相同的类索引给出相同的损失：

```pycon
>>> import torch
>>> loss = CrossEntropyLoss()
>>> logits = torch.tensor([[2.0, 0.0], [0.0, 2.0]])
>>> one_hot = torch.tensor([[1.0, 0.0], [0.0, 1.0]])
>>> round(loss(logits, one_hot).item(), 4)
0.1269
>>> round(loss(logits, torch.tensor([0, 1])).item(), 4)
0.1269
```

参数

 * `predictions` (`Tensor`): 形状为 `[B, C, ...]` 的 logits，是节点的主要输出。
 * `target` (`Tensor`): 形状为 `[B, C, ...]` 的 one-hot 目标，或形状为 `[B, ...]` 的类索引。`classification` 和 `segmentation` 标签的形状为 `[B, C,
   ...]`。

返回

 * `Tensor`: 对于 `"mean"` 和 `"sum"` 归约，是一个标量。对于 `"none"`，是每个元素的损失，形状为 `[B, ...]`。

引发

 * `RuntimeError`: 当 `target` 的维度数既不等于 `predictions` 的维度数，也不比 `predictions` 的维度数少一个时。

#### 属性

##### criterion

##### supported_tasks
