mlx.nn.losses.margin_ranking_loss

mlx.nn.losses.margin_ranking_loss#

class margin_ranking_loss(inputs1: array, inputs2: array, targets: array, margin: float = 0.0, reduction: Literal['none', 'mean', 'sum'] = 'none')#

給定輸入 \(x_1\)\(x_2\) 與標籤 :math:`y`(包含 1 或 -1),計算 margin ranking 損失。

The loss is given by:

\[\text{loss} = \max (0, -y * (x_1 - x_2) + \text{margin})\]

Where \(y\) represents targets, \(x_1\) represents inputs1 and \(x_2\) represents inputs2.

參數:
  • inputs1 (array) -- Scores for the first input.

  • inputs2 (array) -- Scores for the second input.

  • targets (array) -- Labels indicating whether samples in inputs1 should be ranked higher than samples in inputs2. Values should be 1 or -1.

  • margin (float, optional) -- The margin by which the scores should be separated. Default: 0.0.

  • reduction (str, optional) -- Specifies the reduction to apply to the output: 'none' | 'mean' | 'sum'. Default: 'none'.

回傳:

The computed margin ranking loss.

回傳型別:

array

範例

>>> import mlx.core as mx
>>> import mlx.nn as nn
>>> targets = mx.array([1, 1, -1])
>>> inputs1 = mx.array([-0.573409, -0.765166, -0.0638])
>>> inputs2 = mx.array([0.75596, 0.225763, 0.256995])
>>> loss = nn.losses.margin_ranking_loss(inputs1, inputs2, targets)
>>> loss
array(0.773433, dtype=float32)