Sign in

Hinge

Hinge loss (maximum margin loss)

A margin loss for labels of minus one and plus one: zero once the score is on the correct side by at least the margin, linear in the shortfall otherwise.

Overview

Hinge loss cares about being right with room to spare. The label is +1+1 or −1-1 and the model outputs a score whose sign is the prediction. If the score has the right sign and a size of at least the margin, the loss is exactly zero and the example is ignored. If the score falls short, the loss is the size of the shortfall. Only examples near or on the wrong side of the boundary influence training. This is the loss behind support vector machines, and those few influential examples are the support vectors.

A short history

Hinge loss is the loss behind the support vector machine. Corinna Cortes and Vladimir Vapnik introduced the soft-margin form in 1995, building on Vapnik's earlier work on maximum margin classifiers with Bernhard Boser and Isabelle Guyon. It penalises only examples that are misclassified or inside the margin, so the solution depends on a small set of support vectors. SVMs were the leading classifiers for text and many other tasks until deep networks took over.

How it works

  1. Take a raw score ss and a label yy of −1-1 or +1+1 for each element.
  2. Compute y⋅sy \cdot s. It is positive when the sign is right, and larger means more confident.
  3. Compute the shortfall max⁡(0,m−ys)\max(0, m - y s), where mm is the margin.
  4. The loss is the shortfall, or its square when squared is on.
  5. Reduce over all elements with reduction.
  6. In backward, elements that fall short get the gradient −y-y (times twice the shortfall when squared). Elements that clear the margin get zero.

Watch out for

  • Labels must be −1-1 and +1+1. The template raises a ValueError for 0 and 1 labels, which would otherwise silently treat every negative as having no effect.
  • The score is not a probability. To get one you must calibrate it afterwards.
  • The plain hinge has a corner at the margin, so the gradient jumps there. The squared option is smooth but punishes outliers much more.
  • Once every example clears the margin the gradient is zero. Without a weight penalty, nothing then pushes the model to prefer a wider margin.

Use cases

When to use it

Maximum-margin classifiers such as linear SVMs, and any binary task where you want a clear separation and do not need probability estimates.

In industry

Text classification
Linear SVMs trained with hinge loss on word count features are a long-standing baseline for sorting documents and filtering spam.
Image generation
Several GANs, including SAGAN and BigGAN, train the discriminator with a hinge version of the adversarial loss.
Bioinformatics
Support vector machines have been widely used to classify tissue samples from gene expression data, where features far outnumber samples.

Choosing it: what must hold

  • Binary labels coded as minus one and plus one, or a multi-class variant of the loss.
  • A need for a decision, not a probability: the raw score is not calibrated.
  • Features on comparable scales, with regularisation on the weights so the margin is meaningful.

When to choose something else

IfUse instead
You need a probability for each predictionBinary cross-entropy
There are several classes and a neural networkSoftmax cross-entropy
You are learning embeddings from relative comparisonsTriplet loss

