-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathOpLib.py
45 lines (32 loc) · 875 Bytes
/
OpLib.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
from Core import Op
import numpy as np
class ReLU(Op):
def __init__(self):
super().__init__('Op:ReLU')
def forward(self, x):
self.x = x
return (x>0) * x
def backward(self, grad_y):
x = self.x
grad_y[x<0] = 0
return grad_y, 0
class Flatten(Op):
def __init__(self):
super().__init__('Op:Flatten')
def forward(self, x):
self.x = x
return x.flatten('C')
def backward(self, grad_y):
x = self.x
grad_x = grad_y.reshape(x.shape)
return grad_x, 0
class Sigmoid(Op):
def __init__(self):
super().__init__('Op:Sigmoid')
def forward(self, x):
self.x = x
return 1/(1 + np.exp(-x))
def backward(self, grad_y):
x = self.x
grad = self.forward(x) * (1 - self.forward(x))
return grad*grad_y, 0