Skip to content

_hinge

hinge

Calculate the hinge loss between two tensors.

This method can be used with TensorFlow tensors:

true = tf.constant([[-1,1,1,-1], [1,1,1,1], [-1,-1,1,-1], [1,-1,-1,-1]])
pred = tf.constant([[0.1,0.9,0.05,0.05], [0.1,-0.2,0.0,-0.7], [0.0,0.15,0.8,0.05], [1.0,-1.0,-1.0,-1.0]])
b = fe.backend.hinge(y_pred=pred, y_true=true)  # [0.8  1.2  0.85 0.  ]

This method can be used with PyTorch tensors:

true = torch.tensor([[-1,1,1,-1], [1,1,1,1], [-1,-1,1,-1], [1,-1,-1,-1]])
pred = torch.tensor([[0.1,0.9,0.05,0.05], [0.1,-0.2,0.0,-0.7], [0.0,0.15,0.8,0.05], [1.0,-1.0,-1.0,-1.0]])
b = fe.backend.hinge(y_pred=pred, y_true=true)  # [0.8  1.2  0.85 0.  ]

Parameters:

Name Type Description Default
y_true Tensor

Ground truth class labels which should take values of 1 or -1.

required
y_pred Tensor

Prediction score for each class, with a shape like y_true. dtype: float32 or float16.

required

Returns:

Type Description
Tensor

The hinge loss between y_true and y_pred

Raises:

Type Description
ValueError

If y_pred is an unacceptable data type.

Source code in fastestimator/fastestimator/backend/_hinge.py
def hinge(y_true: Tensor, y_pred: Tensor) -> Tensor:
    """Calculate the hinge loss between two tensors.

    This method can be used with TensorFlow tensors:
    ```python
    true = tf.constant([[-1,1,1,-1], [1,1,1,1], [-1,-1,1,-1], [1,-1,-1,-1]])
    pred = tf.constant([[0.1,0.9,0.05,0.05], [0.1,-0.2,0.0,-0.7], [0.0,0.15,0.8,0.05], [1.0,-1.0,-1.0,-1.0]])
    b = fe.backend.hinge(y_pred=pred, y_true=true)  # [0.8  1.2  0.85 0.  ]
    ```

    This method can be used with PyTorch tensors:
    ```python
    true = torch.tensor([[-1,1,1,-1], [1,1,1,1], [-1,-1,1,-1], [1,-1,-1,-1]])
    pred = torch.tensor([[0.1,0.9,0.05,0.05], [0.1,-0.2,0.0,-0.7], [0.0,0.15,0.8,0.05], [1.0,-1.0,-1.0,-1.0]])
    b = fe.backend.hinge(y_pred=pred, y_true=true)  # [0.8  1.2  0.85 0.  ]
    ```

    Args:
        y_true: Ground truth class labels which should take values of 1 or -1.
        y_pred: Prediction score for each class, with a shape like y_true. dtype: float32 or float16.

    Returns:
        The hinge loss between `y_true` and `y_pred`

    Raises:
        ValueError: If `y_pred` is an unacceptable data type.
    """
    y_true = cast(y_true, dtype=y_pred)
    return reduce_mean(clip_by_value(1.0 - y_true * y_pred, min_value=0), axis=-1)