-
Notifications
You must be signed in to change notification settings - Fork 0
/
layers.py
58 lines (41 loc) · 1.17 KB
/
layers.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
import numpy as np
class Param:
def __init__(self, value):
self.value = value
self.grad = np.zeros_like(value)
class Layer:
def __init__(self):
self.isUpdatable = None
pass
def forward(self):
pass
def backward(self):
pass
class SigmoidLayer(Layer):
def __init__(self):
self.X = None
self.isUpdatable = False
def sigmoid(self, X):
return 1/(1 + np.exp(-X))
def forward(self, X):
self.X = X
return self.sigmoid(X)
def backward(self, d_out):
d_result = d_out * (self.sigmoid(self.X) * (1 - self.sigmoid(self.X)))
return d_result
def params(self):
return {}
class FullyConnectedLayer(Layer):
def __init__(self, n_input, n_output):
self.W = Param(1 * np.random.randn(n_input, n_output))
self.X = None
self.isUpdatable = True
def forward(self, X):
self.X = X
return np.dot(X, self.W.value)
def backward(self, d_out):
self.W.grad = np.dot(self.X.T, d_out)
d_result = np.dot(d_out, self.W.value.T)
return d_result
def params(self):
return {'W': self.W}