Compute the multiclass hinge loss
Why it matters Max-margin losses are still used in reranking and contrastive training.
The SVM-style multiclass loss wants the correct score to beat every other score by a margin.
Write multiclass_hinge(S, y, margin=1.0). S is (n, k) scores, y is (n,) correct classes. For each row sum max(0, S[i, j] - S[i, y_i] + margin) over j != y_i, then return the mean over rows.
def multiclass_hinge(S, y, margin=1.0)Example
S = [[3, 1, 2.5]], y = [0] gives max(0, 1 - 3 + 1) + max(0, 2.5 - 3 + 1) = 0.5.
Understand the idea
The multiclass hinge loss, used by linear SVMs, wants the correct class score to beat every other class score by at least a margin. Each wrong class that comes too close adds a penalty equal to how much it falls short. Worked example: margin 1, two rows. Row 1: S = [2, 3, 0.5], correct class 0. Class 1: 3 - 2 + 1 = 2. Class 2: 0.5 - 2 + 1 = -0.5, clipped to 0. Row loss = 2. Row 2: S = [1, 4, 2], correct class 1. Class 0: 1 - 4 + 1 = -2, clipped to 0. Class 2: 2 - 4 + 1 = -1, clipped to 0. Row loss = 0. Mean = (2 + 0) / 2 = 1.0. Rule: loss_i = sum over j != y_i of max(0, S[i, j] - S[i, y_i] + margin); return the mean over rows. Leave out the correct class itself: if you include it, it adds exactly the margin to every row. Used in: linear SVM classifiers, and margin-based ranking losses for retrieval and reward models.