📘
Hinge Loss
Compute the hinge loss for SVM classification.
Given true labels yi∈{−1,+1} and raw predictions (scores) y^i:
L=n1∑i=1nmax(0,1−yi⋅y^i)
This is the loss function used by Support Vector Machines. Points correctly classified with margin ≥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=1 and y^i=0.8, the loss is max(0,1−1⋅0.8)=max(0,0.2)=0.2
- For yi=−1 and y^i=−1.2, the loss is max(0,1−(−1)⋅(−1.2))=max(0,1−1.2)=max(0,−0.2)=0
- For yi=1 and y^i=0.3, the loss is max(0,1−1⋅0.3)=max(0,0.7)=0.7
- For yi=−1 and y^i=−0.5, the loss is max(0,1−(−1)⋅(−0.5))=max(0,1−0.5)=max(0,0.5)=0.5
- Then, we calculate the average hinge loss: L=n1∑i=1nmax(0,1−yi⋅y^i)=41(0.2+0+0.7+0.5)=41.4=0.35
- The final output is 0.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
Python 3.13.1
Test Results
0/0Run code to see test results.