-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathFC.py
220 lines (183 loc) · 9.92 KB
/
FC.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
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
# Based on tutorial by Alec Radford
# https://github.com/Newmu/Theano-Tutorials/blob/master/4_modern_net.py
import cgt
from cgt import nn
from cgt.distributions import categorical
from NNobj import *
class FC(NNobj):
"Class for a multi-layer perceptron (fully connected network) object"
def __init__(self, model="dense", im_size=[28, 28], dropout=True, devtype="cpu", grad_check=True, reg=0):
if grad_check: cgt.set_precision("quad")
self.model = model
self.reg = reg
np.random.seed(0)
cgt.update_config(default_device=cgt.core.Device(devtype=devtype), backend="native")
print(model)
# MLP with 1 hidden layer
if model == "dense1":
self.Xsize = 2*im_size[0]*im_size[1]+im_size[0]+im_size[1]
self.X = cgt.matrix("X", fixed_shape=(None, self.Xsize))
self.y = cgt.vector("y", dtype='i8')
self.p_drop_input, self.p_drop_hidden = (0.2, 0.5) if dropout else (0, 0)
self.w_h = init_weights(self.Xsize, 256)
self.w_o = init_weights(256, 8)
self.pofy_drop = dense_model1(self.X, self.w_h, self.w_o, self.p_drop_input, self.p_drop_hidden)
self.pofy_nodrop = dense_model1(self.X, self.w_h, self.w_o, 0., 0.)
self.params = [self.w_h, self.w_o]
self.l1 = cgt.abs(self.w_h).sum() + cgt.abs(self.w_o).sum()
self.cost_drop = -cgt.mean(categorical.loglik(self.y, self.pofy_drop)) + self.reg*self.l1
# MLP with 2 hidden layers
elif model == "dense2":
self.Xsize = 2*im_size[0]*im_size[1]+im_size[0]+im_size[1]
self.X = cgt.matrix("X", fixed_shape=(None, self.Xsize))
self.y = cgt.vector("y", dtype='i8')
self.p_drop_input, self.p_drop_hidden = (0.2, 0.5) if dropout else (0, 0)
self.w_h = init_weights(self.Xsize, 256)
self.w_h2 = init_weights(256, 256)
self.w_o = init_weights(256, 8)
self.pofy_drop = dense_model2(self.X, self.w_h, self.w_h2, self.w_o, self.p_drop_input, self.p_drop_hidden)
self.pofy_nodrop = dense_model2(self.X, self.w_h, self.w_h2, self.w_o, 0., 0.)
self.params = [self.w_h, self.w_h2, self.w_o]
self.l1 = cgt.abs(self.w_h).sum() + cgt.abs(self.w_h2).sum() + cgt.abs(self.w_o).sum()
self.cost_drop = -cgt.mean(categorical.loglik(self.y, self.pofy_drop)) + self.reg*self.l1
# MLP with 3 hidden layers
elif model == "dense3":
self.Xsize = 2*im_size[0]*im_size[1]+im_size[0]+im_size[1]
self.X = cgt.matrix("X", fixed_shape=(None, self.Xsize))
self.y = cgt.vector("y", dtype='i8')
self.p_drop_input, self.p_drop_hidden = (0.0, [0.5, 0.5, 0.5]) if dropout else (0, [0, 0, 0])
self.w_h = init_weights(self.Xsize, 256)
self.w_h2 = init_weights(256, 256)
self.w_h3 = init_weights(256, 256)
self.w_o = init_weights(256, 8)
self.pofy_drop = dense_model3(self.X, self.w_h, self.w_h2, self.w_h3, self.w_o, self.p_drop_input,
self.p_drop_hidden)
self.pofy_nodrop = dense_model3(self.X, self.w_h, self.w_h2, self.w_h3, self.w_o, 0., [0., 0., 0.])
self.params = [self.w_h, self.w_h2, self.w_h3, self.w_o]
self.l1 = cgt.abs(self.w_h).sum() + cgt.abs(self.w_h2).sum() + cgt.abs(self.w_h3).sum() + \
cgt.abs(self.w_o).sum()
self.cost_drop = -cgt.mean(categorical.loglik(self.y, self.pofy_drop)) + self.reg*self.l1
else:
raise RuntimeError("Unknown Model")
self.y_nodrop = cgt.argmax(self.pofy_nodrop, axis=1)
self.cost_nodrop = -cgt.mean(categorical.loglik(self.y, self.pofy_nodrop))
self.err_nodrop = cgt.cast(cgt.not_equal(self.y_nodrop, self.y), cgt.floatX).mean()
self.computeloss = cgt.function(inputs=[self.X, self.y], outputs=[self.err_nodrop,self.cost_nodrop])
self.y_out = cgt.function(inputs=[self.X], outputs=[self.y_nodrop])
self.updates = rmsprop_updates(self.cost_drop, self.params)
self.train = cgt.function(inputs=[self.X, self.y], outputs=[], updates=self.updates)
def run_training(self, input, stepsize=0.01, epochs=10, output='None', batch_size=128, grad_check=True,
profile=False, step_decrease_rate=0.5, step_decrease_time=1000):
# run NN training from input matlab data file, and save test data prediction in output file
# load data from Matlab file, including
# im_data: flattened images
# state_data: concatenated one-hot vectors for each state variable
# label_data: one-hot vector for action (state difference)
if grad_check: cgt.set_precision("quad")
matlab_data = sio.loadmat(input)
im_data = matlab_data["im_data"]
im_data = (im_data - 1)/255 # obstacles = 1, free zone = 0
state_data = matlab_data["state_data"]
value_data = matlab_data["value_data"]
label_data = matlab_data["label_data"]
Xdata = (np.concatenate((np.concatenate((im_data,value_data),axis=1), state_data), axis=1)).astype(cgt.floatX)
ydata = label_data
training_samples = int(6/7.0*Xdata.shape[0])
Xtrain = Xdata[0:training_samples]
ytrain = ydata[0:training_samples]
Xtest = Xdata[training_samples:]
ytest = ydata[training_samples:]
sortinds = np.random.permutation(training_samples)
Xtrain = Xtrain[sortinds]
ytrain = ytrain[sortinds]
self.updates = rmsprop_updates(self.cost_drop, self.params, stepsize=stepsize)
self.train = cgt.function(inputs=[self.X, self.y], outputs=[], updates=self.updates)
from cgt.tests import gradcheck_model
if grad_check:
cost_nodrop = cgt.core.clone(self.cost_nodrop, {self.X: Xtrain[:1], self.y: ytrain[:1]})
print "doing gradient check..."
print "------------------------------------"
gradcheck_model(cost_nodrop, self.params[0:1])
print "success!"
return
if profile: cgt.profiler.start()
print fmt_row(10, ["Epoch","Train NLL","Train Err","Test NLL","Test Err","Epoch Time"])
for i_epoch in xrange(int(epochs)):
tstart = time.time()
for start in xrange(0, Xtrain.shape[0], batch_size):
end = start+batch_size
self.train(Xtrain[start:end], ytrain[start:end])
elapsed = time.time() - tstart
trainerr, trainloss = self.computeloss(Xtrain[:len(Xtest)], ytrain[:len(Xtest)])
testerr, testloss = self.computeloss(Xtest, ytest)
print fmt_row(10, [i_epoch, trainloss, trainerr, testloss, testerr, elapsed])
if (i_epoch > 0) & (i_epoch % step_decrease_time == 0):
stepsize = step_decrease_rate * stepsize
self.updates = rmsprop_updates(self.cost_drop, self.params, stepsize=stepsize)
self.train = cgt.function(inputs=[self.X, self.y], outputs=[], updates=self.updates)
print stepsize
if profile: cgt.execution.profiler.print_stats()
# save Matlab data
if output != 'None':
sio.savemat(file_name=output, mdict={'in': Xtest, 'out': self.y_out(Xtest)})
def predict(self, input):
# NN output for a single input, read from file
matlab_data = sio.loadmat(input)
im_data = matlab_data["im_data"]
im_data = (im_data - 1)/255 # obstacles = 1, free zone = 0
state_data = matlab_data["state_data"]
value_data = matlab_data["value_data"]
x_test = (np.concatenate((np.concatenate((im_data, value_data), axis=1), state_data), axis=1)).astype(cgt.floatX)
out = self.y_out(x_test)
return out[0][0]
def init_weights(*shape):
return cgt.shared(np.random.randn(*shape) * 0.01, fixed_shape_mask='all')
def rmsprop_updates(cost, params, stepsize=0.001, rho=0.9, epsilon=1e-6):
grads = cgt.grad(cost, params)
updates = []
for p, g in zip(params, grads):
acc = cgt.shared(p.op.get_value() * 0.)
acc_new = rho * acc + (1 - rho) * cgt.square(g)
gradient_scaling = cgt.sqrt(acc_new + epsilon)
g = g / gradient_scaling
updates.append((acc, acc_new))
updates.append((p, p - stepsize * g))
return updates
def adagrad_updates(cost, params, stepsize=0.001, rho=0.9, epsilon=1e-6):
grads = cgt.grad(cost, params)
updates = []
for param, grad in zip(params, grads):
value = param.op.get_value()
accu = cgt.shared(np.zeros(value.shape, dtype=value.dtype))
delta_accu = cgt.shared(np.zeros(value.shape, dtype=value.dtype))
accu_new = rho * accu + (1 - rho) * grad ** 2
updates.append((accu, accu_new))
update = (grad * cgt.sqrt(delta_accu + epsilon) / cgt.sqrt(accu_new + epsilon))
updates.append((param, param - stepsize * update))
delta_accu_new = rho * delta_accu + (1 - rho) * update ** 2
updates.append((delta_accu, delta_accu_new))
return updates
def dense_model1(X, w_h, w_o, p_drop_input, p_drop_hidden):
X = nn.dropout(X, p_drop_input)
h = nn.rectify(cgt.dot(X, w_h))
h = nn.dropout(h, p_drop_hidden)
py_x = nn.softmax(cgt.dot(h, w_o))
return py_x
def dense_model2(X, w_h, w_h2, w_o, p_drop_input, p_drop_hidden):
X = nn.dropout(X, p_drop_input)
h = nn.rectify(cgt.dot(X, w_h))
h = nn.dropout(h, p_drop_hidden)
h2 = nn.rectify(cgt.dot(h, w_h2))
h2 = nn.dropout(h2, p_drop_hidden)
py_x = nn.softmax(cgt.dot(h2, w_o))
return py_x
def dense_model3(X, w_h, w_h2, w_h3, w_o, p_drop_input, p_drop_hidden):
X = nn.dropout(X, p_drop_input)
h = nn.rectify(cgt.dot(X, w_h))
h = nn.dropout(h, p_drop_hidden[0])
h2 = nn.rectify(cgt.dot(h, w_h2))
h2 = nn.dropout(h2, p_drop_hidden[1])
h3 = nn.rectify(cgt.dot(h2, w_h3))
h3 = nn.dropout(h3, p_drop_hidden[2])
py_x = nn.softmax(cgt.dot(h3, w_o))
return py_x