评价此页

HingeEmbeddingLoss#

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

衡量给定输入张量 xx 和标签张量 yy(包含 1 或 -1)时的损失。这通常用于衡量两个输入是相似还是不相似,例如,将 L1 对距离用作 xx,并且通常用于学习非线性嵌入或半监督学习。

mini-batch 中第 nn 个样本的损失函数为

ln={xn,if  yn=1,max{0,marginxn},if  yn=1,l_n = \begin{cases} x_n, & \text{if}\; y_n = 1,\\ \max \{0, margin - x_n\}, & \text{if}\; y_n = -1, \end{cases}

总损失函数为

(x,y)={mean(L),if reduction=‘mean’;sum(L),if reduction=‘sum’.\ell(x, y) = \begin{cases} \operatorname{mean}(L), & \text{if reduction} = \text{`mean';}\\ \operatorname{sum}(L), & \text{if reduction} = \text{`sum'.} \end{cases}

其中 L={l1,,lN}L = \{l_1,\dots,l_N\}^\top

参数:
  • margin (float, 可选) – 默认值为 1

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

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

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

形状
  • 输入:()(*) 其中 * 表示任意数量的维度。求和操作作用于所有元素。

  • 目标:()(*),与输入形状相同

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

示例

>>> loss = nn.HingeEmbeddingLoss()
>>> input = torch.randn(3, 5, requires_grad=True)
>>> target = torch.randn(3, 5).sign()
>>> output = loss(input, target)
>>> output.backward()
forward(input, target)[source]#

执行前向传播。

返回类型:

张量