forked from PINTO0309/DeepLearningMugenKnock
-
Notifications
You must be signed in to change notification settings - Fork 0
/
multi_perceptron_2.py
58 lines (43 loc) · 1.32 KB
/
multi_perceptron_2.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
np.random.seed(0)
xs = np.array([[0,0], [0,1], [1,0], [1,1]], dtype=np.float32)
ts = np.array([[0], [1], [1], [0]], dtype=np.float32)
lr = 0.1
# perceptron
w1 = np.random.normal(0, 1, [2, 2])
b1 = np.random.normal(0, 1, [2])
wout = np.random.normal(0, 1, [2, 1])
bout = np.random.normal(0, 1, [1])
print("weight1 >>\n", w1)
print("bias1 >>\n", b1)
print("weight_out >>\m", wout)
print("bias_out >>\n", bout)
def sigmoid(x):
return 1 / (1 + np.exp(-x))
z1 = xs
for ite in range(5000):
ite += 1
# feed forward
z2 = sigmoid(np.dot(z1, w1) + b1)
out = sigmoid(np.dot(z2, wout) + bout)
# back propagate
En = (out - ts) * out * (1 - out)
grad_wout = np.dot(z2.T, En)
grad_bout = np.dot(np.ones([En.shape[0]]), En)
wout -= lr * grad_wout
bout -= lr * grad_bout
# backpropagation inter layer
grad_u1 = np.dot(En, wout.T) * z2 * (1 - z2)
grad_w1 = np.dot(z1.T, grad_u1)
grad_b1 = np.dot(np.ones([grad_u1.shape[0]]), grad_u1)
w1 -= lr * grad_w1
b1 -= lr * grad_b1
print("weight1 >>\n", w1)
print("bias1 >>\n", b1)
print("weight_out >>\n", wout)
print("bias_out >>\n", bout)
# test
for i in range(4):
z2 = sigmoid(np.dot(z1[i], w1) + b1)
out = sigmoid(np.dot(z2, wout) + bout)
print("in >>", xs[i], ", out >>", out)