-
Notifications
You must be signed in to change notification settings - Fork 93
/
cosh_loss.py
29 lines (26 loc) · 953 Bytes
/
cosh_loss.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
"""Hyperbolic Cosine Loss"""
import typing
import numpy as np
from h2oaicore.metrics import CustomScorer
class CoshLossScorer(CustomScorer):
_description = "Cosh loss for Regression"
_regression = True
_maximize = False
_perfect_score = 0
_display_name = "COSH"
def score(self,
actual: np.array,
predicted: np.array,
sample_weight: typing.Optional[np.array] = None,
labels: typing.Optional[np.array] = None,
**kwargs) -> float:
if sample_weight is None:
sample_weight = np.ones(actual.shape[0])
predicted = predicted.ravel()
good_rows = predicted >= 0
if not good_rows.any():
return 30
delta = predicted[good_rows] - actual[good_rows]
sample_weight = sample_weight[good_rows]
loss = np.log1p(np.cosh(delta))
return np.sum(sample_weight * loss) / np.sum(sample_weight)