Newer
Older
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
import numpy as np
from numpy.typing import ArrayLike
from abc import ABC, abstractmethod
class LossFunction(ABC):
"""
Base class for all loss functions.
"""
__slots__ = ['name', 'prediction', 'target']
def __init__(self) -> None:
self.name = self.__class__.__name__
def forward(self, prediction: ArrayLike, target: ArrayLike) -> float:
"""
Computes the loss for the given prediction and target values.
"""
self.prediction = prediction
self.target = target
loss = self._function(prediction, target)
return np.mean(loss)
def __call__(self, prediction: ArrayLike, target: ArrayLike) -> float:
"""
Allows the instance of the LossFunction class to be called like a function.
"""
return self.forward(prediction, target)
def backward(self) -> np.ndarray:
"""
Computes the derivative of the loss with respect to the predicted values.
"""
return self._derivative()
@abstractmethod
def _function(self, prediction: ArrayLike, target: ArrayLike) -> float:
"""
Computes the loss for the given prediction and target values.
"""
pass
@abstractmethod
def _derivative(self) -> np.ndarray:
"""
Computes the derivative of the loss with respect to the predicted values.
"""
pass
def __str__(self) -> str:
"""
used for print the layer in a human readable manner
"""
return self.name
class MAELoss(LossFunction):
"""
Mean Absolute Error (MAE) loss function for regression tasks.
"""
__slots__ = []
def __init__(self) -> None:
super().__init__()
def _function(self, prediction: ArrayLike, target: ArrayLike) -> float:
"""
Computes the mean absolute error between the predicted and target values.
"""
return np.abs(target - prediction)
def _derivative(self) -> np.ndarray:
"""
Computes the derivative of the mean absolute error with respect to the predicted values.
"""
return np.sign(self.prediction - self.target) / self.target.size
class MSELoss(LossFunction):
"""
Mean Squared Error (MSE) loss function for regression tasks.
"""
__slots__ = []
def __init__(self) -> None:
super().__init__()
def _function(self, prediction: ArrayLike, target: ArrayLike) -> float:
"""
Computes the mean squared error between the predicted and target values.
"""
return np.power(target - prediction, 2)
def _derivative(self) -> np.ndarray:
"""
Computes the derivative of the mean squared error with respect to the predicted values.
"""
return 2 * (self.prediction - self.target) / self.target.size
class HuberLoss(LossFunction):
"""
Class for implementing the Huber loss function for regression tasks.
"""
__slots__ = ['delta']
def __init__(self, delta: float = 1.0) -> None:
super().__init__()
self.delta = delta
def _function(self, prediction: ArrayLike, target: ArrayLike) -> float:
"""
Calculates the Huber loss value based on the prediction and target arrays.
"""
diff = target - prediction
return np.where(np.abs(diff) < self.delta, 0.5 * np.square(diff), self.delta * np.abs(diff) - 0.5 * self.delta ** 2)
def _derivative(self) -> np.ndarray:
"""
Calculates the derivative of the Huber loss function with respect to the prediction array.
"""
diff = self.prediction - self.target
return np.where(np.abs(diff) < self.delta, diff, self.delta * np.sign(diff))
class NLLLoss(LossFunction):
"""
intended for classification
"""
__slots__ = ['epsilon']
def __init__(self, epsilon: float = 1e-8) -> None:
super().__init__()
self.epsilon = epsilon
def _function(self, prediction: ArrayLike, target: ArrayLike) -> float:
"""
Compute the negative log-likelihood loss for binary classification.
"""
return - (target * np.log(prediction + self.epsilon) + (1 - target) * np.log(1 - prediction + self.epsilon))
def _derivative(self) -> np.ndarray:
"""
Compute the derivative of the negative log-likelihood loss.
"""
return (self.prediction - self.target) / (self.prediction * (1 - self.prediction) + self.epsilon)
class CrossEntropyLoss(LossFunction):
"""
intended for classification
"""
__slots__ = ['epsilon']
def __init__(self, epsilon: float = 1e-8) -> None:
super().__init__()
self.epsilon = epsilon # stability parameter
def _function(self, prediction: ArrayLike, target: ArrayLike) -> float:
"""
Compute cross entropy loss for binary classification.
"""
confidence = np.sum(prediction * target, axis=1)
return - np.log(confidence + self.epsilon)
def _derivative(self) -> np.ndarray:
"""
Compute the derivative of cross entropy loss.
"""
return (self.prediction - self.target) / self.target.size
class FocalLoss(LossFunction):
"""
intended for classification
this is an alternative to cross entropy loss...
it could be that the derivative is wrong
"""
__slots__ = ['focus', 'epsilon']
def __init__(self, focus: float = 1.5, epsilon: float = 1e-8):
super().__init__()
self.focus = focus
self.epsilon = epsilon # stability parameter
def _function(self, prediction: ArrayLike, target: ArrayLike) -> float:
"""
Compute focal loss for binary classification.
"""
confidence = np.sum(prediction * target, axis=1)
return - self._power(1 - confidence, self.focus) * np.log(confidence + self.epsilon)
def _derivative(self) -> np.ndarray:
"""
Compute the derivative of focal loss.
"""
pt = np.sum(self.prediction * self.target, axis=1) # p_t
term1 = - (1 - pt)**self.focus * (-np.log(pt) - 1)
term2 = self.focus * (1 - pt)**(self.focus - 1) * np.log(pt)
return - (term1 + term2)
class HellingerLoss(LossFunction):
"""
intended for classification
"""
__slots__ = ['epsilon']
def __init__(self, epsilon: float = 1e-8) -> None:
super().__init__()
self.epsilon = epsilon # stability parameter
def _function(self, prediction: ArrayLike, target: ArrayLike) -> float:
"""
Compute hellinger loss for binary classification.
"""
return np.power(np.sqrt(target) - np.sqrt(prediction), 2)
def _derivative(self) -> np.ndarray:
"""
Compute the derivative of hellinger loss.
"""
p_sqrt = np.sqrt(self.prediction)
q_sqrt = np.sqrt(self.target)
return (1/2*np.sqrt(2)) * (q_sqrt - p_sqrt) / p_sqrt