此页面由 AI 自动翻译。查看英文原版
最后更新

本页目录

  • 类
  • CrossEntropyLoss
Claude CodeCodexCursor
Luxonis 智能体工具包为你常用的编程智能体加载 Luxonis 上下文与技能,更快地基于 OAK 开发应用。
安装工具包

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 之和。

方法

init
Python
1def __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 中所述。
  • **kwargs: 转发给 BaseLoss 的关键字参数,例如 final_loss_weight 和 node。
forward
Python
1def forward(predictions: Tensor, target: Tensor) -> Tensor:
计算 logits 和类目标之间的交叉熵。当两个张量具有相同维度数时,该方法将 target 视为 one-hot。类维度为 1,对于只有一个维度的张量则为 0。当 predictions 具有一个通道时,该方法首先添加第二个通道,如类注释所述。然后它通过对类维度进行 argmax 将 target 转换为类索引。对于 multi-hot 目标,argmax 选择具有最高值的第一个类。参数
  • 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