Hinge Loss: Being Right by a Margin

Loss FunctionsEasy+10 XP+10

Hinge Loss: Being Right by a Margin

Hinge loss is what an SVM minimises. It doesn't want you merely correct — it wants you correct by a margin of at least 1, and stops caring the moment you clear it.

For labels y in {-1, +1} and a raw score s:

1loss = max(0, 1 - y * s)

Task: write hinge_loss(scores, labels) returning the mean loss over all samples, rounded to 4 decimal places.

  • Labels are +1 or -1, not 1 and 0.
  • Scores are raw, unbounded values — not probabilities.

The flat region is the interesting part. Once a point is correctly classified with margin, its loss and its gradient are both exactly zero, so it stops influencing the model entirely. Only the points near the boundary — the support vectors — shape the final decision surface.

Examples

scores = [0.5, -1.5, 2.0]
labels = [1, -1, 1]
returns 0.1667
scores = [2.0, -2.0]
labels = [1, -1]
returns 0.0

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run