-
Notifications
You must be signed in to change notification settings - Fork 1
/
loss.py
34 lines (28 loc) · 1.07 KB
/
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
30
31
32
33
34
import math
class Loss:
@staticmethod
def loss(predicted: float, target: float) -> float:
raise NotImplementedError
@staticmethod
def derivative(predicted: float, target: float) -> float:
raise NotImplementedError
class MSE(Loss):
@staticmethod
def loss(predicted: float, target: float) -> float:
return 0.5 * (predicted - target) ** 2
@staticmethod
def derivative(predicted: float, target: float) -> float:
return predicted - target
class LogLoss(Loss):
@staticmethod
def loss(predicted: float, target: float) -> float:
# Add epsilon to prevent log(0)
epsilon = 1e-15
predicted = max(min(predicted, 1 - epsilon), epsilon)
return -target * math.log(predicted) - (1 - target) * math.log(1 - predicted)
@staticmethod
def derivative(predicted: float, target: float) -> float:
# Add epsilon to prevent division by zero
epsilon = 1e-15
predicted = max(min(predicted, 1 - epsilon), epsilon)
return (predicted - target) / (predicted * (1 - predicted))