PIXELBANKv8.2.1
Menu

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=1ni=1nmax(0,1yiy^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:
  • First, we calculate the hinge loss for each sample:
    • For yi=1y_i = 1 and y^i=0.8\hat{y}_i = 0.8, the loss is max(0,110.8)=max(0,0.2)=0.2\max(0, 1 - 1 \cdot 0.8) = \max(0, 0.2) = 0.2
    • For yi=1y_i = -1 and y^i=1.2\hat{y}_i = -1.2, the loss is max(0,1(1)(1.2))=max(0,11.2)=max(0,0.2)=0\max(0, 1 - (-1) \cdot (-1.2)) = \max(0, 1 - 1.2) = \max(0, -0.2) = 0
    • For yi=1y_i = 1 and y^i=0.3\hat{y}_i = 0.3, the loss is max(0,110.3)=max(0,0.7)=0.7\max(0, 1 - 1 \cdot 0.3) = \max(0, 0.7) = 0.7
    • For yi=1y_i = -1 and y^i=0.5\hat{y}_i = -0.5, the loss is max(0,1(1)(0.5))=max(0,10.5)=max(0,0.5)=0.5\max(0, 1 - (-1) \cdot (-0.5)) = \max(0, 1 - 0.5) = \max(0, 0.5) = 0.5
  • Then, we calculate the average hinge loss: L=1ni=1nmax(0,1yiy^i)=14(0.2+0+0.7+0.5)=1.44=0.35L = \frac{1}{n}\sum_{i=1}^{n} \max(0, 1 - y_i \cdot \hat{y}_i) = \frac{1}{4}(0.2 + 0 + 0.7 + 0.5) = \frac{1.4}{4} = 0.35
  • The final output is 0.350.35

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
Editor

Test Results

0/0
Run code to see test results.