Skip to content
55 changes: 55 additions & 0 deletions machine_learning/loss_functions/hinge_loss.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
"""
Hinge Loss

Description:
Compute the Hinge loss used for training SVM (Support Vector Machine).

Formula:
loss = max(0, 1 - true * pred)

Reference: https://en.wikipedia.org/wiki/Hinge_loss

Author: Poojan Smart
Email: smrtpoojan@gmail.com
"""

import numpy as np


def hinge_loss(y_true: np.ndarray, pred: np.ndarray) -> float:
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
def hinge_loss(y_true: np.ndarray, pred: np.ndarray) -> float:
def hinge_loss(y_true: np.ndarray, y_pred: np.ndarray) -> float:

Please rename for consistency

"""
Calculate the hinge loss for y_true and pred for binary classification.
Comment thread
cclauss marked this conversation as resolved.
Outdated

Args:
y_true: Array of actual values (ground truth) encoded as -1 and 1.
Comment thread
tianyizheng02 marked this conversation as resolved.
pred: Array of predicted values.

Returns:
Hinge loss
Comment thread
cclauss marked this conversation as resolved.
Outdated

Examples:
>>> y_true = np.array([-1, 1, 1, -1, 1])
>>> pred = np.array([-4, -0.3, 0.7, 5, 10])
>>> hinge_loss(y_true, pred)
1.52
>>> y_true = np.array([-1, 1, 1, -1, 1, 1])
>>> pred = np.array([-4, -0.3, 0.7, 5, 10])
>>> hinge_loss(y_true, pred)
Traceback (most recent call last):
...
ValueError: Length of predicted and actual array must be same.
"""

if len(y_true) != len(pred):
raise ValueError("Length of predicted and actual array must be same.")

intermidiate_result = 1.0 - (y_true * pred)
intermidiate_result[intermidiate_result < 0] = 0
Comment thread
cclauss marked this conversation as resolved.
Outdated
loss = np.mean(intermidiate_result)
return loss
Comment thread
cclauss marked this conversation as resolved.
Outdated


if __name__ == "__main__":
import doctest

doctest.testmod()