-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinary.py
More file actions
94 lines (66 loc) · 1.96 KB
/
Binary.py
File metadata and controls
94 lines (66 loc) · 1.96 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import numpy as np
import time
n_hidden = 10
n_in = 10
n_out = 10
n_samples = 300
learning_rate = 0.01
momentum = 0.9
np.random.seed(0)
def sigmoid(x):
return 1.0/(1.0 + np.exp(-x))
def tanh_prime(x):
return 1 - np.tanh(x)**2
def train(x, t, V, W, bv, bw):
# forward
A = np.dot(x, V) + bv
Z = np.tanh(A)
B = np.dot(Z, W) + bw
Y = sigmoid(B)
# backward
Ew = Y - t
Ev = tanh_prime(A) * np.dot(W, Ew)
dW = np.outer(Z, Ew)
dV = np.outer(x, Ev)
loss = -np.mean ( t * np.log(Y) + (1 - t) * np.log(1 - Y) )
# Note that we use error for each layer as a gradient
# for biases
return loss, (dV, dW, Ev, Ew)
def predict(x, V, W, bv, bw):
A = np.dot(x, V) + bv
B = np.dot(np.tanh(A), W) + bw
return (sigmoid(B) > 0.5).astype(int)
# Setup initial parameters
# Note that initialization is cruxial for first-order methods!
V = np.random.normal(scale=0.1, size=(n_in, n_hidden))
W = np.random.normal(scale=0.1, size=(n_hidden, n_out))
bv = np.zeros(n_hidden)
bw = np.zeros(n_out)
params = [V,W,bv,bw]
# Generate some data
X = np.random.binomial(1, 0.5, (n_samples, n_in))
T = X ^ 1
# Train
for epoch in range(100):
err = []
upd = [0]*len(params)
t0 = time.clock()
for i in range(X.shape[0]):
loss, grad = train(X[i], T[i], *params)
for j in range(len(params)):
params[j] -= upd[j]
for j in range(len(params)):
upd[j] = learning_rate * grad[j] + momentum * upd[j]
err.append( loss )
print('Epoch: %d, Loss: %.8f, Time: %.4fs'% (
epoch, np.mean(err), time.clock()-t0))
# Try to predict something
x = np.random.binomial(1, 0.1, n_in)
print ("==================================================")
print ()
print ('XOR prediction:')
print ()
print (x)
print (predict(x, *params))
print ()
print ("==================================================")