AI Logic

Loss Functions

Hinge Loss

Updated:

Graph of the hinge loss. The horizontal axis is the margin z = y Β· f(x) and the vertical axis is the loss, overlaying the hinge loss max(0, 1 βˆ’ z) (solid), the logistic loss log2(1 + e^βˆ’z) (dashed), and the 0-1 loss (dotted). The hinge loss is 1 at z = 0 and 0 from z = 1 onward. Legend on the right

Background and Overview

The hinge loss is a loss function that penalizes a classification score by the amount it falls short of being "correct with room to spare." For binary classification, with the ground-truth label y∈{βˆ’1,Β +1}y \in \{-1,\ +1\} and the model output (score) f(x)f(x), it is written as follows.

β„“hinge(y,f(x))=max⁑(0,Β 1βˆ’yf(x))\ell_{\text{hinge}}(y, f(x)) = \max\bigl(0,\ 1 - y f(x)\bigr)

z=yf(x)z = y f(x) is called the margin; it is positive when the example is classified correctly and negative when it is misclassified. The larger zz is, the farther the example is from the boundary and the more confidently it is classified correctly.

As the figure at the top shows, the hinge loss is exactly 0 for zβ‰₯1z \ge 1 and increases linearly as 1βˆ’z1 - z for z<1z < 1. Its shape resembles the hinge of a half-open door, hence the name.

The loss originated in training support vector machines (SVMs). Cortes and Vapnik (1995) proposed the "soft-margin" SVM, which finds a boundary for data that cannot be separated into two groups without error by introducing variables that measure how far each example violates the margin. That violation is exactly the hinge loss.

What one really wants to minimize is the number of misclassifications (the 0-1 loss), but the 0-1 loss is a step function with no gradient and cannot be optimized directly. The hinge loss replaces it with a convex function that upper-bounds the 0-1 loss (a surrogate loss), which is easy to optimize.

Theory (Computing the Loss)

The binary hinge loss is computed in the following steps. As an example, take four examples with labels y=(+1,Β +1,Β βˆ’1,Β βˆ’1)y = (+1,\ +1,\ -1,\ -1) and model scores f(x)=(2.0,Β 0.5,Β βˆ’0.3,Β 1.5)f(x) = (2.0,\ 0.5,\ -0.3,\ 1.5).

  1. Compute the margin zi=yif(xi)z_i = y_i f(x_i) for each example. Here z=(2.0,Β 0.5,Β 0.3,Β βˆ’1.5)z = (2.0,\ 0.5,\ 0.3,\ -1.5). The fourth has the wrong sign, so it is misclassified.
  2. Take the larger of 1βˆ’zi1 - z_i and 0. Here this gives (0,Β 0.5,Β 0.7,Β 2.5)(0,\ 0.5,\ 0.7,\ 2.5). The first has enough room, so its loss is 0; the second and third are classified correctly but without enough room, so they incur a loss.
  3. Average over the number of examples. Here (0+0.5+0.7+2.5)/4=0.925(0 + 0.5 + 0.7 + 2.5) / 4 = 0.925.

The gradient (strictly, the subgradient) with respect to the score f(x)f(x) is:

