The binary hinge loss is computed in the following steps. As an example, take four examples with labels y=(+1,Β +1,Β β1,Β β1) and model scores f(x)=(2.0,Β 0.5,Β β0.3,Β 1.5).
- Compute the margin ziβ=yiβf(xiβ) for each example. Here z=(2.0,Β 0.5,Β 0.3,Β β1.5). The fourth has the wrong sign, so it is misclassified.
- Take the larger of 1βziβ and 0. Here this gives (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.
- Average over the number of examples. Here (0+0.5+0.7+2.5)/4=0.925.
The gradient (strictly, the subgradient) with respect to the score f(x) is:
βf(x)ββhingeββ={βy0β(yf(x)<1)(yf(x)>1)β
At z=1 the function has a kink and is not differentiable, so any value between βy and 0 is used (most implementations use 0).
Relation to the SVM: Soft-margin training of a linear SVM (f(x)=wβ€x+b) can be written with per-example violations ΞΎiββ₯0 as follows.
w,b,ΞΎminβΒ 21ββ₯wβ₯2+CiββΞΎiβs.t.yiβ(wβ€xiβ+b)β₯1βΞΎiβ,Β Β ΞΎiββ₯0
At the optimum, ΞΎiβ=max(0,Β 1βyiβf(xiβ)), so this is equivalent to minimizing "the sum of hinge losses + a β₯wβ₯2 penalty, the same as Weight Decay." C is a constant that sets how much violation is tolerated.
Extension to multiple classes: With K classes, a common form sums the amounts by which the score syβ of the correct class y fails to exceed each other class's score sjβ by at least the margin. PyTorch's nn.MultiMarginLoss is the following formula, divided by the number of classes K (the margin defaults to 1).
β=K1βjξ =yββmax(0,Β marginβsyβ+sjβ)
Squaring the linear part gives max(0,Β 1βz)2, called the squared hinge loss. It is smoothly differentiable even at z=1 and penalizes examples that fall well inside the margin more heavily. An SVM using it is called an L2-SVM.