GeezerVison is showing github.com — Used start-snippet-# and end-snippet-# for precise inclusion of code … · iamsile/DeepLearningTutorials@7d867f0
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 +76-39Lines changed: 76 additions & 39 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 17 | 17 | from rbm import RBM | 18 | 18 |
| 19 | 19 |
| | 20 | +# start-snippet-1 | 20 | 21 | class DBN(object): | 21 | 22 | """Deep Belief Network | 22 | 23 |
| @@ -65,7 +66,7 @@ def __init__(self, numpy_rng, theano_rng=None, n_ins=784, | 65 | 66 | self.x = T.matrix('x') # the data is presented as rasterized images | 66 | 67 | self.y = T.ivector('y') # the labels are presented as 1D vector | 67 | 68 | # of [int] labels | 68 | | - | | 69 | + # end-snippet-1 | 69 | 70 | # The DBN is an MLP, for which all weights of intermediate | 70 | 71 | # layers are shared with a different RBM. We will first | 71 | 72 | # construct the DBN as a deep multilayer perceptron, and when | @@ -174,12 +175,14 @@ def pretraining_functions(self, train_set_x, batch_size, k): | 174 | 175 | persistent=None, k=k) | 175 | 176 |
| 176 | 177 | # compile the theano function | 177 | | - fn = theano.function(inputs=[index, | 178 | | - theano.Param(learning_rate, default=0.1)], | 179 | | - outputs=cost, | 180 | | - updates=updates, | 181 | | - givens={self.x: | 182 | | - train_set_x[batch_begin:batch_end]}) | | 178 | + fn = theano.function( | | 179 | + inputs=[index, theano.Param(learning_rate, default=0.1)], | | 180 | + outputs=cost, | | 181 | + updates=updates, | | 182 | + givens={ | | 183 | + self.x: train_set_x[batch_begin:batch_end] | | 184 | + } | | 185 | + ) | 183 | 186 | # append `fn` to the list of functions | 184 | 187 | pretrain_fns.append(fn) | 185 | 188 |
| @@ -224,25 +227,45 @@ def build_finetune_functions(self, datasets, batch_size, learning_rate): | 224 | 227 | for param, gparam in zip(self.params, gparams): | 225 | 228 | updates.append((param, param - gparam * learning_rate)) | 226 | 229 |
| 227 | | - train_fn = theano.function(inputs=[index], | 228 | | - outputs=self.finetune_cost, | 229 | | - updates=updates, | 230 | | - givens={self.x: train_set_x[index * batch_size: | 231 | | - (index + 1) * batch_size], | 232 | | - self.y: train_set_y[index * batch_size: | 233 | | - (index + 1) * batch_size]}) | 234 | | - | 235 | | - test_score_i = theano.function([index], self.errors, | 236 | | - givens={self.x: test_set_x[index * batch_size: | 237 | | - (index + 1) * batch_size], | 238 | | - self.y: test_set_y[index * batch_size: | 239 | | - (index + 1) * batch_size]}) | 240 | | - | 241 | | - valid_score_i = theano.function([index], self.errors, | 242 | | - givens={self.x: valid_set_x[index * batch_size: | 243 | | - (index + 1) * batch_size], | 244 | | - self.y: valid_set_y[index * batch_size: | 245 | | - (index + 1) * batch_size]}) | | 230 | + train_fn = theano.function( | | 231 | + inputs=[index], | | 232 | + outputs=self.finetune_cost, | | 233 | + updates=updates, | | 234 | + givens={ | | 235 | + self.x: train_set_x[ | | 236 | + index * batch_size: (index + 1) * batch_size | | 237 | + ], | | 238 | + self.y: train_set_y[ | | 239 | + index * batch_size: (index + 1) * batch_size | | 240 | + ] | | 241 | + } | | 242 | + ) | | 243 | + | | 244 | + test_score_i = theano.function( | | 245 | + [index], | | 246 | + self.errors, | | 247 | + givens={ | | 248 | + self.x: test_set_x[ | | 249 | + index * batch_size: (index + 1) * batch_size | | 250 | + ], | | 251 | + self.y: test_set_y[ | | 252 | + index * batch_size: (index + 1) * batch_size | | 253 | + ] | | 254 | + } | | 255 | + ) | | 256 | + | | 257 | + valid_score_i = theano.function( | | 258 | + [index], | | 259 | + self.errors, | | 260 | + givens={ | | 261 | + self.x: valid_set_x[ | | 262 | + index * batch_size: (index + 1) * batch_size | | 263 | + ], | | 264 | + self.y: valid_set_y[ | | 265 | + index * batch_size: (index + 1) * batch_size | | 266 | + ] | | 267 | + } | | 268 | + ) | 246 | 269 |
| 247 | 270 | # Create a function that scans the entire validation set | 248 | 271 | def valid_score(): | @@ -296,6 +319,7 @@ def test_DBN(finetune_lr=0.1, pretraining_epochs=100, | 296 | 319 | hidden_layers_sizes=[1000, 1000, 1000], | 297 | 320 | n_outs=10) | 298 | 321 |
| | 322 | + # start-snippet-2 | 299 | 323 | ######################### | 300 | 324 | # PRETRAINING THE MODEL # | 301 | 325 | ######################### | @@ -319,21 +343,23 @@ def test_DBN(finetune_lr=0.1, pretraining_epochs=100, | 319 | 343 | print numpy.mean(c) | 320 | 344 |
| 321 | 345 | end_time = time.clock() | | 346 | + # end-snippet-2 | 322 | 347 | print >> sys.stderr, ('The pretraining code for file ' + | 323 | 348 | os.path.split(__file__)[1] + | 324 | 349 | ' ran for %.2fm' % ((end_time - start_time) / 60.)) | 325 | | - | 326 | 350 | ######################## | 327 | 351 | # FINETUNING THE MODEL # | 328 | 352 | ######################## | 329 | 353 |
| 330 | 354 | # get the training, validation and testing function for the model | 331 | 355 | print '... getting the finetuning functions' | 332 | 356 | train_fn, validate_model, test_model = dbn.build_finetune_functions( | 333 | | - datasets=datasets, batch_size=batch_size, | 334 | | - learning_rate=finetune_lr) | | 357 | + datasets=datasets, | | 358 | + batch_size=batch_size, | | 359 | + learning_rate=finetune_lr | | 360 | + ) | 335 | 361 |
| 336 | | - print '... finetunning the model' | | 362 | + print '... finetuning the model' | 337 | 363 | # early-stopping parameters | 338 | 364 | patience = 4 * n_train_batches # look as this many examples regardless | 339 | 365 | patience_increase = 2. # wait this much longer when a new best is | @@ -342,7 +368,7 @@ def test_DBN(finetune_lr=0.1, pretraining_epochs=100, | 342 | 368 | # considered significant | 343 | 369 | validation_frequency = min(n_train_batches, patience / 2) | 344 | 370 | # go through this many | 345 | | - # minibatche before checking the network | | 371 | + # minibatches before checking the network | 346 | 372 | # on the validation set; in this case we | 347 | 373 | # check every epoch | 348 | 374 |
| @@ -365,16 +391,24 @@ def test_DBN(finetune_lr=0.1, pretraining_epochs=100, | 365 | 391 |
| 366 | 392 | validation_losses = validate_model() | 367 | 393 | this_validation_loss = numpy.mean(validation_losses) | 368 | | - print('epoch %i, minibatch %i/%i, validation error %f %%' % \ | 369 | | - (epoch, minibatch_index + 1, n_train_batches, | 370 | | - this_validation_loss * 100.)) | | 394 | + print( | | 395 | + 'epoch %i, minibatch %i/%i, validation error %f %%' | | 396 | + % ( | | 397 | + epoch, | | 398 | + minibatch_index + 1, | | 399 | + n_train_batches, | | 400 | + this_validation_loss * 100. | | 401 | + ) | | 402 | + ) | 371 | 403 |
| 372 | 404 | # if we got the best validation score until now | 373 | 405 | if this_validation_loss < best_validation_loss: | 374 | 406 |
| 375 | 407 | #improve patience if loss improvement is good enough | 376 | | - if (this_validation_loss < best_validation_loss * | 377 | | - improvement_threshold): | | 408 | + if ( | | 409 | + this_validation_loss < best_validation_loss * | | 410 | + improvement_threshold | | 411 | + ): | 378 | 412 | patience = max(patience, iter * patience_increase) | 379 | 413 |
| 380 | 414 | # save best validation score and iteration number | @@ -394,9 +428,12 @@ def test_DBN(finetune_lr=0.1, pretraining_epochs=100, | 394 | 428 | break | 395 | 429 |
| 396 | 430 | end_time = time.clock() | 397 | | - print(('Optimization complete with best validation score of %f %%,' | 398 | | - 'with test performance %f %%') % | 399 | | - (best_validation_loss * 100., test_score * 100.)) | | 431 | + print( | | 432 | + ( | | 433 | + 'Optimization complete with best validation score of %f %%,' | | 434 | + 'with test performance %f %%' | | 435 | + ) % (best_validation_loss * 100., test_score * 100.) | | 436 | + ) | 400 | 437 | print >> sys.stderr, ('The fine tuning code for file ' + | 401 | 438 | os.path.split(__file__)[1] + | 402 | 439 | ' ran for %.2fm' % ((end_time - start_time) | |
Collapse file Copy file name to clipboardExpand all lines: code/SdA.py +44-25Lines changed: 44 additions & 25 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 46 | 46 | from dA import dA | 47 | 47 |
| 48 | 48 |
| | 49 | +# start-snippet-1 | 49 | 50 | class SdA(object): | 50 | 51 | """Stacked denoising auto-encoder class (SdA) | 51 | 52 |
| @@ -104,6 +105,7 @@ def __init__( | 104 | 105 | self.x = T.matrix('x') # the data is presented as rasterized images | 105 | 106 | self.y = T.ivector('y') # the labels are presented as 1D vector of | 106 | 107 | # [int] labels | | 108 | + # end-snippet-1 | 107 | 109 |
| 108 | 110 | # The SdA is an MLP, for which all weights of intermediate layers | 109 | 111 | # are shared with a different denoising autoencoders | @@ -115,6 +117,7 @@ def __init__( | 115 | 117 | # During finetunining we will finish training the SdA by doing | 116 | 118 | # stochastich gradient descent on the MLP | 117 | 119 |
| | 120 | + # start-snippet-2 | 118 | 121 | for i in xrange(self.n_layers): | 119 | 122 | # construct the sigmoidal layer | 120 | 123 |
| @@ -157,11 +160,13 @@ def __init__( | 157 | 160 | W=sigmoid_layer.W, | 158 | 161 | bhid=sigmoid_layer.b) | 159 | 162 | self.dA_layers.append(dA_layer) | 160 | | - | | 163 | + # end-snippet-2 | 161 | 164 | # We now need to add a logistic layer on top of the MLP | 162 | 165 | self.logLayer = LogisticRegression( | 163 | | - input=self.sigmoid_layers[-1].output, | 164 | | - n_in=hidden_layers_sizes[-1], n_out=n_outs) | | 166 | + input=self.sigmoid_layers[-1].output, | | 167 | + n_in=hidden_layers_sizes[-1], | | 168 | + n_out=n_outs | | 169 | + ) | 165 | 170 |
| 166 | 171 | self.params.extend(self.logLayer.params) | 167 | 172 | # construct a function that implements one step of finetunining | @@ -210,13 +215,18 @@ def pretraining_functions(self, train_set_x, batch_size): | 210 | 215 | cost, updates = dA.get_cost_updates(corruption_level, | 211 | 216 | learning_rate) | 212 | 217 | # compile the theano function | 213 | | - fn = theano.function(inputs=[index, | 214 | | - theano.Param(corruption_level, default=0.2), | 215 | | - theano.Param(learning_rate, default=0.1)], | 216 | | - outputs=cost, | 217 | | - updates=updates, | 218 | | - givens={self.x: train_set_x[batch_begin: | 219 | | - batch_end]}) | | 218 | + fn = theano.function( | | 219 | + inputs=[ | | 220 | + index, | | 221 | + theano.Param(corruption_level, default=0.2), | | 222 | + theano.Param(learning_rate, default=0.1) | | 223 | + ], | | 224 | + outputs=cost, | | 225 | + updates=updates, | | 226 | + givens={ | | 227 | + self.x: train_set_x[batch_begin: batch_end] | | 228 | + } | | 229 | + ) | 220 | 230 | # append `fn` to the list of functions | 221 | 231 | pretrain_fns.append(fn) | 222 | 232 |
| @@ -282,12 +292,12 @@ def build_finetune_functions(self, datasets, batch_size, learning_rate): | 282 | 292 | [index], | 283 | 293 | self.errors, | 284 | 294 | givens={ | 285 | | - self.x: test_set_x[ | 286 | | - index * batch_size: (index + 1) * batch_size | 287 | | - ], | 288 | | - self.y: test_set_y[ | 289 | | - index * batch_size: (index + 1) * batch_size | 290 | | - ] | | 295 | + self.x: test_set_x[ | | 296 | + index * batch_size: (index + 1) * batch_size | | 297 | + ], | | 298 | + self.y: test_set_y[ | | 299 | + index * batch_size: (index + 1) * batch_size | | 300 | + ] | 291 | 301 | }, | 292 | 302 | name='test' | 293 | 303 | ) | @@ -354,6 +364,7 @@ def test_SdA(finetune_lr=0.1, pretraining_epochs=15, | 354 | 364 | n_train_batches /= batch_size | 355 | 365 |
| 356 | 366 | # numpy random generator | | 367 | + # start-snippet-3 | 357 | 368 | numpy_rng = numpy.random.RandomState(89677) | 358 | 369 | print '... building the model' | 359 | 370 | # construct the stacked denoising autoencoder class | @@ -363,7 +374,7 @@ def test_SdA(finetune_lr=0.1, pretraining_epochs=15, | 363 | 374 | hidden_layers_sizes=[1000, 1000, 1000], | 364 | 375 | n_outs=10 | 365 | 376 | ) | 366 | | - | | 377 | + # end-snippet-3 start-snippet-4 | 367 | 378 | ######################### | 368 | 379 | # PRETRAINING THE MODEL # | 369 | 380 | ######################### | @@ -392,16 +403,18 @@ def test_SdA(finetune_lr=0.1, pretraining_epochs=15, | 392 | 403 | print >> sys.stderr, ('The pretraining code for file ' + | 393 | 404 | os.path.split(__file__)[1] + | 394 | 405 | ' ran for %.2fm' % ((end_time - start_time) / 60.)) | 395 | | - | | 406 | + # end-snippet-4 | 396 | 407 | ######################## | 397 | 408 | # FINETUNING THE MODEL # | 398 | 409 | ######################## | 399 | 410 |
| 400 | 411 | # get the training, validation and testing function for the model | 401 | 412 | print '... getting the finetuning functions' | 402 | 413 | train_fn, validate_model, test_model = sda.build_finetune_functions( | 403 | | - datasets=datasets, batch_size=batch_size, | 404 | | - learning_rate=finetune_lr) | | 414 | + datasets=datasets, | | 415 | + batch_size=batch_size, | | 416 | + learning_rate=finetune_lr | | 417 | + ) | 405 | 418 |
| 406 | 419 | print '... finetunning the model' | 407 | 420 | # early-stopping parameters | @@ -441,8 +454,10 @@ def test_SdA(finetune_lr=0.1, pretraining_epochs=15, | 441 | 454 | if this_validation_loss < best_validation_loss: | 442 | 455 |
| 443 | 456 | #improve patience if loss improvement is good enough | 444 | | - if (this_validation_loss < best_validation_loss * | 445 | | - improvement_threshold): | | 457 | + if ( | | 458 | + this_validation_loss < best_validation_loss * | | 459 | + improvement_threshold | | 460 | + ): | 446 | 461 | patience = max(patience, iter * patience_increase) | 447 | 462 |
| 448 | 463 | # save best validation score and iteration number | @@ -462,9 +477,13 @@ def test_SdA(finetune_lr=0.1, pretraining_epochs=15, | 462 | 477 | break | 463 | 478 |
| 464 | 479 | end_time = time.clock() | 465 | | - print(('Optimization complete with best validation score of %f %%,' | 466 | | - 'with test performance %f %%') % | 467 | | - (best_validation_loss * 100., test_score * 100.)) | | 480 | + print( | | 481 | + ( | | 482 | + 'Optimization complete with best validation score of %f %%,' | | 483 | + 'with test performance %f %%' | | 484 | + ) | | 485 | + % (best_validation_loss * 100., test_score * 100.) | | 486 | + ) | 468 | 487 | print >> sys.stderr, ('The training code for file ' + | 469 | 488 | os.path.split(__file__)[1] + | 470 | 489 | ' ran for %.2fm' % ((end_time - start_time) / 60.)) | |
Collapse file Copy file name to clipboardExpand all lines: code/cA.py +17-10Lines changed: 17 additions & 10 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -131,11 +131,14 @@ def __init__(self, numpy_rng, input=None, n_visible=784, n_hidden=100, | 131 | 131 | # 4*sqrt(6./(n_hidden+n_visible))the output of uniform if | 132 | 132 | # converted using asarray to dtype | 133 | 133 | # theano.config.floatX so that the code is runable on GPU | 134 | | - initial_W = numpy.asarray(numpy_rng.uniform( | 135 | | - low=-4 * numpy.sqrt(6. / (n_hidden + n_visible)), | 136 | | - high=4 * numpy.sqrt(6. / (n_hidden + n_visible)), | 137 | | - size=(n_visible, n_hidden)), | 138 | | - dtype=theano.config.floatX) | | 134 | + initial_W = numpy.asarray( | | 135 | + numpy_rng.uniform( | | 136 | + low=-4 * numpy.sqrt(6. / (n_hidden + n_visible)), | | 137 | + high=4 * numpy.sqrt(6. / (n_hidden + n_visible)), | | 138 | + size=(n_visible, n_hidden) | | 139 | + ), | | 140 | + dtype=theano.config.floatX | | 141 | + ) | 139 | 142 | W = theano.shared(value=initial_W, name='W', borrow=True) | 140 | 143 |
| 141 | 144 | if not bvis: | @@ -186,7 +189,7 @@ def get_reconstructed_input(self, hidden): | 186 | 189 | hidden layer | 187 | 190 |
| 188 | 191 | """ | 189 | | - return T.nnet.sigmoid(T.dot(hidden, self.W_prime) + self.b_prime) | | 192 | + return T.nnet.sigmoid(T.dot(hidden, self.W_prime) + self.b_prime) | 190 | 193 |
| 191 | 194 | def get_cost_updates(self, contraction_level, learning_rate): | 192 | 195 | """ This function computes the cost and the updates for one trainng | @@ -265,10 +268,14 @@ def test_cA(learning_rate=0.01, training_epochs=20, | 265 | 268 | cost, updates = ca.get_cost_updates(contraction_level=contraction_level, | 266 | 269 | learning_rate=learning_rate) | 267 | 270 |
| 268 | | - train_ca = theano.function([index], [T.mean(ca.L_rec), ca.L_jacob], | 269 | | - updates=updates, | 270 | | - givens={x: train_set_x[index * batch_size: | 271 | | - (index + 1) * batch_size]}) | | 271 | + train_ca = theano.function( | | 272 | + [index], | | 273 | + [T.mean(ca.L_rec), ca.L_jacob], | | 274 | + updates=updates, | | 275 | + givens={ | | 276 | + x: train_set_x[index * batch_size: (index + 1) * batch_size] | | 277 | + } | | 278 | + ) | 272 | 279 |
| 273 | 280 | start_time = time.clock() | 274 | 281 |
| |
|