-
Notifications
You must be signed in to change notification settings - Fork 0
/
activation.py
65 lines (43 loc) · 1.3 KB
/
activation.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
import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(x):
x = sigmoid(x)
return x * (1 - x)
def relu(x):
return np.where(x > 0, x, x * 0.01)
def relu_derivative(x):
return np.where(x > 0, 1, 0.01)
def Tanh(x):
return np.tanh(x)
def Tanh_derivative(x):
return 1 - np.tanh(x) ** 2
class Activation:
def __init__(self, activation=["sigmoid", "relu", "tanh"]):
self.activation = activation
if activation == "sigmoid":
self.func = sigmoid
self.dfunc = sigmoid_derivative
elif activation == "relu":
self.func = relu
self.dfunc = relu_derivative
elif activation == "tanh":
self.func = Tanh
self.dfunc = Tanh_derivative
def forward(self, X):
self.X = X
return self.func(X)
def backward(self, grad, rate):
return np.multiply(grad, self.dfunc(self.X))
class SoftMax:
def __init__(self):
pass
def forward(self, X):
tmp = np.exp(X)
self.output = tmp / np.sum(tmp)
return self.output
def backward(self, output_gradient, rate):
n = np.size(self.output)
return np.dot(
rate * (np.identity(n) - self.output.T) * self.output, output_gradient
)