评价此页

MultiMarginLoss#

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

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

对于每个 mini-batch 样本,1D 输入 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 的张量。否则,假定其所有元素为 1。

  • 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 是 batch size,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...)
forward(input, target)[源代码]#

执行前向传播。

返回类型

张量