smooth_bce_with_logits
最后更新
luxonis_train.attached_modules.losses.smooth_bce_with_logits带标签平滑的二元交叉熵。类
SmoothBCEWithLogitsLoss
输入::predictions(Tensor):[B, C, ...]logitstarget(Tensor): 相同形状,浮点值在[0, 1]之间
输出::Tensor: 标量,或当reduction为"none"时为[B, C, ...]
公式:: 对于平滑因子 s,目标 y 变为 y’ = (1 − s) y + s (1 − y) 因此,目标1变为 1 − s,目标0变为 s。损失是 logits 和 y’ 的 BCEWithLogitsLoss,其中bce_pow作为其pos_weight。
参考
- 来源:本项目。
- 许可证:Apache-2.0(本项目)
注意
bce_pow 不是指数。它是二元交叉熵正项的因子。示例
附加到
model.nodes 中的 DDRNetSegmentationHead:Yaml
1- name: DDRNetSegmentationHead
2 inputs: [DDRNet]
3 losses:
4 - name: SmoothBCEWithLogitsLoss兼容::
方法
init
Python
1def __init__(label_smoothing: float = 0.0, bce_pow: float = 1.0, weight: list[float] | None = None, reduction: Literal['mean', 'sum', 'none'] = 'mean', **kwargs):label_smoothing(float): 平滑因子 s。目标1变为1 - label_smoothing,目标0变为label_smoothing。0.0保持目标不变。bce_pow(float): 损失正项的因子,所有类别相同。它成为包装损失的pos_weight。weight(list[float] | None): 元素损失的因子。包装损失将列表转换为张量,该张量与损失广播,并在最后一个维度对齐。None使每个元素的因子为1。reduction(Literal['mean', 'sum', 'none']): 如何减少元素的损失:"none": 返回每个元素的损失。"mean": 返回所有元素的平均值。"sum": 返回所有元素的总和。
**kwargs: 转发给 BaseLoss 的关键字参数,例如final_loss_weight和node。
forward
Python
1def forward(predictions: Tensor, target: Tensor) -> Tensor:示例
平滑因子
0.1 将目标 1 和 0 转换为 0.9 和 0.1:Pycon
1>>> import torch
2>>> import torch.nn.functional as F
3>>> logits = torch.tensor([[2.0, -1.0]])
4>>> target = torch.tensor([[1.0, 0.0]])
5>>> loss = SmoothBCEWithLogitsLoss(label_smoothing=0.1)
6>>> smoothed = torch.tensor([[0.9, 0.1]])
7>>> bce = F.binary_cross_entropy_with_logits(logits, smoothed)
8>>> torch.allclose(loss(logits, target), bce)
9Truepredictions(Tensor): 形状为[B, C, ...]的 logits,是节点的主要输出。target(Tensor): 形状与predictions相同的[0, 1]范围内的浮点目标。
Tensor: 对于"mean"和"sum"归约,返回一个标量。对于"none",返回每个元素的损失,形状为[B, C, ...]。
RuntimeError: 当predictions和target形状不同时。