Problems
Loading...
1 / 1

Implement Hinge Loss (Binary SVM)

Loss Functions
Easy

Compute the hinge loss for binary SVM with labels y ∈ {-1,+1} and real-valued scores s. For each example:

Mathematical Definition

i=max(0,myisi)\ell_i = \max(0, m - y_i s_i)

where m is the margin (default m=1). Return the mean loss.

Loading visualization...

Examples

Input:

y_true = [ 1, 1, -1]

y_score = [ 2, 0, 0]

Output:

( max(0,1-1*2)=0, max(0,1-1*0)=1, max(0,1-(-1*0))=1 )

→ mean = (0+1+1)/3 = 0.66666667

Input:

y_true = [-1, 1]

y_score = [-3, 0.5]

Output:

( max(0,1-(-1*-3))=max(0,1-3)=0,

max(0,1-1*0.5)=0.5 ) → mean = 0.25

Hint 1

Use np.maximum(0, margin - y*s) to compute the hinge loss vectorized.

Hint 2

Apply reduction using loss.mean() or loss.sum() based on the parameter.

Requirements

  • Validate shapes and label set {-1,+1}
  • Fully vectorized (no Python loops)
  • Support reduction="mean" (default) and "sum"
  • Return float value

Constraints

  • n ≤ 1e6
  • Use NumPy only
  • Time limit: 200 ms
Try Similar Problems