βˆ‚β„“hingeβˆ‚f(x)={βˆ’y(yf(x)<1)0(yf(x)>1)\frac{\partial \ell_{\text{hinge}}}{\partial f(x)} = \begin{cases} -y & (y f(x) < 1) \\ 0 & (y f(x) > 1) \end{cases}

At z=1z = 1 the function has a kink and is not differentiable, so any value between βˆ’y-y and 0 is used (most implementations use 0).

Relation to the SVM: Soft-margin training of a linear SVM (f(x)=w⊀x+bf(x) = w^\top x + b) can be written with per-example violations ΞΎiβ‰₯0\xi_i \ge 0 as follows.

min⁑w, b, ξ 12βˆ₯wβˆ₯2+Cβˆ‘iΞΎis.t.yi(w⊀xi+b)β‰₯1βˆ’ΞΎi,Β Β ΞΎiβ‰₯0\min_{w,\, b,\, \xi}\ \frac{1}{2}\lVert w \rVert^2 + C \sum_{i} \xi_i \quad \text{s.t.}\quad y_i (w^\top x_i + b) \ge 1 - \xi_i,\ \ \xi_i \ge 0

At the optimum, ΞΎi=max⁑(0,Β 1βˆ’yif(xi))\xi_i = \max(0,\ 1 - y_i f(x_i)), so this is equivalent to minimizing "the sum of hinge losses + a βˆ₯wβˆ₯2\lVert w \rVert^2 penalty, the same as Weight Decay." CC is a constant that sets how much violation is tolerated.

Extension to multiple classes: With KK classes, a common form sums the amounts by which the score sys_y of the correct class yy fails to exceed each other class's score sjs_j by at least the margin. PyTorch's nn.MultiMarginLoss is the following formula, divided by the number of classes KK (the margin defaults to 1).

β„“=1Kβˆ‘jβ‰ ymax⁑(0,Β marginβˆ’sy+sj)\ell = \frac{1}{K} \sum_{j \ne y} \max\bigl(0,\ \text{margin} - s_y + s_j\bigr)

Squaring the linear part gives max⁑(0,Β 1βˆ’z)2\max(0,\ 1 - z)^2, called the squared hinge loss. It is smoothly differentiable even at z=1z = 1 and penalizes examples that fall well inside the margin more heavily. An SVM using it is called an L2-SVM.

Why It Focuses on Examples Near the Boundary

The key property of the hinge loss is that the loss and gradient of examples with zβ‰₯1z \ge 1 are exactly 0.

  • Examples classified correctly with room to spare do not affect training: No matter how much the score of the first example above increases, its loss stays 0 and it produces no gradient. Training proceeds using only the examples inside the margin and the misclassified ones.
  • Only examples near the boundary determine it: In an SVM, the examples on or inside the margin are called support vectors, and the final boundary is determined by them alone. Because the loss has a region where it is 0, many examples drop out of the boundary decision, making the solution sparse.
  • Difference from the logistic loss: Cross-entropy (the logistic loss log⁑(1+eβˆ’z)\log(1 + e^{-z}) in the binary case) never reaches 0 however large zz is, so a small gradient always remains. It therefore keeps pushing the probability of already-correct examples even closer to 1.

As an analogy, think of an exam with a passing score (margin 1). The hinge loss says nothing to students above the passing score and coaches only those below it, in proportion to the points they are missing. Cross-entropy keeps telling even students near a perfect score to "push a little higher."

Even though the margin is fixed at 1, combining it with the βˆ₯wβˆ₯2\lVert w \rVert^2 penalty selects the boundary that satisfies zβ‰₯1z \ge 1 while keeping the weights small, that is, the boundary that maximizes the distance (margin) to the closest examples. This is considered the reason SVMs generalize well.

Experimental Results

Tang (2013) replaced the final softmax and cross-entropy of deep classification networks with a linear SVM (one-vs-rest, training one SVM per class, with the squared hinge loss) and compared the two. The lower layers are trained by backpropagation of the gradient from the SVM loss.

Dataset / metricSoftmax + cross-entropyLinear SVM (squared hinge loss)
Facial expression recognition (ICML 2013 competition) / accuracy, 8-fold cross-validation67.6%68.9%
Facial expression recognition / accuracy, final leaderboard (private test data)70.1%71.2%
MNIST / error rate (fully connected network)0.99%0.87%
CIFAR-10 / error rate (convolutional network)14.0%11.9%

The paper reports that the squared hinge loss (L2-SVM) was usually slightly better than the hinge loss (L1-SVM) and uses the squared hinge loss in its experiments. It also argues that the improvement is likely due to the regularization effect of the SVM loss rather than to better optimization.

These comparisons come from small networks in which only the loss of the last layer was changed. Weight decay and learning rate were chosen separately for each model. The paper does not show whether the same gap would appear in today's large models or on other tasks.

Practical Considerations

For the binary hinge loss, use labels +1+1 and βˆ’1-1. If 0/1 labels are plugged directly into max⁑(0,Β 1βˆ’yf(x))\max(0,\ 1 - y f(x)), the loss of every example with y=0y = 0 is always 1 regardless of its score, and that class is never learned.

Keep the following points in mind as well.

  • The output is not a probability: There is no basis for interpreting scores trained with the hinge loss as probabilities. When probabilities are needed, methods such as Platt scaling, which learns a mapping that passes the scores through a sigmoid function on validation data, are used, but the resulting probabilities are not considered very accurate. If you want to use probabilities directly, choose cross-entropy.
  • Not differentiable at z=1z = 1: Gradient methods can train with the subgradient, but because the loss curve has a kink, a large learning rate tends to make training oscillate around the boundary. If smoothness is needed, use the squared hinge loss.
  • PyTorch's nn.HingeEmbeddingLoss is something else: Despite the similar name, it takes a distance xx between two inputs and uses xx as the loss for similar pairs and max⁑(0,Β marginβˆ’x)\max(0,\ \text{margin} - x) for dissimilar pairs; it is not the classification hinge loss. Write the binary hinge loss as torch.clamp(1 - y * f, min=0) and use nn.MultiMarginLoss for multiple classes.
  • Pair it with a weight penalty: The margin-maximizing property of the SVM comes only with the βˆ₯wβˆ₯2\lVert w \rVert^2 penalty. When using it in neural networks, tune the strength of weight decay as well (it corresponds to the SVM's CC).

Comparison with Other Loss Functions

The table below compares the hinge loss with other binary classification losses, viewed as functions of the margin z=yf(x)z = y f(x).

Loss functionLossDerivative at z=1z = 1Loss for z>1z > 1Output usable as a probabilityMain uses
0-1 loss1 for z<0z < 0, otherwise 0β€” (no gradient)0β€”Evaluation (error rate)
Hinge lossmax⁑(0,Β 1βˆ’z)\max(0,\ 1 - z)Not differentiable (kink)0NoSVMs, margin-oriented classification
Squared hinge lossmax⁑(0,Β 1βˆ’z)2\max(0,\ 1 - z)^2Differentiable0NoL2-SVM, when smoothness is needed
Logistic loss (cross-entropy)log⁑(1+eβˆ’z)\log(1 + e^{-z})DifferentiableClose to 0 but positiveYesStandard for neural network classification

Rough guidelines for choosing among them:

  • For neural network classification, start with cross-entropy: It produces probabilities, is smooth everywhere, and extends directly to multiple classes.
  • Use the hinge loss when you want training to focus on examples near the boundary and do not need probabilities: Examples that are already well classified produce no gradient, so training concentrates on determining the boundary.
  • Use the squared hinge loss if you want to train a hinge-type loss stably with gradient methods.
  • When learning distances between embeddings, use losses that apply the hinge shape to distances: Contrastive Loss and Triplet Loss have the same form as the hinge loss, penalizing only the amount by which a distance gap falls short of the margin.

PyTorch example

Show code
python
import torch
import torch.nn as nn

# Binary: labels are +1 / βˆ’1; f is the model output (score)
y = torch.tensor([1.0, 1.0, -1.0, -1.0])
f = torch.tensor([2.0, 0.5, -0.3, 1.5], requires_grad=True)

def hinge_loss(f, y):
    return torch.clamp(1 - y * f, min=0).mean()

def squared_hinge_loss(f, y):
    return (torch.clamp(1 - y * f, min=0) ** 2).mean()

loss = hinge_loss(f, y)
print(loss.item())        # 0.925
loss.backward()
print(f.grad)             # (0, βˆ’0.25, 0.25, 0.25): the first, with z β‰₯ 1, has zero gradient

# If you have 0 / 1 labels, convert them to +1 / βˆ’1 first
labels01 = torch.tensor([1, 1, 0, 0])
y_pm = labels01.float() * 2 - 1          # (+1, +1, βˆ’1, βˆ’1)

# Multiclass: nn.MultiMarginLoss (margin=1; p=1 is the ordinary hinge loss, p=2 the squared one)
scores = torch.tensor([[2.0, 1.5, -0.5]])   # scores for 3 classes
target = torch.tensor([0])                  # the correct class is 0
criterion = nn.MultiMarginLoss(margin=1.0, p=1)
print(criterion(scores, target).item())     # (max(0, 1 βˆ’ 2 + 1.5) + max(0, 1 βˆ’ 2 βˆ’ 0.5)) / 3 = 0.1667

# Same training as a linear SVM: hinge loss + weight penalty (weight_decay plays the role of the ||w||Β² term)
model = nn.Linear(10, 1)
optimizer = torch.optim.SGD(model.parameters(), lr=0.01, weight_decay=1e-3)
x = torch.randn(64, 10)
t = torch.randint(0, 2, (64,)).float() * 2 - 1   # labels +1 / βˆ’1
loss = hinge_loss(model(x).squeeze(1), t)
optimizer.zero_grad()
loss.backward()
optimizer.step()

FAQ

Q. Should I use the hinge loss or cross-entropy?
A.

For neural network classification, cross-entropy is the standard: it produces probabilities and is smooth everywhere. The hinge loss suits cases where probabilities are not needed and you want training to focus on examples near the boundary. Small experiments have reported slight improvements from replacing the last layer with a squared-hinge-loss SVM, but that does not guarantee improvement on every task.

Q. Why is the margin set to 1?
A.

For a linear model, scaling the score f(x) by any factor does not change the classification, so fixing the margin at 1 loses no generality. With the margin fixed at 1, making the weight norm ||w|| small corresponds to making the distance between the boundary and the closest examples large.

Q. Does PyTorch have a hinge loss class?
A.

The multiclass hinge loss is nn.MultiMarginLoss. There is no class for the binary hinge loss itself, so write torch.clamp(1 - y * f, min=0).mean(). Note that nn.HingeEmbeddingLoss is a different loss, used on the distance between two inputs.

References

  1. C. Cortes and V. Vapnik, "Support-Vector Networks," Machine Learning, 20, pp. 273–297, 1995.
  2. K. P. Murphy, "Probabilistic Machine Learning: An Introduction," MIT Press, 2022, Section 4.3.2 Surrogate loss and Section 17.3 Support vector machines.
  3. Y. Tang, "Deep Learning using Linear Support Vector Machines," ICML 2013 Workshop on Challenges in Representation Learning, 2013.
  4. PyTorch Documentation, "torch.nn.MultiMarginLoss."
  5. PyTorch Documentation, "torch.nn.HingeEmbeddingLoss."