diff --git a/mla/metrics/metrics.py b/mla/metrics/metrics.py index 3cffcee3..1fd2edde 100644 --- a/mla/metrics/metrics.py +++ b/mla/metrics/metrics.py @@ -66,7 +66,7 @@ def logloss(actual, predicted): def hinge(actual, predicted): - return np.mean(np.max(1.0 - actual * predicted, 0.0)) + return np.mean(np.maximum(1.0 - actual * predicted, 0.0)) def binary_crossentropy(actual, predicted): diff --git a/mla/metrics/tests/test_metrics.py b/mla/metrics/tests/test_metrics.py index 307dca70..d969ba78 100644 --- a/mla/metrics/tests/test_metrics.py +++ b/mla/metrics/tests/test_metrics.py @@ -86,3 +86,25 @@ def test_multiclass_logloss(): assert_almost_equal(f([1], [1]), 0) assert_almost_equal(f([1, 1], [1, 1]), 0) assert_almost_equal(f([1], [0.5]), -np.log(0.5)) + + +@pytest.mark.parametrize( + "actual, predicted, expected", + [ + ([1, -1], [2.0, -2.0], 0.0), + ([1, -1], [0.0, 0.0], 1.0), + ([1, -1], [-1.0, 1.0], 2.0), + ([1, -1, 1], [2.0, -0.5, -1.0], 2.5 / 3), + ], +) +def test_hinge(actual, predicted, expected): + assert_almost_equal(metric("hinge")(actual, predicted), expected) + + +def test_hinge_gradient(): + from autograd import grad + + actual = np.array([1.0, -1.0, 1.0]) + predicted = np.array([2.0, -0.5, -1.0]) + gradient = grad(lambda scores: get_metric("hinge")(actual, scores)) + np.testing.assert_allclose(gradient(predicted), [0.0, 1.0 / 3, -1.0 / 3])