-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLossFunction.py
76 lines (58 loc) · 1.79 KB
/
LossFunction.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
72
73
74
75
76
"""
several loss functions:
CrossEntropy
L1 distance
L2 distance
"""
import numpy as np
class CrossEntropy:
def __init__(self):
self.middle = None
def __call__(self, pred, label):
return self.forward(pred, label)
def forward(self, pred, label):
# default : rows represent the different samples
# cols represent the scores
assert pred.shape == label.shape
result = (-1 / pred.shape[0]) * np.sum(label * np.log(pred))
self.middle = pred, label
return result
def backward(self):
pred, label = self.middle
grad = (-1 / pred.shape[0]) * (label / pred)
return grad
def __repr__(self):
return "Loss Function : CrossEntropy"
class L1:
def __init__(self):
self.middle = None
def __call__(self, pred, label):
return self.forward(pred, label)
def forward(self, pred, label):
assert pred.shape == label.shape
result = np.mean(np.abs(pred - label))
self.middle = pred, label
return result
def backward(self):
pred, label = self.middle
mask = (pred - label) >= 0
grad = (1 / np.product(pred.shape)) * (2 * mask - 1)
return grad
def __repr__(self):
return "Loss Function : L1"
class L2:
def __init__(self):
self.middle = None
def __call__(self, pred, label):
return self.forward(pred, label)
def forward(self, pred, label):
assert pred.shape == label.shape
result = np.mean(np.square(pred - label))
self.middle = pred, label
return result
def backward(self):
pred, label = self.middle
grad = (2 / np.product(pred.shape)) * (pred - label)
return grad
def __repr__(self):
return "Loss Function : L2"