评价此页

MultiMarginLoss#

class torch.nn.MultiMarginLoss(p=1, margin=1.0, weight=None, size_average=None, reduce=None, reduction='mean')[source]#

创建一个标准,用于优化输入 xx (一个二维小批量 Tensor) 和输出 yy (目标类别索引的一维张量,0yx.size(1)10 \leq y \leq \text{x.size}(1)-1)之间的多类分类铰链损失(基于边距的损失)。

对于每个小批量样本,以一维输入 xx 和标量输出 yy 为目标的损失是:

loss(x,y)=imax(0,marginx[y]+x[i])px.size(0)\text{loss}(x, y) = \frac{\sum_i \max(0, \text{margin} - x[y] + x[i])^p}{\text{x.size}(0)}

其中 i{0,  ,  x.size(0)1}i \in \left\{0, \; \cdots , \; \text{x.size}(0) - 1\right\}iyi \neq y.

另外,你可以通过在构造函数中传入一个一维的 weight 张量来为类别设置不同的权重。

那么损失函数变为

loss(x,y)=iw[y]max(0,marginx[y]+x[i])px.size(0)\text{loss}(x, y) = \frac{\sum_i w[y] * \max(0, \text{margin} - x[y] + x[i])^p}{\text{x.size}(0)}
参数
  • p (int, optional) – 默认为 11。 只支持 1122

  • margin (float, optional) – 默认为 11

  • weight (Tensor, optional) – 指定给每个类别的手动缩放权重。如果提供,它必须是一个大小为 C 的张量。否则,它被视为所有类别权重为一。

  • size_average (bool, optional) – 已弃用 (参见 reduction)。 默认情况下,损失在批次中的每个损失元素上取平均值。请注意,对于某些损失,每个样本有多个元素。如果 size_average 字段设置为 False,则损失将对每个小批次求和。当 reduceFalse 时忽略。 默认值: True

  • reduce (bool, optional) – 已弃用 (参见 reduction)。 默认情况下,损失根据 size_average 的设置,在每个小批次的观测值上取平均值或求和。当 reduceFalse 时,则返回每个批次元素的损失,并忽略 size_average。 默认值: True

  • reduction (str, optional) – 指定应用于输出的约简方式:'none' | 'mean' | 'sum''none':不进行约简,'mean':输出的总和将除以输出中的元素数量,'sum':将对输出进行求和。注意:size_averagereduce 正在被弃用,在此期间,指定这两个参数中的任何一个都将覆盖 reduction。 默认值: 'mean'

形状
  • 输入: (N,C)(N, C)(C)(C),其中 NN 是批次大小,CC 是类别数量。

  • 目标: (N)(N)()(),其中每个值满足 0targets[i]C10 \leq \text{targets}[i] \leq C-1.

  • 输出:标量。如果 reduction'none',则形状与目标相同。

示例

>>> loss = nn.MultiMarginLoss()
>>> x = torch.tensor([[0.1, 0.2, 0.4, 0.8]])
>>> y = torch.tensor([3])
>>> # 0.25 * ((1-(0.8-0.1)) + (1-(0.8-0.2)) + (1-(0.8-0.4)))
>>> loss(x, y)
tensor(0.32...)