megengine.functional.nn.hinge_loss

hinge_loss(pred, label, norm='L1', reduction='mean')[源代码]

Caculates the hinge loss which is often used in SVM.

The hinge loss can be described as:

\[loss(x, y) = \frac{1}{N}\sum_i\sum_j(max(0, 1 - x_{ij}*y_{ij}))\]
参数
  • pred (Tensor) – input tensor representing the predicted probability, shape is (N, C).

  • label (Tensor) – input tensor representing the binary classification label, shape is (N, C).

  • norm (str) – specify the norm to caculate the loss, should be “L1” or “L2”.

  • reduction (str) – the reduction to apply to the output: ‘none’ | ‘mean’ | ‘sum’. Default: ‘mean’

返回类型

Tensor

返回

loss value.

实际案例

from megengine import tensor
import megengine.functional as F

pred = tensor([[0.5, -0.5, 0.1], [-0.6, 0.7, 0.8]], dtype="float32")
label = tensor([[1, -1, -1], [-1, 1, 1]], dtype="float32")
loss = F.nn.hinge_loss(pred, label)
print(loss.numpy())

Outputs:

1.5