Implement Multiclass SVM Hinge Loss and Its Subgradient

Quick Overview

Implement the multiclass SVM hinge loss in NumPy along with its subgradient with respect to the score matrix. Tests vectorized margin bookkeeping, weighted means, strict tie handling, input validation, and why the outputs stay finite for very large scores.

Implement Multiclass SVM Hinge Loss and Its Subgradient

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Given a score matrix `scores` of shape `(n, k)` and integer class labels `y` of length `n`, implement two functions for the multiclass SVM hinge loss: ```python def multiclass_hinge_loss(scores, y, margin=1.0, sample_weight=None) -> float: ... def multiclass_hinge_grad(scores, y, margin=1.0, sample_weight=None) -> np.ndarray: ... ``` The loss for example $i$ is $$ L_i = \sum_{j\ne y_i} \max\left(0,\; s_{ij} - s_{i y_i} + \text{margin}\right) $$ `multiclass_hinge_loss` returns the weighted mean of $L_i$ over the examples as a Python `float`. `multiclass_hinge_grad` returns the subgradient of that loss with respect to `scores`, an array of shape `(n, k)`. Both functions must be vectorized. Example with the default margin of 1 and no weights: ```python scores = [[3.2, 5.1, -1.7], [1.3, 4.9, 2.0], [2.2, 2.5, -3.1]] y = [0, 1, 2] multiclass_hinge_loss(scores, y) # (2.9 + 0.0 + 12.9) / 3 = 5.2667 multiclass_hinge_grad(scores, y) # [[-1/3, 1/3, 0 ], # [ 0, 0, 0 ], # [ 1/3, 1/3, -2/3]] ``` ```hint One matrix for both outputs Compute the margin term for every class of every row in a single broadcast. Then decide what the true-class column should hold so it never adds to the loss. ``` ```hint Gradient bookkeeping An active term $s_{ij} - s_{i y_i} + \text{margin}$ involves exactly two scores in its row. Work out what it adds to the derivative of each one, then count the active terms per row. ``` ### Constraints & Assumptions - Weights default to 1 and are normalized by their sum: $\text{loss} = \sum_i w_i L_i / \sum_i w_i$. - A margin term of exactly 0 contributes no loss and no gradient (use strict `> 0`). The correct-class entry of the gradient gets minus the count of active margin terms in its row. - Raise `ValueError` if `scores` is not 2-D, if `y` or `sample_weight` does not have length `n`, or if the weights sum to 0 or less. - Scores may be large (for example ±1000), and the results must stay finite. - No Python loop over examples. ### What a Strong Answer Covers - A vectorized construction of the margin matrix that keeps the true class out of its own loss. - The weighted mean with weights normalized by their sum, returned as a Python `float`. - The subgradient rule for active terms, including the strict comparison at exact ties and the true-class entry. - Input validation that raises `ValueError` in each listed case. - Why the outputs stay finite for very large scores. ### Follow-up Questions - Why is the output only a subgradient, and does the value chosen at exact ties matter in practice? - For a linear classifier with `scores = X @ W`, how do you get the gradient with respect to `W` from this function? - How does this loss treat well-classified examples compared with softmax cross-entropy?

Overview: Implement the multiclass SVM hinge loss in NumPy along with its subgradient with respect to the score matrix. Tests vectorized margin bookkeeping, weighted means, strict tie handling, input validation, and why the outputs stay finite for very large scores.

PracHub logo
General
Nov 24, 2026
mediumMachine Learning EngineerOtherMachine Learning
0
0

Given a score matrix scores of shape (n, k) and integer class labels y of length n, implement two functions for the multiclass SVM hinge loss:

def multiclass_hinge_loss(scores, y, margin=1.0, sample_weight=None) -> float: ...

def multiclass_hinge_grad(scores, y, margin=1.0, sample_weight=None) -> np.ndarray: ...

The loss for example ii is

Li=∑j≠yimax⁡(0,  sij−siyi+margin)L_i = \sum_{j\ne y_i} \max\left(0,\; s_{ij} - s_{i y_i} + \text{margin}\right)

multiclass_hinge_loss returns the weighted mean of LiL_i over the examples as a Python float. multiclass_hinge_grad returns the subgradient of that loss with respect to scores, an array of shape (n, k). Both functions must be vectorized.

Example with the default margin of 1 and no weights:

scores = [[3.2, 5.1, -1.7],
          [1.3, 4.9,  2.0],
          [2.2, 2.5, -3.1]]
y = [0, 1, 2]
multiclass_hinge_loss(scores, y)  # (2.9 + 0.0 + 12.9) / 3 = 5.2667
multiclass_hinge_grad(scores, y)
# [[-1/3, 1/3,  0  ],
#  [ 0,   0,    0  ],
#  [ 1/3, 1/3, -2/3]]

Constraints & Assumptions

  • Weights default to 1 and are normalized by their sum: loss=∑iwiLi/∑iwi\text{loss} = \sum_i w_i L_i / \sum_i w_i .
  • A margin term of exactly 0 contributes no loss and no gradient (use strict > 0 ). The correct-class entry of the gradient gets minus the count of active margin terms in its row.
  • Raise ValueError if scores is not 2-D, if y or sample_weight does not have length n , or if the weights sum to 0 or less.
  • Scores may be large (for example ±1000), and the results must stay finite.
  • No Python loop over examples.

What a Strong Answer Covers Guidance

  • A vectorized construction of the margin matrix that keeps the true class out of its own loss.
  • The weighted mean with weights normalized by their sum, returned as a Python float .
  • The subgradient rule for active terms, including the strict comparison at exact ties and the true-class entry.
  • Input validation that raises ValueError in each listed case.
  • Why the outputs stay finite for very large scores.

Follow-up Questions Guidance

  • Why is the output only a subgradient, and does the value chosen at exact ties matter in practice?
  • For a linear classifier with scores = X @ W , how do you get the gradient with respect to W from this function?
  • How does this loss treat well-classified examples compared with softmax cross-entropy?