GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — pep8 · starimpact/DeepLearningTutorials@da46247

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • code
    • mlp.py
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎code/mlp.py‎

Copy file name to clipboardExpand all lines: code/mlp.py
+75-71Lines changed: 75 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,13 @@
2121
__docformat__ = 'restructedtext en'
2222

2323

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
2531

2632
import theano
2733
import theano.tensor as T
@@ -31,7 +37,8 @@
3137

3238

3339
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):
3542
"""
3643
Typical hidden layer of a MLP: units are fully-connected and have
3744
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
6976
# For example, results presented in [Xavier10] suggest that you
7077
# should use 4 times larger initial weights for sigmoid
7178
# 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.
7381
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)
7886
if activation == theano.tensor.nnet.sigmoid:
7987
W_values *= 4
8088

81-
W = theano.shared(value = W_values, name ='W')
89+
W = theano.shared(value=W_values, name='W')
8290

8391
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')
8694

8795
self.W = W
8896
self.b = b
8997

9098
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))
92101
# parameters of the model
93102
self.params = [self.W, self.b]
94103

@@ -104,8 +113,6 @@ class MLP(object):
104113
class).
105114
"""
106115

107-
108-
109116
def __init__(self, rng, input, n_in, n_hidden, n_out):
110117
"""Initialize the parameters for the multilayer perceptron
111118
@@ -133,16 +140,16 @@ def __init__(self, rng, input, n_in, n_hidden, n_out):
133140
# translate into a TanhLayer connected to the LogisticRegression
134141
# layer; this can be replaced by a SigmoidalLayer, or a layer
135142
# 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)
139146

140147
# The logistic regression layer gets as input the hidden units
141148
# of the hidden layer
142149
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)
146153

147154
# L1 norm ; one regularization option is to enforce L1 norm to
148155
# be small
@@ -151,8 +158,8 @@ def __init__(self, rng, input, n_in, n_hidden, n_out):
151158

152159
# square of L2 norm ; one regularization option is to enforce
153160
# 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()
156163

157164
# negative log likelihood of the MLP is given by the negative
158165
# 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):
166173
self.params = self.hiddenLayer.params + self.logRegressionLayer.params
167174

168175

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):
171178
"""
172179
Demonstrate stochastic gradient descent optimization for a multilayer
173180
perceptron
@@ -191,22 +198,20 @@ def test_mlp( learning_rate=0.01, L1_reg = 0.00, L2_reg = 0.0001, n_epochs=1000,
191198
192199
:type dataset: string
193200
: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
195202
196203
197204
"""
198205
datasets = load_data(dataset)
199206

200207
train_set_x, train_set_y = datasets[0]
201208
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]
205210

206211
# compute number of minibatches for training, validation and testing
207212
n_train_batches = train_set_x.get_value(borrow=True).shape[0] / batch_size
208213
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
210215

211216
######################
212217
# 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,
215220

216221
# allocate symbolic variables for the data
217222
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
221226

222227
rng = numpy.random.RandomState(1234)
223228

224229
# 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)
226231

227232
# the cost we minimize during training is the negative log likelihood of
228233
# 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,
233238

234239
# compiling a Theano function that computes the mistakes that are made
235240
# 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),
238243
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]})
241246

242-
validate_model = theano.function(inputs = [index],
243-
outputs = classifier.errors(y),
247+
validate_model = theano.function(inputs=[index],
248+
outputs=classifier.errors(y),
244249
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]})
247252

248253
# compute the gradient of cost with respect to theta (sotred in params)
249254
# the resulting gradients will be stored in a list gparams
250255
gparams = []
251256
for param in classifier.params:
252-
gparam = T.grad(cost, param)
257+
gparam = T.grad(cost, param)
253258
gparams.append(gparam)
254259

255-
256260
# specify how to update the parameters of the model as a dictionary
257261
updates = {}
258262
# given two list the zip A = [ a1,a2,a3,a4] and B = [b1,b2,b3,b4] of
259263
# same length, zip generates a list C of same size, where each element
260264
# is a pair formed from the two lists :
261265
# C = [ (a1,b1), (a2,b2), (a3,b3) , (a4,b4) ]
262266
for param, gparam in zip(classifier.params, gparams):
263-
updates[param] = param - learning_rate*gparam
267+
updates[param] = param - learning_rate * gparam
264268

265269
# compiling a Theano function `train_model` that returns the cost, but
266270
# in the same time updates the parameter of the model based on the rules
267271
# 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,
270274
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]})
273277

274278
###############
275279
# TRAIN MODEL #
276280
###############
277281
print '... training'
278282

279283
# 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)
286290
# go through this many
287291
# minibatche before checking the network
288292
# on the validation set; in this case we
289293
# check every epoch
290294

291-
292-
best_params = None
295+
best_params = None
293296
best_validation_loss = numpy.inf
294-
best_iter = 0
295-
test_score = 0.
297+
best_iter = 0
298+
test_score = 0.
296299
start_time = time.clock()
297300

298301
epoch = 0
@@ -306,21 +309,21 @@ def test_mlp( learning_rate=0.01, L1_reg = 0.00, L2_reg = 0.0001, n_epochs=1000,
306309
# iteration number
307310
iter = epoch * n_train_batches + minibatch_index
308311

309-
if (iter+1) % validation_frequency == 0:
312+
if (iter + 1) % validation_frequency == 0:
310313
# 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)]
312316
this_validation_loss = numpy.mean(validation_losses)
313317

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.))
318321

319322
# if we got the best validation score until now
320323
if this_validation_loss < best_validation_loss:
321324
#improve patience if loss improvement is good enough
322325
if this_validation_loss < best_validation_loss * \
323-
improvement_threshold :
326+
improvement_threshold:
324327
patience = max(patience, iter * patience_increase)
325328

326329
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,
330333
test_score = numpy.mean(test_losses)
331334

332335
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.))
335339

336-
if patience <= iter :
340+
if patience <= iter:
337341
done_looping = True
338342
break
339343

340-
341344
end_time = time.clock()
342345
print(('Optimization complete. Best validation score of %f %% '
343346
'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.))
346351

347352

348353
if __name__ == '__main__':
349354
test_mlp()
350-

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.