Implement Hinge Loss (Binary SVM)
Implement Hinge Loss (Binary SVM)
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,m−yisi)where m is the margin (default m=1). Return the mean loss.
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
Log in to take notes on this problem
Accepts: array
Accepts: array
Accepts: number
Accepts: string
Implement Hinge Loss (Binary SVM)
Implement Hinge Loss (Binary SVM)
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,m−yisi)where m is the margin (default m=1). Return the mean loss.
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
Log in to take notes on this problem
Accepts: array
Accepts: array
Accepts: number
Accepts: string