mindspore.nn.TripletMarginLoss

查看源文件
class mindspore.nn.TripletMarginLoss(p=2, swap=False, eps=1e-06, reduction='mean', margin=1.0)[源代码]

执行三元组损失函数的操作。

三元组损失值通常用来测量样本之间的相似度,由一个三元组和一个大于 \(0\)\(margin\) 计算得到。 其中,三元组由下面公式中的 \(a\)\(p\)\(n\) 组成。

所有输入Tensor的shape都应该为 \((N, *)\) ,其中 \(N\) 代表批处理的数量, \(*\) 代表任意数量的附加维度。 距离交换在V. Balntas、E. Riba等人在论文 Learning local feature descriptors with triplets and shallow convolutional neural networks 中有详细的阐述。

对于每个小批量样本,损失值为:

\[L(a, p, n) = \max \{d(a_i, p_i) - d(a_i, n_i) + {\rm margin}, 0\}\]

其中

\[d(x_i, y_i) = \left\lVert {\bf x}_i - {\bf y}_i \right\rVert_p\]
参数:
  • p (int,可选) - 成对距离的范数。默认值: 2

  • swap (bool,可选) - 距离交换。默认值: False

  • eps (float,可选) - 防止除数为 0。默认值: 1e-06

  • reduction (str,可选) - 指定应用于输出结果的规约计算方式,可选 'none''mean''sum' ,默认值: 'mean'

    • "none":不应用规约方法。

    • "mean":计算输出元素的平均值。

    • "sum":计算输出元素的总和。

  • margin (Union[Tensor, float]) - 用于拉进 xpositive 之间的距离,拉远 xnegative 之间的距离。默认值: 1.0

输入:
  • x (Tensor) - 从训练集随机选取的样本。数据类型为BasicType。即上述公式中的 \(a\)

  • positive (Tensor) - 与 x 为同一类的样本,数据类型与shape与 x 一致。即上述公式中的 \(p\)

  • negative (Tensor) - 与 x 为异类的样本,数据类型与shape与 x 一致。即上述公式中的 \(n\)

  • margin (Union[Tensor, float]) - 用于拉进 xpositive 之间的距离,拉远 xnegative 之间的距离。默认值: 1.0

输出:

Tensor。如果 reduction 为”none”,其shape为 \((N)\)。否则,将返回Scalar。

异常:
  • TypeError - xpositivenegative 不是Tensor。

  • TypeError - xpositive 或者 negative 的数据类型不一致。

  • TypeError - p 的数据类型不是int。

  • TypeError - eps 的数据类型不是float。

  • TypeError - swap 的数据类型不是bool。

  • ValueError - xpositivenegative 的维度同时小于等于1。

  • ValueError - xpositivenegative 的维度大于等于8。

  • ValueError - margin 的shape长度不为0。

  • ValueError - xpositivenegative 三者之间的shape无法广播。

  • ValueError - reduction 不为 "mean""sum""none"

支持平台:

GPU

样例:

>>> import mindspore as ms
>>> import mindspore.nn as nn
>>> import numpy as np
>>> loss = nn.TripletMarginLoss()
>>> x = ms.Tensor(np.array([[0.3, 0.7], [0.5, 0.5]]), ms.float32)
>>> positive = ms.Tensor(np.array([[0.4, 0.6], [0.4, 0.6]]), ms.float32)
>>> negative = ms.Tensor(np.array([[0.2, 0.9], [0.3, 0.7]]), ms.float32)
>>> output = loss(x, positive, negative)
>>> print(output)
0.8881968