|
21 | 21 | __docformat__ = 'restructedtext en' |
22 | 22 |
|
23 | 23 |
|
24 | | -import numpy, time, cPickle, gzip, sys, os |
| 24 | +import cPickle |
| 25 | +import gzip |
| 26 | +import os |
| 27 | +import sys |
| 28 | +import time |
| 29 | + |
| 30 | +import numpy |
25 | 31 |
|
26 | 32 | import theano |
27 | 33 | import theano.tensor as T |
|
31 | 37 |
|
32 | 38 |
|
33 | 39 | class HiddenLayer(object): |
34 | | - def __init__(self, rng, input, n_in, n_out, W = None, b = None, activation = T.tanh): |
| 40 | + def __init__(self, rng, input, n_in, n_out, W=None, b=None, |
| 41 | + activation=T.tanh): |
35 | 42 | """ |
36 | 43 | Typical hidden layer of a MLP: units are fully-connected and have |
37 | 44 | sigmoidal activation function. Weight matrix W is of shape (n_in,n_out) |
@@ -69,26 +76,28 @@ def __init__(self, rng, input, n_in, n_out, W = None, b = None, activation = T.t |
69 | 76 | # For example, results presented in [Xavier10] suggest that you |
70 | 77 | # should use 4 times larger initial weights for sigmoid |
71 | 78 | # compared to tanh |
72 | | - # We have no info for other function, so we use the same as tanh. |
| 79 | + # We have no info for other function, so we use the same as |
| 80 | + # tanh. |
73 | 81 | if W is None: |
74 | | - W_values = numpy.asarray( rng.uniform( |
75 | | - low = - numpy.sqrt(6./(n_in+n_out)), |
76 | | - high = numpy.sqrt(6./(n_in+n_out)), |
77 | | - size = (n_in, n_out)), dtype = theano.config.floatX) |
| 82 | + W_values = numpy.asarray(rng.uniform( |
| 83 | + low=-numpy.sqrt(6. / (n_in + n_out)), |
| 84 | + high=numpy.sqrt(6. / (n_in + n_out)), |
| 85 | + size=(n_in, n_out)), dtype=theano.config.floatX) |
78 | 86 | if activation == theano.tensor.nnet.sigmoid: |
79 | 87 | W_values *= 4 |
80 | 88 |
|
81 | | - W = theano.shared(value = W_values, name ='W') |
| 89 | + W = theano.shared(value=W_values, name='W') |
82 | 90 |
|
83 | 91 | if b is None: |
84 | | - b_values = numpy.zeros((n_out,), dtype= theano.config.floatX) |
85 | | - b = theano.shared(value= b_values, name ='b') |
| 92 | + b_values = numpy.zeros((n_out,), dtype=theano.config.floatX) |
| 93 | + b = theano.shared(value=b_values, name='b') |
86 | 94 |
|
87 | 95 | self.W = W |
88 | 96 | self.b = b |
89 | 97 |
|
90 | 98 | lin_output = T.dot(input, self.W) + self.b |
91 | | - self.output = lin_output if activation is None else activation(lin_output) |
| 99 | + self.output = (lin_output if activation is None |
| 100 | + else activation(lin_output)) |
92 | 101 | # parameters of the model |
93 | 102 | self.params = [self.W, self.b] |
94 | 103 |
|
@@ -104,8 +113,6 @@ class MLP(object): |
104 | 113 | class). |
105 | 114 | """ |
106 | 115 |
|
107 | | - |
108 | | - |
109 | 116 | def __init__(self, rng, input, n_in, n_hidden, n_out): |
110 | 117 | """Initialize the parameters for the multilayer perceptron |
111 | 118 |
|
@@ -133,16 +140,16 @@ def __init__(self, rng, input, n_in, n_hidden, n_out): |
133 | 140 | # translate into a TanhLayer connected to the LogisticRegression |
134 | 141 | # layer; this can be replaced by a SigmoidalLayer, or a layer |
135 | 142 | # implementing any other nonlinearity |
136 | | - self.hiddenLayer = HiddenLayer(rng = rng, input = input, |
137 | | - n_in = n_in, n_out = n_hidden, |
138 | | - activation = T.tanh) |
| 143 | + self.hiddenLayer = HiddenLayer(rng=rng, input=input, |
| 144 | + n_in=n_in, n_out=n_hidden, |
| 145 | + activation=T.tanh) |
139 | 146 |
|
140 | 147 | # The logistic regression layer gets as input the hidden units |
141 | 148 | # of the hidden layer |
142 | 149 | self.logRegressionLayer = LogisticRegression( |
143 | | - input = self.hiddenLayer.output, |
144 | | - n_in = n_hidden, |
145 | | - n_out = n_out) |
| 150 | + input=self.hiddenLayer.output, |
| 151 | + n_in=n_hidden, |
| 152 | + n_out=n_out) |
146 | 153 |
|
147 | 154 | # L1 norm ; one regularization option is to enforce L1 norm to |
148 | 155 | # be small |
@@ -151,8 +158,8 @@ def __init__(self, rng, input, n_in, n_hidden, n_out): |
151 | 158 |
|
152 | 159 | # square of L2 norm ; one regularization option is to enforce |
153 | 160 | # square of L2 norm to be small |
154 | | - self.L2_sqr = (self.hiddenLayer.W**2).sum() \ |
155 | | - + (self.logRegressionLayer.W**2).sum() |
| 161 | + self.L2_sqr = (self.hiddenLayer.W ** 2).sum() \ |
| 162 | + + (self.logRegressionLayer.W ** 2).sum() |
156 | 163 |
|
157 | 164 | # negative log likelihood of the MLP is given by the negative |
158 | 165 | # log likelihood of the output of the model, computed in the |
@@ -166,8 +173,8 @@ def __init__(self, rng, input, n_in, n_hidden, n_out): |
166 | 173 | self.params = self.hiddenLayer.params + self.logRegressionLayer.params |
167 | 174 |
|
168 | 175 |
|
169 | | -def test_mlp( learning_rate=0.01, L1_reg = 0.00, L2_reg = 0.0001, n_epochs=1000, |
170 | | - dataset = '../data/mnist.pkl.gz', batch_size = 20): |
| 176 | +def test_mlp(learning_rate=0.01, L1_reg=0.00, L2_reg=0.0001, n_epochs=1000, |
| 177 | + dataset='../data/mnist.pkl.gz', batch_size=20): |
171 | 178 | """ |
172 | 179 | Demonstrate stochastic gradient descent optimization for a multilayer |
173 | 180 | perceptron |
@@ -191,22 +198,20 @@ def test_mlp( learning_rate=0.01, L1_reg = 0.00, L2_reg = 0.0001, n_epochs=1000, |
191 | 198 |
|
192 | 199 | :type dataset: string |
193 | 200 | :param dataset: the path of the MNIST dataset file from |
194 | | - http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.pkl.gz |
| 201 | + http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.pkl.gz |
195 | 202 |
|
196 | 203 |
|
197 | 204 | """ |
198 | 205 | datasets = load_data(dataset) |
199 | 206 |
|
200 | 207 | train_set_x, train_set_y = datasets[0] |
201 | 208 | valid_set_x, valid_set_y = datasets[1] |
202 | | - test_set_x , test_set_y = datasets[2] |
203 | | - |
204 | | - |
| 209 | + test_set_x, test_set_y = datasets[2] |
205 | 210 |
|
206 | 211 | # compute number of minibatches for training, validation and testing |
207 | 212 | n_train_batches = train_set_x.get_value(borrow=True).shape[0] / batch_size |
208 | 213 | n_valid_batches = valid_set_x.get_value(borrow=True).shape[0] / batch_size |
209 | | - n_test_batches = test_set_x.get_value(borrow=True).shape[0] / batch_size |
| 214 | + n_test_batches = test_set_x.get_value(borrow=True).shape[0] / batch_size |
210 | 215 |
|
211 | 216 | ###################### |
212 | 217 | # BUILD ACTUAL MODEL # |
@@ -215,14 +220,14 @@ def test_mlp( learning_rate=0.01, L1_reg = 0.00, L2_reg = 0.0001, n_epochs=1000, |
215 | 220 |
|
216 | 221 | # allocate symbolic variables for the data |
217 | 222 | index = T.lscalar() # index to a [mini]batch |
218 | | - x = T.matrix('x') # the data is presented as rasterized images |
219 | | - y = T.ivector('y') # the labels are presented as 1D vector of |
220 | | - # [int] labels |
| 223 | + x = T.matrix('x') # the data is presented as rasterized images |
| 224 | + y = T.ivector('y') # the labels are presented as 1D vector of |
| 225 | + # [int] labels |
221 | 226 |
|
222 | 227 | rng = numpy.random.RandomState(1234) |
223 | 228 |
|
224 | 229 | # construct the MLP class |
225 | | - classifier = MLP( rng = rng, input=x, n_in=28*28, n_hidden = 500, n_out=10) |
| 230 | + classifier = MLP(rng=rng, input=x, n_in=28 * 28, n_hidden=500, n_out=10) |
226 | 231 |
|
227 | 232 | # the cost we minimize during training is the negative log likelihood of |
228 | 233 | # the model plus the regularization terms (L1 and L2); cost is expressed |
@@ -233,66 +238,64 @@ def test_mlp( learning_rate=0.01, L1_reg = 0.00, L2_reg = 0.0001, n_epochs=1000, |
233 | 238 |
|
234 | 239 | # compiling a Theano function that computes the mistakes that are made |
235 | 240 | # by the model on a minibatch |
236 | | - test_model = theano.function(inputs = [index], |
237 | | - outputs = classifier.errors(y), |
| 241 | + test_model = theano.function(inputs=[index], |
| 242 | + outputs=classifier.errors(y), |
238 | 243 | givens={ |
239 | | - x:test_set_x[index*batch_size:(index+1)*batch_size], |
240 | | - y:test_set_y[index*batch_size:(index+1)*batch_size]}) |
| 244 | + x: test_set_x[index * batch_size:(index + 1) * batch_size], |
| 245 | + y: test_set_y[index * batch_size:(index + 1) * batch_size]}) |
241 | 246 |
|
242 | | - validate_model = theano.function(inputs = [index], |
243 | | - outputs = classifier.errors(y), |
| 247 | + validate_model = theano.function(inputs=[index], |
| 248 | + outputs=classifier.errors(y), |
244 | 249 | givens={ |
245 | | - x:valid_set_x[index*batch_size:(index+1)*batch_size], |
246 | | - y:valid_set_y[index*batch_size:(index+1)*batch_size]}) |
| 250 | + x: valid_set_x[index * batch_size:(index + 1) * batch_size], |
| 251 | + y: valid_set_y[index * batch_size:(index + 1) * batch_size]}) |
247 | 252 |
|
248 | 253 | # compute the gradient of cost with respect to theta (sotred in params) |
249 | 254 | # the resulting gradients will be stored in a list gparams |
250 | 255 | gparams = [] |
251 | 256 | for param in classifier.params: |
252 | | - gparam = T.grad(cost, param) |
| 257 | + gparam = T.grad(cost, param) |
253 | 258 | gparams.append(gparam) |
254 | 259 |
|
255 | | - |
256 | 260 | # specify how to update the parameters of the model as a dictionary |
257 | 261 | updates = {} |
258 | 262 | # given two list the zip A = [ a1,a2,a3,a4] and B = [b1,b2,b3,b4] of |
259 | 263 | # same length, zip generates a list C of same size, where each element |
260 | 264 | # is a pair formed from the two lists : |
261 | 265 | # C = [ (a1,b1), (a2,b2), (a3,b3) , (a4,b4) ] |
262 | 266 | for param, gparam in zip(classifier.params, gparams): |
263 | | - updates[param] = param - learning_rate*gparam |
| 267 | + updates[param] = param - learning_rate * gparam |
264 | 268 |
|
265 | 269 | # compiling a Theano function `train_model` that returns the cost, but |
266 | 270 | # in the same time updates the parameter of the model based on the rules |
267 | 271 | # defined in `updates` |
268 | | - train_model =theano.function( inputs = [index], outputs = cost, |
269 | | - updates = updates, |
| 272 | + train_model = theano.function(inputs=[index], outputs=cost, |
| 273 | + updates=updates, |
270 | 274 | givens={ |
271 | | - x:train_set_x[index*batch_size:(index+1)*batch_size], |
272 | | - y:train_set_y[index*batch_size:(index+1)*batch_size]}) |
| 275 | + x: train_set_x[index * batch_size:(index + 1) * batch_size], |
| 276 | + y: train_set_y[index * batch_size:(index + 1) * batch_size]}) |
273 | 277 |
|
274 | 278 | ############### |
275 | 279 | # TRAIN MODEL # |
276 | 280 | ############### |
277 | 281 | print '... training' |
278 | 282 |
|
279 | 283 | # early-stopping parameters |
280 | | - patience = 10000 # look as this many examples regardless |
281 | | - patience_increase = 2 # wait this much longer when a new best is |
282 | | - # found |
283 | | - improvement_threshold = 0.995 # a relative improvement of this much is |
284 | | - # considered significant |
285 | | - validation_frequency = min(n_train_batches,patience/2) |
| 284 | + patience = 10000 # look as this many examples regardless |
| 285 | + patience_increase = 2 # wait this much longer when a new best is |
| 286 | + # found |
| 287 | + improvement_threshold = 0.995 # a relative improvement of this much is |
| 288 | + # considered significant |
| 289 | + validation_frequency = min(n_train_batches, patience / 2) |
286 | 290 | # go through this many |
287 | 291 | # minibatche before checking the network |
288 | 292 | # on the validation set; in this case we |
289 | 293 | # check every epoch |
290 | 294 |
|
291 | | - |
292 | | - best_params = None |
| 295 | + best_params = None |
293 | 296 | best_validation_loss = numpy.inf |
294 | | - best_iter = 0 |
295 | | - test_score = 0. |
| 297 | + best_iter = 0 |
| 298 | + test_score = 0. |
296 | 299 | start_time = time.clock() |
297 | 300 |
|
298 | 301 | epoch = 0 |
@@ -306,21 +309,21 @@ def test_mlp( learning_rate=0.01, L1_reg = 0.00, L2_reg = 0.0001, n_epochs=1000, |
306 | 309 | # iteration number |
307 | 310 | iter = epoch * n_train_batches + minibatch_index |
308 | 311 |
|
309 | | - if (iter+1) % validation_frequency == 0: |
| 312 | + if (iter + 1) % validation_frequency == 0: |
310 | 313 | # compute zero-one loss on validation set |
311 | | - validation_losses = [validate_model(i) for i in xrange(n_valid_batches)] |
| 314 | + validation_losses = [validate_model(i) for i |
| 315 | + in xrange(n_valid_batches)] |
312 | 316 | this_validation_loss = numpy.mean(validation_losses) |
313 | 317 |
|
314 | | - print('epoch %i, minibatch %i/%i, validation error %f %%' % \ |
315 | | - (epoch, minibatch_index+1,n_train_batches, \ |
316 | | - this_validation_loss*100.)) |
317 | | - |
| 318 | + print('epoch %i, minibatch %i/%i, validation error %f %%' % |
| 319 | + (epoch, minibatch_index + 1, n_train_batches, |
| 320 | + this_validation_loss * 100.)) |
318 | 321 |
|
319 | 322 | # if we got the best validation score until now |
320 | 323 | if this_validation_loss < best_validation_loss: |
321 | 324 | #improve patience if loss improvement is good enough |
322 | 325 | if this_validation_loss < best_validation_loss * \ |
323 | | - improvement_threshold : |
| 326 | + improvement_threshold: |
324 | 327 | patience = max(patience, iter * patience_increase) |
325 | 328 |
|
326 | 329 | best_validation_loss = this_validation_loss |
@@ -330,21 +333,22 @@ def test_mlp( learning_rate=0.01, L1_reg = 0.00, L2_reg = 0.0001, n_epochs=1000, |
330 | 333 | test_score = numpy.mean(test_losses) |
331 | 334 |
|
332 | 335 | print((' epoch %i, minibatch %i/%i, test error of best ' |
333 | | - 'model %f %%') % \ |
334 | | - (epoch, minibatch_index+1, n_train_batches,test_score*100.)) |
| 336 | + 'model %f %%') % |
| 337 | + (epoch, minibatch_index + 1, n_train_batches, |
| 338 | + test_score * 100.)) |
335 | 339 |
|
336 | | - if patience <= iter : |
| 340 | + if patience <= iter: |
337 | 341 | done_looping = True |
338 | 342 | break |
339 | 343 |
|
340 | | - |
341 | 344 | end_time = time.clock() |
342 | 345 | print(('Optimization complete. Best validation score of %f %% ' |
343 | 346 | 'obtained at iteration %i, with test performance %f %%') % |
344 | | - (best_validation_loss * 100., best_iter, test_score*100.)) |
345 | | - print >> sys.stderr, ('The code for file '+os.path.split(__file__)[1]+' ran for %.2fm' % ((end_time-start_time)/60.)) |
| 347 | + (best_validation_loss * 100., best_iter, test_score * 100.)) |
| 348 | + print >> sys.stderr, ('The code for file ' + |
| 349 | + os.path.split(__file__)[1] + |
| 350 | + ' ran for %.2fm' % ((end_time - start_time) / 60.)) |
346 | 351 |
|
347 | 352 |
|
348 | 353 | if __name__ == '__main__': |
349 | 354 | test_mlp() |
350 | | - |
|