Loss & Training ยท Easy
Hinge Loss
Implement Hinge Loss with production-minded edge case handling.
Task
Implement hinge_loss(labels: list[int], scores: list[float], margin: float) -> float. Compute the mean binary hinge loss from -1/+1 labels and prediction scores.
Requirements
- labels and scores have the same shape, and every label is either -1 or +1.
- For each example, compute max(0, margin - label * score).
- Return the arithmetic mean of all per-example losses.
- Return 0.0 when the inputs are empty.
- An example exactly on the margin boundary contributes 0.0.
- Do not modify the inputs.
Example
labels = [1, -1, 1]
scores = [2.0, -0.5, 0.2]
hinge_loss(labels, scores, margin=1.0)
# 0.43333333333333335