Math foundations

  1. The loss for one element

    ℓ(s,y)=max⁡(0,  m−y s)\ell(s, y) = \max(0,\; m - y\,s)

    Zero when the signed score ysy s is at least the margin mm. Otherwise it is the amount by which the score falls short.

  2. The squared hinge

    ℓsq(s,y)=max⁡(0,  m−y s)2\ell_{\text{sq}}(s, y) = \max(0,\; m - y\,s)^{2}

    Smooth at the margin, with a gradient that grows with the shortfall. It penalises large violations more heavily.

  3. The subgradient

    ∂ℓ∂s={−y,y s<m0,y s≥m\frac{\partial \ell}{\partial s} = \begin{cases} -y, & y\,s < m \\ 0, & y\,s \ge m \end{cases}

    A constant push in the direction of the label for every violating example, however bad the violation. At the corner the template uses 0.

  4. Gradient of the squared hinge

    ∂ℓsq∂s=−2 y max⁡(0,  m−y s)\frac{\partial \ell_{\text{sq}}}{\partial s} = -2\,y\,\max(0,\; m - y\,s)

    The push is proportional to the shortfall, and it fades smoothly to zero at the margin.

  5. The SVM objective it comes from

    min⁡w,b    λ2∥w∥2+1n∑i=1nmax⁡ ⁣(0,  1−yi (w⊤xi+b))\min_{w, b}\;\; \frac{\lambda}{2}\lVert w \rVert^{2} + \frac{1}{n}\sum_{i=1}^{n}\max\!\big(0,\; 1 - y_i\,(w^{\top}x_i + b)\big)

    Hinge loss plus an L2 penalty on the weights. The penalty is what turns clearing the margin into making the margin wide. The template supplies the second term only.

Symbols

ss
the raw score for one element, score
yy
the label, -1 or +1
mm
the margin, margin in the config, default 1
ℓ,ℓsq\ell, \ell_{\text{sq}}
the hinge loss and the squared hinge loss for one element
w,bw, b
weights and bias of a linear classifier
xi,yix_i, y_i
the i-th training input and its label
λ\lambda
strength of the L2 penalty
nn
the number of training examples

Worked by hand

Margin m=1m = 1. Three cases: label +1+1 with score 1.5, label +1+1 with score 0.3, and label −1-1 with score 0.3.

max⁡(0,  1−(+1)(1.5))=max⁡(0,−0.5)=0\max(0,\; 1 - (+1)(1.5)) = \max(0, -0.5) = 0
max⁡(0,  1−(+1)(0.3))=0.7\max(0,\; 1 - (+1)(0.3)) = 0.7
max⁡(0,  1−(−1)(0.3))=1.3\max(0,\; 1 - (-1)(0.3)) = 1.3
mean=0+0.7+1.33=0.6667\text{mean} = \frac{0 + 0.7 + 1.3}{3} = 0.6667

The first example clears the margin and costs nothing. The second is correct but too close, costing 0.7. The third is wrong and costs 1.3.

Visual example

Loading the example.

Try this

  • Move across the curve: the height is what the model is charged.
  • Move each control and watch which part of the curve it changes.

Code sample

import numpy as np
from impl import HingeLoss
from config import HingeLossConfig

loss = HingeLoss(HingeLossConfig(margin=1.0))
score = np.array([2.0, 0.5, -1.0, -3.0])       # raw classifier scores
label = np.array([1.0, 1.0, 1.0, -1.0])        # -1 or +1
print(loss.forward(score, label))              # (0 + 0.5 + 2 + 0) / 4 = 0.625
print(loss.backward(score, label))             # [0, -0.25, -0.25, 0]
Read the implementation (66 lines)
"""Hinge loss for labels in {-1, +1}: max(0, margin - y * score), optionally squared.

NumPy only. `forward` returns the loss, `backward` its (sub)gradient with respect to the score.
"""
from __future__ import annotations

import numpy as np

try:
    from .config import HingeLossConfig
except ImportError:  # run from the template's own folder
    from config import HingeLossConfig

def _pair(pred, target) -> tuple[np.ndarray, np.ndarray]:
    """Both inputs as float arrays of one shape. Raises ValueError when the shapes differ."""
    pred, target = np.asarray(pred, dtype=float), np.asarray(target, dtype=float)
    if pred.shape != target.shape:
        raise ValueError(f"pred and target must have the same shape, got {pred.shape} and {target.shape}")
    return pred, target


def _reduce(values: np.ndarray, reduction: str):
    """Reduce per-element losses: "mean" and "sum" give a float, "none" returns the array unchanged."""
    if reduction == "mean":
        return float(values.mean())
    if reduction == "sum":
        return float(values.sum())
    return values


def _grad_scale(count: int, reduction: str) -> float:
    """Factor the reduction puts on every per-element gradient: 1 / count for "mean", otherwise 1."""
    return 1.0 / count if reduction == "mean" else 1.0


class HingeLoss:
    """max(0, margin - y * score), or its square, for labels y in {-1, +1}."""

    def __init__(self, config: HingeLossConfig | None = None) -> None:
        self.config = config or HingeLossConfig()

    def _shortfall(self, score: np.ndarray, target: np.ndarray) -> np.ndarray:
        """How far each score falls short of the margin, 0 when it clears it. Raises on labels other than +-1."""
        if not np.isin(target, (-1.0, 1.0)).all():
            raise ValueError("target must hold only -1 and +1")
        return np.maximum(0.0, self.config.margin - target * score)

    def forward(self, score: np.ndarray, target: np.ndarray):
        """score: raw scores, any shape. target: same shape, -1 or +1.
        Returns a float, or the per-element array for "none"."""
        score, target = _pair(score, target)
        short = self._shortfall(score, target)
        return _reduce(short**2 if self.config.squared else short, self.config.reduction)

    def backward(self, score: np.ndarray, target: np.ndarray) -> np.ndarray:
        """Subgradient of the reduced loss with respect to the score, same shape as the score.

        Per element: -y where the score falls short of the margin (times twice the shortfall when squared),
        0 where it clears it, the kink included. For "none" it is returned unscaled (the gradient of the sum).
        """
        score, target = _pair(score, target)
        short = self._shortfall(score, target)
        local = -2.0 * target * short if self.config.squared else -target * (short > 0)
        return local * _grad_scale(score.size, self.config.reduction)

    __call__ = forward
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
7, run with python3 -m unittest -v

Practice

Build HingeLoss(HingeLossConfig(margin=1.0, reduction="none")) and evaluate forward and backward on scores from -2 to 3 with all targets +1. Repeat with squared=True and compare both the loss and the gradient at a score of -2 and at a score of 0.99.

Check on learning

  1. A correctly classified example with score 0.3 still has a loss of 0.7. Why penalise a correct prediction?
    A way to think about it

    Think about what happens to that example when the input is slightly perturbed. A margin asks for answers that stay correct under small changes.

  2. Cross-entropy never reaches zero for any finite score. Hinge loss does. What does that difference mean for which examples shape the final model?
    A way to think about it

    With hinge, well-classified examples drop out entirely. With cross-entropy, every example keeps pulling a little. Consider robustness to far-away points.

  3. On linearly separable data with no weight penalty, many different boundaries give zero hinge loss. Which one does training find, and what would make the choice principled?
    A way to think about it

    With zero loss everywhere the gradient vanishes, so training stops wherever it first gets there. Look at the first term of the SVM objective.

  4. One training point is far on the wrong side because of a labelling error. Compare its influence under hinge and under squared hinge.
    A way to think about it

    Compute the gradient size in each case for a shortfall of 10. One is constant, the other grows in proportion to the shortfall.