# bce_with_logits

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

对原始 logits 进行二元交叉熵计算。

## 类

### BCEWithLogitsLoss

对 logits 进行二元交叉熵计算，其中 sigmoid 函数包含在损失函数内部。

该损失函数将 sigmoid 和二元交叉熵结合在一个步骤中。这比 `Sigmoid` 层后接 `BCELoss` 更具数值稳定性，因为组合步骤使用了 log-sum-exp 技巧。

 * `输入:`: * `predictions` (`Tensor`): `[B, C, ...]` logits
    * `target` (`Tensor`): 相同形状，浮点值在 `[0, 1]` 之间
 * `输出:`: * `Tensor`: 标量，或当 `reduction` 为 `"none"` 时为 `[B, C, ...]`
 * `公式:`: 对于 logit x，其目标 y，以及 sigmoid σ，一个元素的损失为 ℓ = − w[p ylogσ(x) + (1 − y)log(1 − σ(x))] 这里的 w 来自 `weight`，p 来自
   `pos_weight`。如果未设置，两者都为 `1`。然后 `reduction` 对所有元素取平均值或求和，或者保留每个元素的损失。

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

> **注意**
> 该类封装了 `nn.BCEWithLogitsLoss`。[forward](/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/attached_modules/losses/bce_with_logits.md) 首先比较两个张量的形状，如果它们不同则抛出 `RuntimeError`。

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

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

 * `兼容:`: * 节点: *
   [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](/software-v3/ai-inference/model-source/training/luxonis-train/luxonis-train-api-reference/nodes/heads/transformer_segmentation_head.md)

#### 方法

##### init

```python
def __init__(weight: list[float] | None = None, reduction: Literal['none', 'mean', 'sum'] = 'mean', pos_weight: Tensor | None = None, **kwargs):
```

初始化损失函数和封装的 `nn.BCEWithLogitsLoss`。

参数

 * `weight` (`list[float] | None`): 元素损失的因子。该列表将成为一个张量，与形状为 `[B, C, ...]` 的损失进行广播，并在最后一个维度对齐。对于形状为 `[B, C]` 的目标，包含 `C`
   个值的列表为每个类别提供一个因子。对于形状为 `[B, C, H, W]` 的目标，该列表与 `W` 对齐，而不是与类别对齐。`None` 使每个元素的因子为 `1`。
 * `reduction` (`Literal['none', 'mean', 'sum']`): 如何减少元素的损失： * `"none"`: 返回每个元素的损失。
    * `"mean"`: 返回所有元素的平均值。
    * `"sum"`: 返回所有元素的总和。
 * `pos_weight` (`Tensor | None`): 损失正项的因子。该张量与目标进行广播，并在最后一个维度对齐。对于形状为 `[B, C, H, W]` 的目标，形状为 `[C, 1, 1]` 的张量为每个类别提供一个因子。`None`
   使因子为 `1`。列表会引发 `TypeError`。
 * `**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 和目标之间的二元交叉熵。

> **示例**
> 一个自信的正确 logit 会产生较小的损失，而一个自信的错误 logit 会产生较大的损失：

```pycon
>>> import torch
>>> loss = BCEWithLogitsLoss(reduction="none")
>>> logits = torch.tensor([[2.0, -2.0]])
>>> target = torch.tensor([[1.0, 1.0]])
>>> values = loss(logits, target)[0].tolist()
>>> [round(value, 4) for value in values]
[0.1269, 2.1269]
```

目标必须与 logits 的形状相同：

```pycon
>>> BCEWithLogitsLoss()(logits, torch.tensor([1.0, 1.0]))
Traceback (most recent call last):
    ...
RuntimeError: Target tensor dimension (torch.Size([2])) and preds tensor dimension (torch.Size([1, 2])) should be the same.
```

参数

 * `predictions` (`Tensor`): 形状为 `[B, C, ...]` 的 logits，是节点的主要输出。
 * `target` (`Tensor`): 形状与 `predictions` 相同的 `[0, 1]` 范围内的浮点目标。`classification` 标签的形状为 `[B, C]`，`segmentation` 标签的形状为 `[B, C, H,
   W]`。

返回

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

抛出

 * `RuntimeError`: 当 `predictions` 和 `target` 形状不同时。

#### 属性

##### criterion

##### supported_tasks
