soft_margin_loss

paddle.nn.functional. soft_margin_loss ( input, label, reduction='mean', name=None ) [源代码]

计算输入 inputlabel 间的二分类损失。

损失函数按照下列公式计算

\[\text{loss}(x, y) = \sum_i \frac{\log(1 + \exp(-y[i]*x[i]))}{\text{x.nelement}()}\]

最后,添加 reduce 操作到前面的输出 Out 上。当 reductionnone 时,直接返回最原始的 Out 结果。当 reductionmean 时,返回输出的均值 \(Out = MEAN(Out)\) 。当 reductionsum 时,返回输出的求和 \(Out = SUM(Out)\)

参数

  • input (Tensor) - \([N, *]\) ,其中 N 是 batch_size, * 是任意其他维度。数据类型是 float32、float64。

  • label (Tensor) - \([N, *]\) ,标签 label 的维度、数据类型与输入 input 相同。

  • reduction (str,可选) - 指定应用于输出结果的计算方式,可选值有: 'none''mean''sum' 。默认为 'mean',计算 Loss 的均值;设置为 'sum' 时,计算 Loss 的总和;设置为 'none' 时,则返回原始 Loss。

  • name (str,可选) - 操作的名称(可选,默认值为 None)。更多信息请参见 Name

返回

  • 输出的结果 Tensor。如果 reduction'none', 则输出的维度为 \([N, *]\) ,与输入 input 的形状相同。如果 reduction'mean''sum',则输出的维度为 \([1]\)

代码示例

import paddle

input = paddle.to_tensor([[0.5, 0.6, 0.7],[0.3, 0.5, 0.2]], 'float32')
label = paddle.to_tensor([[1.0, -1.0, 1.0],[-1.0, 1.0, 1.0]], 'float32')
output = paddle.nn.functional.soft_margin_loss(input, label)
print(output)
# Tensor(shape=[1], dtype=float32, place=Place(gpu:0), stop_gradient=True,
#        [0.64022040])

input = paddle.uniform(shape=(5, 5), dtype="float32", min=0.1, max=0.8)
label = paddle.randint(0, 2, shape=(5, 5), dtype="int64")
label[label==0]=-1

output = paddle.nn.functional.soft_margin_loss(input, label, reduction='none')
print(output)
# Tensor(shape=[5, 5], dtype=float32, place=Place(gpu:0), stop_gradient=True,
#        [[1.09917796, 0.52613139, 0.56263304, 0.82736146, 0.38776723],
#         [1.07179427, 1.11924267, 0.49877715, 1.10026348, 0.46184641],
#         [0.84367639, 0.74795729, 0.44629076, 0.55123353, 0.77659678],
#         [0.39465919, 0.76651484, 0.54485321, 0.76609844, 0.77166790],
#         [0.51283568, 0.84757161, 0.78913331, 1.05268764, 0.45318675]])