-
Notifications
You must be signed in to change notification settings - Fork 0
/
loss.py
39 lines (27 loc) · 907 Bytes
/
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
35
36
37
38
39
# Loss
import abc
import numpy as np
from layers import layer
class Loss(layer.Layer):
@abc.abstractmethod
def forward(self, *args, **kwargs) -> float:
pass
@abc.abstractmethod
def backward(self, *args, **kwargs) -> np.ndarray:
pass
class MSELoss(Loss):
def forward(self, y: np.ndarray, targets: np.ndarray) -> float:
self._y = y
self._targets = targets
diff = y - targets
return np.sum(diff**2) / y.size
def backward(self, *args, **kwargs) -> np.ndarray:
diff = self._y - self._targets
return 2 * diff / self._y.size
class CrossEntropyLoss(Loss):
def forward(self, y: np.ndarray, targets: np.ndarray) -> float:
self._y = y
self._targets = targets
return -np.sum(targets * np.log(y))
def backward(self, *args, **kwargs) -> np.ndarray:
return -self._targets / self._y