GeezerVison is showing github.com — Fix a bunch of flake8/pep8 errors · mpage/DeepLearningTutorials@cee690d
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: code/DBN.py +3-5Lines changed: 3 additions & 5 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 1 | 1 | """ | 2 | 2 | """ | 3 | | -import cPickle | 4 | | -import gzip | 5 | 3 | import os | 6 | 4 | import sys | 7 | 5 | import time | @@ -372,7 +370,6 @@ def test_DBN(finetune_lr=0.1, pretraining_epochs=100, | 372 | 370 | # on the validation set; in this case we | 373 | 371 | # check every epoch | 374 | 372 |
| 375 | | - best_params = None | 376 | 373 | best_validation_loss = numpy.inf | 377 | 374 | test_score = 0. | 378 | 375 | start_time = time.clock() | @@ -430,9 +427,10 @@ def test_DBN(finetune_lr=0.1, pretraining_epochs=100, | 430 | 427 | end_time = time.clock() | 431 | 428 | print( | 432 | 429 | ( | 433 | | - 'Optimization complete with best validation score of %f %%,' | | 430 | + 'Optimization complete with best validation score of %f %%, ' | | 431 | + 'obtained at iteration %i, ' | 434 | 432 | 'with test performance %f %%' | 435 | | - ) % (best_validation_loss * 100., test_score * 100.) | | 433 | + ) % (best_validation_loss * 100., best_iter + 1, test_score * 100.) | 436 | 434 | ) | 437 | 435 | print >> sys.stderr, ('The fine tuning code for file ' + | 438 | 436 | os.path.split(__file__)[1] + | |
Collapse file Copy file name to clipboardExpand all lines: code/SdA.py +3-7Lines changed: 3 additions & 7 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 29 | 29 | Systems 19, 2007 | 30 | 30 |
| 31 | 31 | """ | 32 | | -import cPickle | 33 | | -import gzip | 34 | 32 | import os | 35 | 33 | import sys | 36 | 34 | import time | @@ -202,8 +200,6 @@ def pretraining_functions(self, train_set_x, batch_size): | 202 | 200 | index = T.lscalar('index') # index to a minibatch | 203 | 201 | corruption_level = T.scalar('corruption') # % of corruption to use | 204 | 202 | learning_rate = T.scalar('lr') # learning rate to use | 205 | | - # number of batches | 206 | | - n_batches = train_set_x.get_value(borrow=True).shape[0] / batch_size | 207 | 203 | # begining of a batch, given `index` | 208 | 204 | batch_begin = index * batch_size | 209 | 205 | # ending of a batch given `index` | @@ -429,7 +425,6 @@ def test_SdA(finetune_lr=0.1, pretraining_epochs=15, | 429 | 425 | # on the validation set; in this case we | 430 | 426 | # check every epoch | 431 | 427 |
| 432 | | - best_params = None | 433 | 428 | best_validation_loss = numpy.inf | 434 | 429 | test_score = 0. | 435 | 430 | start_time = time.clock() | @@ -479,10 +474,11 @@ def test_SdA(finetune_lr=0.1, pretraining_epochs=15, | 479 | 474 | end_time = time.clock() | 480 | 475 | print( | 481 | 476 | ( | 482 | | - 'Optimization complete with best validation score of %f %%,' | | 477 | + 'Optimization complete with best validation score of %f %%, ' | | 478 | + 'on iteration %i, ' | 483 | 479 | 'with test performance %f %%' | 484 | 480 | ) | 485 | | - % (best_validation_loss * 100., test_score * 100.) | | 481 | + % (best_validation_loss * 100., best_iter + 1, test_score * 100.) | 486 | 482 | ) | 487 | 483 | print >> sys.stderr, ('The training code for file ' + | 488 | 484 | os.path.split(__file__)[1] + | |
Collapse file Copy file name to clipboardExpand all lines: code/cA.py +8-9Lines changed: 8 additions & 9 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 12 | 12 | squared Frobenius norm of the Jacobian of the hidden mapping h with | 13 | 13 | respect to the visible units yields the contractive auto-encoder: | 14 | 14 |
| 15 | | - - \sum_{k=1}^d[ x_k \log z_k + (1-x_k) \log( 1-z_k)] + \| \frac{\partial h(x)}{\partial x} \|^2 | | 15 | + - \sum_{k=1}^d[ x_k \log z_k + (1-x_k) \log( 1-z_k)] | | 16 | + + \| \frac{\partial h(x)}{\partial x} \|^2 | 16 | 17 |
| 17 | 18 | References : | 18 | 19 | - S. Rifai, P. Vincent, X. Muller, X. Glorot, Y. Bengio: Contractive | | 27 | 28 | Systems 19, 2007 | 28 | 29 |
| 29 | 30 | """ | 30 | | -import cPickle | 31 | | -import gzip | 32 | 31 | import os | 33 | 32 | import sys | 34 | 33 | import time | @@ -79,11 +78,11 @@ class cA(object): | 79 | 78 |
| 80 | 79 | def __init__(self, numpy_rng, input=None, n_visible=784, n_hidden=100, | 81 | 80 | n_batchsize=1, W=None, bhid=None, bvis=None): | 82 | | - """Initialize the cA class by specifying the number of visible units (the | 83 | | - dimension d of the input ), the number of hidden units ( the dimension | 84 | | - d' of the latent or hidden space ) and the contraction level. The | 85 | | - constructor also receives symbolic variables for the input, weights and | 86 | | - bias. | | 81 | + """Initialize the cA class by specifying the number of visible units | | 82 | + (the dimension d of the input), the number of hidden units (the | | 83 | + dimension d' of the latent or hidden space) and the contraction level. | | 84 | + The constructor also receives symbolic variables for the input, weights | | 85 | + and bias. | 87 | 86 |
| 88 | 87 | :type numpy_rng: numpy.random.RandomState | 89 | 88 | :param numpy_rng: number random generator used to generate weights | @@ -161,7 +160,7 @@ def __init__(self, numpy_rng, input=None, n_visible=784, n_hidden=100, | 161 | 160 | self.W_prime = self.W.T | 162 | 161 |
| 163 | 162 | # if no input is given, generate a variable representing the input | 164 | | - if input == None: | | 163 | + if input is None: | 165 | 164 | # we use a matrix because we expect a minibatch of several | 166 | 165 | # examples, each example being a row | 167 | 166 | self.x = T.dmatrix(name='input') | |
Collapse file Copy file name to clipboardExpand all lines: code/convolutional_mlp.py +13-16Lines changed: 13 additions & 16 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 21 | 21 | http://yann.lecun.com/exdb/publis/pdf/lecun-98.pdf | 22 | 22 |
| 23 | 23 | """ | 24 | | -import cPickle | 25 | | -import gzip | 26 | 24 | import os | 27 | 25 | import sys | 28 | 26 | import time | @@ -53,14 +51,14 @@ def __init__(self, rng, input, filter_shape, image_shape, poolsize=(2, 2)): | 53 | 51 |
| 54 | 52 | :type filter_shape: tuple or list of length 4 | 55 | 53 | :param filter_shape: (number of filters, num input feature maps, | 56 | | - filter height,filter width) | | 54 | + filter height, filter width) | 57 | 55 |
| 58 | 56 | :type image_shape: tuple or list of length 4 | 59 | 57 | :param image_shape: (batch size, num input feature maps, | 60 | 58 | image height, image width) | 61 | 59 |
| 62 | 60 | :type poolsize: tuple or list of length 2 | 63 | | - :param poolsize: the downsampling (pooling) factor (#rows,#cols) | | 61 | + :param poolsize: the downsampling (pooling) factor (#rows, #cols) | 64 | 62 | """ | 65 | 63 |
| 66 | 64 | assert image_shape[1] == filter_shape[1] | @@ -104,7 +102,7 @@ def __init__(self, rng, input, filter_shape, image_shape, poolsize=(2, 2)): | 104 | 102 | ) | 105 | 103 |
| 106 | 104 | # add the bias term. Since the bias is a vector (1D array), we first | 107 | | - # reshape it to a tensor of shape (1,n_filters,1,1). Each bias will | | 105 | + # reshape it to a tensor of shape (1, n_filters, 1, 1). Each bias will | 108 | 106 | # thus be broadcasted across mini-batches and feature map | 109 | 107 | # width & height | 110 | 108 | self.output = T.tanh(pooled_out + self.b.dimshuffle('x', 0, 'x', 'x')) | @@ -155,21 +153,21 @@ def evaluate_lenet5(learning_rate=0.1, n_epochs=200, | 155 | 153 | x = T.matrix('x') # the data is presented as rasterized images | 156 | 154 | y = T.ivector('y') # the labels are presented as 1D vector of | 157 | 155 | # [int] labels | 158 | | - ishape = (28, 28) # this is the size of MNIST images | 159 | 156 |
| 160 | 157 | ###################### | 161 | 158 | # BUILD ACTUAL MODEL # | 162 | 159 | ###################### | 163 | 160 | print '... building the model' | 164 | 161 |
| 165 | | - # Reshape matrix of rasterized images of shape (batch_size,28*28) | | 162 | + # Reshape matrix of rasterized images of shape (batch_size, 28 * 28) | 166 | 163 | # to a 4D tensor, compatible with our LeNetConvPoolLayer | | 164 | + # (28, 28) is the size of MNIST images. | 167 | 165 | layer0_input = x.reshape((batch_size, 1, 28, 28)) | 168 | 166 |
| 169 | 167 | # Construct the first convolutional pooling layer: | 170 | | - # filtering reduces the image size to (28-5+1,28-5+1)=(24,24) | 171 | | - # maxpooling reduces this further to (24/2,24/2) = (12,12) | 172 | | - # 4D output tensor is thus of shape (batch_size,nkerns[0],12,12) | | 168 | + # filtering reduces the image size to (28-5+1 , 28-5+1) = (24, 24) | | 169 | + # maxpooling reduces this further to (24/2, 24/2) = (12, 12) | | 170 | + # 4D output tensor is thus of shape (batch_size, nkerns[0], 12, 12) | 173 | 171 | layer0 = LeNetConvPoolLayer( | 174 | 172 | rng, | 175 | 173 | input=layer0_input, | @@ -179,9 +177,9 @@ def evaluate_lenet5(learning_rate=0.1, n_epochs=200, | 179 | 177 | ) | 180 | 178 |
| 181 | 179 | # Construct the second convolutional pooling layer | 182 | | - # filtering reduces the image size to (12-5+1,12-5+1)=(8,8) | 183 | | - # maxpooling reduces this further to (8/2,8/2) = (4,4) | 184 | | - # 4D output tensor is thus of shape (nkerns[0],nkerns[1],4,4) | | 180 | + # filtering reduces the image size to (12-5+1, 12-5+1) = (8, 8) | | 181 | + # maxpooling reduces this further to (8/2, 8/2) = (4, 4) | | 182 | + # 4D output tensor is thus of shape (nkerns[0], nkerns[1], 4, 4) | 185 | 183 | layer1 = LeNetConvPoolLayer( | 186 | 184 | rng, | 187 | 185 | input=layer0.output, | @@ -240,7 +238,7 @@ def evaluate_lenet5(learning_rate=0.1, n_epochs=200, | 240 | 238 | # SGD Since this model has many parameters, it would be tedious to | 241 | 239 | # manually create an update rule for each model parameter. We thus | 242 | 240 | # create the updates list by automatically looping over all | 243 | | - # (params[i],grads[i]) pairs. | | 241 | + # (params[i], grads[i]) pairs. | 244 | 242 | updates = [ | 245 | 243 | (param_i, param_i - learning_rate * grad_i) | 246 | 244 | for param_i, grad_i in zip(params, grads) | @@ -273,7 +271,6 @@ def evaluate_lenet5(learning_rate=0.1, n_epochs=200, | 273 | 271 | # on the validation set; in this case we | 274 | 272 | # check every epoch | 275 | 273 |
| 276 | | - best_params = None | 277 | 274 | best_validation_loss = numpy.inf | 278 | 275 | best_iter = 0 | 279 | 276 | test_score = 0. | @@ -331,7 +328,7 @@ def evaluate_lenet5(learning_rate=0.1, n_epochs=200, | 331 | 328 |
| 332 | 329 | end_time = time.clock() | 333 | 330 | print('Optimization complete.') | 334 | | - print('Best validation score of %f %% obtained at iteration %i,' | | 331 | + print('Best validation score of %f %% obtained at iteration %i, ' | 335 | 332 | 'with test performance %f %%' % | 336 | 333 | (best_validation_loss * 100., best_iter + 1, test_score * 100.)) | 337 | 334 | print >> sys.stderr, ('The code for file ' + | |
Collapse file Copy file name to clipboardExpand all lines: code/dA.py +1-3Lines changed: 1 addition & 3 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 30 | 30 |
| 31 | 31 | """ | 32 | 32 |
| 33 | | -import cPickle | 34 | | -import gzip | 35 | 33 | import os | 36 | 34 | import sys | 37 | 35 | import time | @@ -185,7 +183,7 @@ def __init__( | 185 | 183 | self.W_prime = self.W.T | 186 | 184 | self.theano_rng = theano_rng | 187 | 185 | # if no input is given, generate a variable representing the input | 188 | | - if input == None: | | 186 | + if input is None: | 189 | 187 | # we use a matrix because we expect a minibatch of several | 190 | 188 | # examples, each example being a row | 191 | 189 | self.x = T.dmatrix(name='input') | |
Collapse file Copy file name to clipboardExpand all lines: code/hmc/hmc.py +46-44Lines changed: 46 additions & 44 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 8 | 8 | from theano import tensor as TT | 9 | 9 | import theano | 10 | 10 |
| 11 | | -sharedX = lambda X, name: \ | 12 | | - shared(numpy.asarray(X, dtype=theano.config.floatX), name=name) | | 11 | +sharedX = (lambda X, name: | | 12 | + shared(numpy.asarray(X, dtype=theano.config.floatX), name=name)) | 13 | 13 |
| 14 | 14 |
| 15 | 15 | def kinetic_energy(vel): | @@ -145,13 +145,14 @@ def leapfrog(pos, vel, step): | 145 | 145 |
| 146 | 146 | # perform leapfrog updates: the scan op is used to repeatedly compute | 147 | 147 | # vel(t + (m-1/2)*stepsize) and pos(t + m*stepsize) for m in [2,n_steps]. | 148 | | - (all_pos, all_vel), scan_updates = theano.scan(leapfrog, | 149 | | - outputs_info=[ | 150 | | - dict(initial=pos_full_step), | 151 | | - dict(initial=vel_half_step), | 152 | | - ], | 153 | | - non_sequences=[stepsize], | 154 | | - n_steps=n_steps - 1) | | 148 | + (all_pos, all_vel), scan_updates = theano.scan( | | 149 | + leapfrog, | | 150 | + outputs_info=[ | | 151 | + dict(initial=pos_full_step), | | 152 | + dict(initial=vel_half_step), | | 153 | + ], | | 154 | + non_sequences=[stepsize], | | 155 | + n_steps=n_steps - 1) | 155 | 156 | final_pos = all_pos[-1] | 156 | 157 | final_vel = all_vel[-1] | 157 | 158 | # NOTE: Scan always returns an updates dictionary, in case the | @@ -171,6 +172,7 @@ def leapfrog(pos, vel, step): | 171 | 172 | # return new proposal state | 172 | 173 | return final_pos, final_vel | 173 | 174 |
| | 175 | + | 174 | 176 | # start-snippet-1 | 175 | 177 | def hmc_move(s_rng, positions, energy_fn, stepsize, n_steps): | 176 | 178 | """ | @@ -224,10 +226,11 @@ def hmc_move(s_rng, positions, energy_fn, stepsize, n_steps): | 224 | 226 | # end-snippet-4 | 225 | 227 | return accept, final_pos | 226 | 228 |
| | 229 | + | 227 | 230 | # start-snippet-5 | 228 | 231 | def hmc_updates(positions, stepsize, avg_acceptance_rate, final_pos, accept, | 229 | | - target_acceptance_rate, stepsize_inc, stepsize_dec, | 230 | | - stepsize_min, stepsize_max, avg_acceptance_slowness): | | 232 | + target_acceptance_rate, stepsize_inc, stepsize_dec, | | 233 | + stepsize_min, stepsize_max, avg_acceptance_slowness): | 231 | 234 | """This function is executed after `n_steps` of HMC sampling | 232 | 235 | (`hmc_move` function). It creates the updates dictionary used by | 233 | 236 | the `simulate` function. It takes care of updating: the position | @@ -293,14 +296,15 @@ def hmc_updates(positions, stepsize, avg_acceptance_rate, final_pos, accept, | 293 | 296 | # perform exponential moving average | 294 | 297 | mean_dtype = theano.scalar.upcast(accept.dtype, avg_acceptance_rate.dtype) | 295 | 298 | new_acceptance_rate = TT.add( | 296 | | - avg_acceptance_slowness * avg_acceptance_rate, | 297 | | - (1.0 - avg_acceptance_slowness) * accept.mean(dtype=mean_dtype)) | | 299 | + avg_acceptance_slowness * avg_acceptance_rate, | | 300 | + (1.0 - avg_acceptance_slowness) * accept.mean(dtype=mean_dtype)) | 298 | 301 | # end-snippet-6 start-snippet-8 | 299 | 302 | return [(positions, new_positions), | 300 | 303 | (stepsize, new_stepsize), | 301 | 304 | (avg_acceptance_rate, new_acceptance_rate)] | 302 | 305 | # end-snippet-8 | 303 | 306 |
| | 307 | + | 304 | 308 | class HMC_sampler(object): | 305 | 309 | """ | 306 | 310 | Convenience wrapper for performing Hybrid Monte Carlo (HMC). It creates the | @@ -322,11 +326,11 @@ def __init__(self, **kwargs): | 322 | 326 |
| 323 | 327 | @classmethod | 324 | 328 | def new_from_shared_positions( | 325 | | - cls, | 326 | | - shared_positions, | | 329 | + cls, | | 330 | + shared_positions, | 327 | 331 | energy_fn, | 328 | | - initial_stepsize=0.01, | 329 | | - target_acceptance_rate=.9, | | 332 | + initial_stepsize=0.01, | | 333 | + target_acceptance_rate=.9, | 330 | 334 | n_steps=20, | 331 | 335 | stepsize_dec=0.98, | 332 | 336 | stepsize_min=0.001, | @@ -350,8 +354,6 @@ def new_from_shared_positions( | 350 | 354 | sampling to work. | 351 | 355 |
| 352 | 356 | """ | 353 | | - batchsize = shared_positions.shape[0] | 354 | | - | 355 | 357 | # allocate shared variables | 356 | 358 | stepsize = sharedX(initial_stepsize, 'hmc_stepsize') | 357 | 359 | avg_acceptance_rate = sharedX(target_acceptance_rate, | @@ -360,40 +362,40 @@ def new_from_shared_positions( | 360 | 362 |
| 361 | 363 | # define graph for an `n_steps` HMC simulation | 362 | 364 | accept, final_pos = hmc_move( | 363 | | - s_rng, | 364 | | - shared_positions, | 365 | | - energy_fn, | 366 | | - stepsize, | 367 | | - n_steps) | | 365 | + s_rng, | | 366 | + shared_positions, | | 367 | + energy_fn, | | 368 | + stepsize, | | 369 | + n_steps) | 368 | 370 |
| 369 | 371 | # define the dictionary of updates, to apply on every `simulate` call | 370 | 372 | simulate_updates = hmc_updates( | 371 | | - shared_positions, | 372 | | - stepsize, | 373 | | - avg_acceptance_rate, | 374 | | - final_pos=final_pos, | 375 | | - accept=accept, | 376 | | - stepsize_min=stepsize_min, | 377 | | - stepsize_max=stepsize_max, | 378 | | - stepsize_inc=stepsize_inc, | 379 | | - stepsize_dec=stepsize_dec, | 380 | | - target_acceptance_rate=target_acceptance_rate, | 381 | | - avg_acceptance_slowness=avg_acceptance_slowness) | | 373 | + shared_positions, | | 374 | + stepsize, | | 375 | + avg_acceptance_rate, | | 376 | + final_pos=final_pos, | | 377 | + accept=accept, | | 378 | + stepsize_min=stepsize_min, | | 379 | + stepsize_max=stepsize_max, | | 380 | + stepsize_inc=stepsize_inc, | | 381 | + stepsize_dec=stepsize_dec, | | 382 | + target_acceptance_rate=target_acceptance_rate, | | 383 | + avg_acceptance_slowness=avg_acceptance_slowness) | 382 | 384 |
| 383 | 385 | # compile theano function | 384 | 386 | simulate = function([], [], updates=simulate_updates) | 385 | 387 |
| 386 | 388 | # create HMC_sampler object with the following attributes ... | 387 | 389 | return cls( | 388 | | - positions=shared_positions, | 389 | | - stepsize=stepsize, | 390 | | - stepsize_min=stepsize_min, | 391 | | - stepsize_max=stepsize_max, | 392 | | - avg_acceptance_rate=avg_acceptance_rate, | 393 | | - target_acceptance_rate=target_acceptance_rate, | 394 | | - s_rng=s_rng, | 395 | | - _updates=simulate_updates, | 396 | | - simulate=simulate) | | 390 | + positions=shared_positions, | | 391 | + stepsize=stepsize, | | 392 | + stepsize_min=stepsize_min, | | 393 | + stepsize_max=stepsize_max, | | 394 | + avg_acceptance_rate=avg_acceptance_rate, | | 395 | + target_acceptance_rate=target_acceptance_rate, | | 396 | + s_rng=s_rng, | | 397 | + _updates=simulate_updates, | | 398 | + simulate=simulate) | 397 | 399 |
| 398 | 400 | def draw(self, **kwargs): | 399 | 401 | """ | |
|