v9.1.1
Menu

Hinge Loss

easyFREESupport Vector MachinesMachine Learning 1

Compute the hinge loss for SVM classification.

Given true labels yi∈{−1,+1}y_i \in \{-1, +1\} and raw predictions (scores) y^i\hat{y}_i:

L=1n∑i=1nmax⁡(0,1−yi⋅y^i)L = \frac{1}{n}\sum_{i=1}^{n} \max(0, 1 - y_i \cdot \hat{y}_i)

This is the loss function used by Support Vector Machines. Points correctly classified with margin ≥1\geq 1 contribute zero loss.

Return the average hinge loss rounded to 4 decimal places.

Example

Input
y_true = [1, -1, 1, -1]
y_scores = [0.8, -1.2, 0.3, -0.5]
Output
0.35
Reasoning
  • Inputs: y_true holds the four true labels (+1,−1,+1,−1)(+1, -1, +1, -1) and y_scores holds the classifier's raw scores (0.8,−1.2,0.3,−0.5)(0.8, -1.2, 0.3, -0.5). The sign of a score is the predicted class; its size is the confidence.
  • Margins: multiply each label by its score, mi=yiy^im_i = y_i \hat{y}_i, giving 0.8, 1.2, 0.3, 0.50.8,\ 1.2,\ 0.3,\ 0.5. All four are positive, so every point is on the correct side.
  • Per-point loss: max⁡(0,1−mi)\max(0, 1 - m_i) gives 0.2, 0, 0.7, 0.50.2,\ 0,\ 0.7,\ 0.5. The second point has margin 1.2≥11.2 \geq 1, so 1−1.2=−0.21 - 1.2 = -0.2 is clipped to 00.
  • Average: L=0.2+0+0.7+0.54=1.44=0.35L = \frac{0.2 + 0 + 0.7 + 0.5}{4} = \frac{1.4}{4} = 0.35, which is the output 0.35.
  • Notice: three points are classified correctly yet still pay a penalty, because their margin is below 11. Hinge loss rewards confident correct predictions, not just correct ones. A wrong sign (negative margin) would push a point's loss above 11.

Constraints

  • y_true: list of labels in {-1, +1}
  • y_scores: list of raw prediction scores (any real number)
  • Return average hinge loss rounded to 4 decimal places

Learn this in

More from Machine Learning 1

solution.py

Test results

Sign in to run your code against the test cases.