评价此页

MultiLabelMarginLoss#

class torch.nn.modules.loss.MultiLabelMarginLoss(size_average=None, reduce=None, reduction='mean')[源码]#

创建一个标准,用于优化输入 xx(一个 2D 小批量 Tensor)和输出 yy(一个 2D 目标类别索引 Tensor)之间的多类别多分类合页损失(基于间隔的损失)。对于小批量中的每个样本

loss(x,y)=ijmax(0,1(x[y[j]]x[i]))x.size(0)\text{loss}(x, y) = \sum_{ij}\frac{\max(0, 1 - (x[y[j]] - x[i]))}{\text{x.size}(0)}

其中 x{0,  ,  x.size(0)1}x \in \left\{0, \; \cdots , \; \text{x.size}(0) - 1\right\}, y{0,  ,  y.size(0)1}y \in \left\{0, \; \cdots , \; \text{y.size}(0) - 1\right\}, 0y[j]x.size(0)10 \leq y[j] \leq \text{x.size}(0)-1, and iy[j]i \neq y[j] for all ii and jj.

yy and xx must have the same size。

该标准仅考虑从头开始的连续非负目标块。

这允许不同的样本具有可变数量的目标类别。

参数:
  • 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'

形状
  • Input: (C)(C)(N,C)(N, C),其中 N 是批量大小,C 是类别数。

  • Target: (C)(C)(N,C)(N, C),标签目标用 -1 填充,以确保形状与输入相同。

  • 输出:标量。如果 reduction'none',则为 (N)(N)

示例

>>> loss = nn.MultiLabelMarginLoss()
>>> x = torch.FloatTensor([[0.1, 0.2, 0.4, 0.8]])
>>> # for target y, only consider labels 3 and 0, not after label -1
>>> y = torch.LongTensor([[3, 0, -1, 1]])
>>> # 0.25 * ((1-(0.1-0.2)) + (1-(0.1-0.4)) + (1-(0.8-0.2)) + (1-(0.8-0.4)))
>>> loss(x, y)
tensor(0.85...)
forward(input, target)[源码]#

执行前向传播。

返回类型:

张量