GeezerVison is showing github.com — a few typos + a few updates to rbm · willfu/DeepLearningTutorials@cffce58
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/SdA.py +3Lines changed: 3 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -263,6 +263,9 @@ def __init__(self, n_visible= 784, n_hidden= 500, corruption_level = 0.1,\ | 263 | 263 | self.params = [ self.W, self.b, self.b_prime ] | 264 | 264 |
| 265 | 265 |
| | 266 | +class DeepNetwork() | | 267 | + def pretrain( dataset ) | | 268 | + def finetune() | 266 | 269 |
| 267 | 270 |
| 268 | 271 | class SdA(): | |
Collapse file Copy file name to clipboardExpand all lines: code/logistic_cg.py +17-20Lines changed: 17 additions & 20 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -77,9 +77,9 @@ def __init__(self, input, n_in, n_out): | 77 | 77 | # n_in*n_out + n_out elements | 78 | 78 | self.theta = theano.shared( value = numpy.zeros(n_in*n_out+n_out, dtype = theano.config.floatX) ) | 79 | 79 | # W is represented by the fisr n_in*n_out elements of theta | 80 | | - self.W = self.theta[0:n_in*n_out].reshape((n_in,n_out)) | | 80 | + self.W = self.theta[0:n_in*n_out].reshape((n_in,n_out)) | 81 | 81 | # b is the rest (last n_out elements) | 82 | | - self.b = self.theta[n_in*n_out:n_in*n_out+n_out] | | 82 | + self.b = self.theta[n_in*n_out:n_in*n_out+n_out] | 83 | 83 |
| 84 | 84 |
| 85 | 85 | # compute vector of class-membership probabilities in symbolic form | @@ -182,8 +182,7 @@ def shared_dataset(data_xy): | 182 | 182 |
| 183 | 183 |
| 184 | 184 | # construct the logistic regression class | 185 | | - classifier = LogisticRegression( \ | 186 | | - input=x, n_in=28*28, n_out=10) | | 185 | + classifier = LogisticRegression( input=x, n_in=28*28, n_out=10) | 187 | 186 |
| 188 | 187 | # the cost we minimize during training is the negative log likelihood of | 189 | 188 | # the model in symbolic format | @@ -202,21 +201,19 @@ def shared_dataset(data_xy): | 202 | 201 | y:valid_set_y[minibatch_offset:minibatch_offset+batch_size]}) | 203 | 202 |
| 204 | 203 | # compile a thenao function that returns the cost of a minibatch | 205 | | - batch_cost = theano.function(\ | 206 | | - [minibatch_offset], cost, \ | 207 | | - givens= { | 208 | | - x : train_set_x[minibatch_offset:minibatch_offset+batch_size], | 209 | | - y : train_set_y[minibatch_offset:minibatch_offset+batch_size]}) | | 204 | + batch_cost = theano.function([minibatch_offset], cost, | | 205 | + givens= { | | 206 | + x : train_set_x[minibatch_offset:minibatch_offset+batch_size], | | 207 | + y : train_set_y[minibatch_offset:minibatch_offset+batch_size]}) | 210 | 208 |
| 211 | 209 |
| 212 | 210 |
| 213 | 211 | # compile a theano function that returns the gradient of the minibatch | 214 | 212 | # with respect to theta | 215 | | - batch_grad = theano.function(\ | 216 | | - [minibatch_offset], T.grad(cost,classifier.theta), \ | 217 | | - givens= { | 218 | | - x : train_set_x[minibatch_offset:minibatch_offset+batch_size], | 219 | | - y : train_set_y[minibatch_offset:minibatch_offset+batch_size]}) | | 213 | + batch_grad = theano.function([minibatch_offset], T.grad(cost,classifier.theta), | | 214 | + givens= { | | 215 | + x : train_set_x[minibatch_offset:minibatch_offset+batch_size], | | 216 | + y : train_set_y[minibatch_offset:minibatch_offset+batch_size]}) | 220 | 217 |
| 221 | 218 |
| 222 | 219 | # creates a function that computes the average cost on the training set | @@ -258,12 +255,12 @@ def callback(theta_value): | 258 | 255 | print ("Optimizing using scipy.optimize.fmin_cg...") | 259 | 256 | start_time = time.clock() | 260 | 257 | best_w_b = scipy.optimize.fmin_cg( | 261 | | - f=train_fn, | 262 | | - x0=numpy.zeros((n_in+1)*n_out, dtype=x.dtype), | 263 | | - fprime=train_fn_grad, | 264 | | - callback=callback, | 265 | | - disp=0, | 266 | | - maxiter=n_epochs) | | 258 | + f = train_fn, | | 259 | + x0 = numpy.zeros((n_in+1)*n_out, dtype=x.dtype), | | 260 | + fprime = train_fn_grad, | | 261 | + callback = callback, | | 262 | + disp = 0, | | 263 | + maxiter = n_epochs) | 267 | 264 | end_time = time.clock() | 268 | 265 | print(('Optimization complete with best validation score of %f %%, with ' | 269 | 266 | 'test performance %f %%') % | |
Collapse file Copy file name to clipboardExpand all lines: code/logistic_sgd.py +3-3Lines changed: 3 additions & 3 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -161,7 +161,7 @@ def shared_dataset(data_xy): | 161 | 161 | shared_y = theano.shared(numpy.asarray(data_y, dtype=theano.config.floatX)) | 162 | 162 | return shared_x, T.cast(shared_y, 'int32') | 163 | 163 |
| 164 | | - test_set_x, test_set_y = shared_dataset(test_set) | | 164 | + test_set_x, test_set_y = shared_dataset(test_set) | 165 | 165 | valid_set_x, valid_set_y = shared_dataset(valid_set) | 166 | 166 | train_set_x, train_set_y = shared_dataset(train_set) | 167 | 167 |
| @@ -193,7 +193,7 @@ def shared_dataset(data_xy): | 193 | 193 | x:test_set_x[index*batch_size:(index+1)*batch_size], | 194 | 194 | y:test_set_y[index*batch_size:(index+1)*batch_size]}) | 195 | 195 |
| 196 | | - validate_model =theano.function([index], classifier.errors(y), | | 196 | + validate_model = theano.function([index], classifier.errors(y), | 197 | 197 | givens={ | 198 | 198 | x:valid_set_x[index*batch_size:(index+1)*batch_size], | 199 | 199 | y:valid_set_y[index*batch_size:(index+1)*batch_size]}) | @@ -262,7 +262,7 @@ def shared_dataset(data_xy): | 262 | 262 | # test it on the test set | 263 | 263 |
| 264 | 264 | test_losses = [test_model(i) for i in xrange(n_test_batches)] | 265 | | - test_score = numpy.mean(test_losses) | | 265 | + test_score = numpy.mean(test_losses) | 266 | 266 |
| 267 | 267 | print((' epoch %i, minibatch %i/%i, test error of best ' | 268 | 268 | 'model %f %%') % \ | |
Collapse file Copy file name to clipboardExpand all lines: code/mlp.py +9-9Lines changed: 9 additions & 9 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -75,17 +75,17 @@ def __init__(self, input, n_in, n_hidden, n_out): | 75 | 75 | # the output of uniform if converted using asarray to dtype | 76 | 76 | # theano.config.floatX so that the code is runable on GPU | 77 | 77 | W1_values = numpy.asarray( numpy.random.uniform( \ | 78 | | - low = -numpy.sqrt(6./(n_in+n_hidden)), \ | 79 | | - high = numpy.sqrt(6./(n_in+n_hidden)), \ | 80 | | - size = (n_in, n_hidden)), dtype = theano.config.floatX) | | 78 | + low = -numpy.sqrt(6./(n_in+n_hidden)), \ | | 79 | + high = numpy.sqrt(6./(n_in+n_hidden)), \ | | 80 | + size = (n_in, n_hidden)), dtype = theano.config.floatX) | 81 | 81 | # `W2` is initialized with `W2_values` which is uniformely sampled | 82 | 82 | # from -6./sqrt(n_hidden+n_out) and 6./sqrt(n_hidden+n_out) | 83 | 83 | # the output of uniform if converted using asarray to dtype | 84 | 84 | # theano.config.floatX so that the code is runable on GPU | 85 | 85 | W2_values = numpy.asarray( numpy.random.uniform( | 86 | | - low = -numpy.sqrt(6./(n_hidden+n_out)), \ | 87 | | - high= numpy.sqrt(6./(n_hidden+n_out)),\ | 88 | | - size= (n_hidden, n_out)), dtype = theano.config.floatX) | | 86 | + low = -numpy.sqrt(6./(n_hidden+n_out)), \ | | 87 | + high = numpy.sqrt(6./(n_hidden+n_out)),\ | | 88 | + size = (n_hidden, n_out)), dtype = theano.config.floatX) | 89 | 89 |
| 90 | 90 | self.W1 = theano.shared( value = W1_values ) | 91 | 91 | self.b1 = theano.shared( value = numpy.zeros((n_hidden,), | @@ -98,15 +98,15 @@ def __init__(self, input, n_in, n_hidden, n_out): | 98 | 98 | self.hidden = T.tanh(T.dot(input, self.W1)+ self.b1) | 99 | 99 |
| 100 | 100 | # symbolic expression computing the values of the top layer | 101 | | - self.p_y_given_x= T.nnet.softmax(T.dot(self.hidden, self.W2)+self.b2) | | 101 | + self.p_y_given_x = T.nnet.softmax(T.dot(self.hidden, self.W2)+self.b2) | 102 | 102 |
| 103 | 103 | # compute prediction as class whose probability is maximal in | 104 | 104 | # symbolic form | 105 | 105 | self.y_pred = T.argmax( self.p_y_given_x, axis =1) | 106 | 106 |
| 107 | 107 | # L1 norm ; one regularization option is to enforce L1 norm to | 108 | 108 | # be small | 109 | | - self.L1 = abs(self.W1).sum() + abs(self.W2).sum() | | 109 | + self.L1 = abs(self.W1).sum() + abs(self.W2).sum() | 110 | 110 |
| 111 | 111 | # square of L2 norm ; one regularization option is to enforce | 112 | 112 | # square of L2 norm to be small | @@ -184,7 +184,7 @@ def shared_dataset(data_xy): | 184 | 184 | shared_y = theano.shared(numpy.asarray(data_y, dtype=theano.config.floatX)) | 185 | 185 | return shared_x, T.cast(shared_y, 'int32') | 186 | 186 |
| 187 | | - test_set_x, test_set_y = shared_dataset(test_set) | | 187 | + test_set_x, test_set_y = shared_dataset(test_set) | 188 | 188 | valid_set_x, valid_set_y = shared_dataset(valid_set) | 189 | 189 | train_set_x, train_set_y = shared_dataset(train_set) | 190 | 190 |
| |
Collapse file Copy file name to clipboardExpand all lines: code/rbm.py +64-50Lines changed: 64 additions & 50 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 14 | 14 |
| 15 | 15 | from theano.tensor.shared_randomstreams import RandomStreams | 16 | 16 |
| 17 | | -from theano.sandbox.scan import scan | 18 | | - | 19 | | - | 20 | 17 | class RBM(): | 21 | 18 | """Restricted Boltzmann Machine (RBM) | 22 | 19 | """ | @@ -267,8 +264,7 @@ class RBM_option2(object): | 267 | 264 | *** WRITE THE ENERGY FUNCTION USE SAME LETTERS AS VARIABLE NAMES IN CODE | 268 | 265 | """ | 269 | 266 |
| 270 | | - @classmethod | 271 | | - def new(cls, input=None, n_visible=784, n_hidden=500, | | 267 | + def __init__(self, input=None, n_visible=784, n_hidden=500, | 272 | 268 | W=None, hbias=None, vbias=None, | 273 | 269 | numpy_rng=None): | 274 | 270 | """ | @@ -320,12 +316,7 @@ def new(cls, input=None, n_visible=784, n_hidden=500, | 320 | 316 | # initialize input layer for standalone RBM or layer0 of DBN | 321 | 317 | input = T.dmatrix('input') | 322 | 318 |
| 323 | | - return cls(input, W, hbias, vbias, params) | 324 | | - | 325 | | - def __init__(self, input, W, hbias, vbias, params): | 326 | | - | 327 | | - # setup theano random number generator | 328 | | - self.visible = self.input = input | | 319 | + self.input = input | 329 | 320 | self.W = W | 330 | 321 | self.hbias = hbias | 331 | 322 | self.vbias = vbias | @@ -334,41 +325,62 @@ def __init__(self, input, W, hbias, vbias, params): | 334 | 325 | self.hidden_mean = T.nnet.sigmoid(T.dot(input, W)+hbias) | 335 | 326 | self.hidden_sample = Trng.binomial(self.hidden_mean.shape, 1, self.hidden_mean) | 336 | 327 |
| 337 | | - def gibbs_1(self, v_sample): | 338 | | - # quick change of names internally: v_sample -> v0_sample | 339 | | - v0_sample = v_sample; del v_sample | 340 | | - | 341 | | - h0_mean = T.nnet.sigmoid(T.dot(v0_sample, self.W) + self.hbias) | 342 | | - h0_sample = self.theano_rng.binomial(h0_mean.shape, 1, h0_mean) | 343 | | - v1_mean = T.nnet.sigmoid(T.dot(h0_sample, self.W.T) + self.vbias) | 344 | | - v1_act = self.theano_rng.binomial(v1_mean.shape, 1, v1_mean) | 345 | | - return v1_mean, v1_act | | 328 | + def gibbs_k(self, v_sample, k): | | 329 | + ''' This function implements k steps of Gibbs sampling ''' | | 330 | + | | 331 | + # We compute the visible after k steps of Gibbs by iterating | | 332 | + # over ``gibs_1`` for k times; this can be done in Theano using | | 333 | + # the `scan op`. For a more comprehensive description of scan see | | 334 | + # http://deeplearning.net/software/theano/library/scan.html . | | 335 | + | | 336 | + def gibbs_1(v0_sample, t): | | 337 | + ''' This function implements one Gibbs step ''' | 346 | 338 |
| 347 | | - def gibbs_k(self, k): | 348 | | - def gibbs_steps(v_sample): | 349 | | - v0_sample = v_sample; del v_sample | | 339 | + # compute the activation of the hidden units given a sample of the | | 340 | + # vissibles | 350 | 341 | h0_mean = T.nnet.sigmoid(T.dot(v0_sample, self.W) + self.hbias) | | 342 | + # get a sample of the hiddens given their activation | 351 | 343 | h0_sample = self.theano_rng.binomial(h0_mean.shape, 1, h0_mean) | | 344 | + # compute the activation of the visible given the hidden sample | 352 | 345 | v1_mean = T.nnet.sigmoid(T.dot(h0_sample, self.W.T) + self.vbias) | | 346 | + # get a sample of the visible given their activation | 353 | 347 | v1_act = self.theano_rng.binomial(v1_mean.shape, 1, v1_mean) | 354 | | - | 355 | | - def gibbs_step(v_sample_tm1, v_mean_tm1 ): | 356 | | - h_mean_t = T.nnet.sigmoid(T.dot(v_sample_tm1, self.W) + self.hbias) | 357 | | - h_sample_t = self.theano_rng.binomial(h_mean_t.shape, 1, h_mean_t) | 358 | | - v_mean_t = T.nnet.sigmoid(T.dot(h_sample_t, self.W.T) + self.vbias) | 359 | | - v_sample_t = self.theano_rng.binomial(v_mean_t.shape, 1, v_mean_t) | 360 | | - return v_sample_t, v_mean_t | 361 | | - | 362 | | - v_samples, v_means = scan(gibbs_step, [], [v1_act, v1_mean],[], \ | 363 | | - n_steps = k-1) | 364 | | - return v_means[-1], v_samples[-1] | | 348 | + return [v1_act, v1_mean] | | 349 | + | | 350 | + | | 351 | + | | 352 | + # Because we require as output two values, namely the mean field | | 353 | + # approximation of the visible and the sample obtained after k steps, | | 354 | + # scan needs to know the shape of those two outputs. Scan takes | | 355 | + # this information from the variables containing the initial state | | 356 | + # of the outputs. Since we do not need a initial state of ``v_mean`` | | 357 | + # we provide a dummy one used only to get the correct shape | | 358 | + v_mean = T.zeros_like(v_sample) | | 359 | + | | 360 | + # ``outputs_taps`` is an argument of scan which describes at each | | 361 | + # time step what past values of the outputs the function applied | | 362 | + # recursively needs. This is given in the form of a dictionary, | | 363 | + # where the keys are outputs indexes, and values are a list of | | 364 | + # of the offsets used by the corresponding outputs | | 365 | + # In our case the function ``gibbs_1`` applied recursively, requires | | 366 | + # at time k the past value k-1 for the first output (index 0) and | | 367 | + # no past value of the second output | | 368 | + outputs_taps = { 0 : [-1], 1 : [-1] } | | 369 | + | | 370 | + v_samples, v_means = theano.scan( fn = gibbs_1, | | 371 | + sequences = [], | | 372 | + initial_states = [v_sample, v_mean], | | 373 | + non_sequences = [], | | 374 | + outputs_taps = outputs_taps, | | 375 | + n_steps = k) | | 376 | + return v_means[-1], v_samples[-1] | 365 | 377 |
| 366 | 378 | def free_energy(self, v_sample): | 367 | 379 | h_mean = T.nnet.sigmoid(T.dot(v_sample, self.W) + self.hbias) | 368 | 380 | #TODO: make sure log(sigmoid) is optimized to something stable! | 369 | 381 | return -T.sum(T.log(1.0001-h_mean)) - T.sum(T.dot(v_sample, self.vbias)) | 370 | 382 |
| 371 | | - def cd(self, visible=None, persistent=None, step = None): | | 383 | + def cd(self, visible=None, persistent=None, steps = 1): | 372 | 384 | """ | 373 | 385 | Return a 5-tuple of values related to contrastive divergence: (cost, | 374 | 386 | end-state of negative-phase chain, gradient on weights, gradient on | @@ -378,31 +390,34 @@ def cd(self, visible=None, persistent=None, step = None): | 378 | 390 | If persistent is None, it defaults to self.input | 379 | 391 |
| 380 | 392 | CD aka CD1 - cd() | 381 | | - CD-10 - cd(step=gibbs_k(10)) | | 393 | + CD-10 - cd(steps=10) | 382 | 394 | PCD - cd(persistent=shared(numpy.asarray(initializer))) | 383 | 395 | PCD-k - cd(persistent=shared(numpy.asarray(initializer)), | 384 | | - step=gibbs_k(10)) | | 396 | + steps=10) | 385 | 397 | """ | 386 | 398 | if visible is None: | 387 | 399 | visible = self.input | 388 | 400 |
| 389 | 401 | if visible is None: | 390 | 402 | raise TypeError('visible argument is required when self.input is None') | 391 | 403 |
| 392 | | - if step is None: | 393 | | - step = self.gibbs_1 | 394 | | - | 395 | 404 | if persistent is None: | 396 | 405 | chain_start = visible | 397 | 406 | else: | 398 | 407 | chain_start = persistent | 399 | | - chain_end_mean, chain_end_sample = step(chain_start) | | 408 | + chain_end_mean, chain_end_sample = self.gibbs_k(chain_start, steps) | 400 | 409 |
| 401 | 410 | cost = self.free_energy(visible) - self.free_energy(chain_end_sample) | | 411 | + | | 412 | + # Compute the gradient of the cost with respect to the parameters | | 413 | + # Note the use of argument ``consider_constant``. The reason for | | 414 | + # using this parameter is because the gradient should not try to | | 415 | + # propagate through the gibs chain | | 416 | + gparams = T.grad(cost, self.params, consider_constant = [chain_end_sample]) | | 417 | + | | 418 | + return (cost, chain_end_sample,) + tuple(gparams) | 402 | 419 |
| 403 | | - return (cost, chain_end_sample,) + tuple(T.grad(cost, [self.W, self.hbias, self.vbias])) | 404 | | - | 405 | | - def cd_updates(self, lr, visible=None, persistent=None, step = None): | | 420 | + def cd_updates(self, lr, visible=None, persistent=None, steps = 1): | 406 | 421 | """ | 407 | 422 | Return the learning updates for the RBM parameters that are shared variables. | 408 | 423 |
| @@ -417,7 +432,7 @@ def cd_updates(self, lr, visible=None, persistent=None, step = None): | 417 | 432 |
| 418 | 433 | """ | 419 | 434 |
| 420 | | - cost, chain_end, gW, ghbias, gvbias = self.cd(visible, persistent, step) | | 435 | + cost, chain_end, gW, ghbias, gvbias = self.cd(visible, persistent, steps) | 421 | 436 |
| 422 | 437 | updates = {} | 423 | 438 | if self.W in self.params: | @@ -463,14 +478,13 @@ def shared_dataset(data_xy): | 463 | 478 |
| 464 | 479 | print '... making model' | 465 | 480 | # construct the RBM class | 466 | | - rbm = RBM_option2.new(input = x, n_visible=28*28, n_hidden=500, numpy_rng= | | 481 | + rbm = RBM_option2(input = x, n_visible=28*28, n_hidden=500, numpy_rng= | 467 | 482 | numpy.random.RandomState(234234)) | 468 | | - step = rbm.gibbs_k(10) | 469 | | - cost = rbm.cd(step = step)[0] | | 483 | + cost = rbm.cd(steps = 10 )[0] | 470 | 484 |
| 471 | 485 | print '... compiling train function' | 472 | | - train_rbm = theano.function([index], rbm.cd(step = step)[0], | 473 | | - updates = rbm.cd_updates(learning_rate, step = step), | | 486 | + train_rbm = theano.function([index], rbm.cd(steps = 10)[0], | | 487 | + updates = rbm.cd_updates(learning_rate, steps = 10), | 474 | 488 | givens = { | 475 | 489 | x: train_set_x[index*batch_size:(index+1)*batch_size], | 476 | 490 | y: train_set_y[index*batch_size:(index+1)*batch_size]} | |
|