-
Notifications
You must be signed in to change notification settings - Fork 8
/
huberLoss.py
71 lines (63 loc) · 1.89 KB
/
huberLoss.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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
"""Loss functions."""
import tensorflow as tf
def huber_loss(y_true, y_pred, max_grad=1.):
"""Calculate the huber loss.
See https://en.wikipedia.org/wiki/Huber_loss
Parameters
----------
y_true: np.array, tf.Tensor
Target value.
y_pred: np.array, tf.Tensor
Predicted value.
max_grad: float, optional
Positive floating point value. Represents the maximum possible
gradient magnitude.
Returns
-------
tf.Tensor
The huber loss.
"""
a = tf.abs(y_true - y_pred)
less_than_max = 0.5 * tf.square(a)
greater_than_max = max_grad * (a - 0.5 * max_grad)
return tf.where(a <= max_grad, x=less_than_max, y=greater_than_max)
def mean_huber_loss(y_true, y_pred, max_grad=1.):
"""Return mean huber loss.
Same as huber_loss, but takes the mean over all values in the
output tensor.
Parameters
----------
y_true: np.array, tf.Tensor
Target value.
y_pred: np.array, tf.Tensor
Predicted value.
max_grad: float, optional
Positive floating point value. Represents the maximum possible
gradient magnitude.
Returns
-------
tf.Tensor
The mean huber loss.
"""
return tf.reduce_mean(huber_loss(y_true, y_pred, max_grad=max_grad))
def weighted_huber_loss(y_true, y_pred, weights, max_grad=1.):
"""Return mean huber loss.
Same as huber_loss, but takes the mean over all values in the
output tensor.
Parameters
----------
y_true: np.array, tf.Tensor
Target value.
y_pred: np.array, tf.Tensor
Predicted value.
weights: np.array, tf.Tensor
weights value.
max_grad: float, optional
Positive floating point value. Represents the maximum possible
gradient magnitude.
Returns
-------
tf.Tensor
The mean huber loss.
"""
return tf.reduce_mean(weights*huber_loss(y_true, y_pred, max_grad=max_grad))