comparison deep/stacked_dae/sgd_optimization.py @ 167:1f5937e9e530

More moves - transformations into data_generation, added "deep" folder
author Dumitru Erhan <dumitru.erhan@gmail.com>
date Fri, 26 Feb 2010 14:15:38 -0500
parents scripts/stacked_dae/sgd_optimization.py@7d8366fb90bf
children b9ea8e2d071a
comparison
equal deleted inserted replaced
166:17ae5a1a4dd1 167:1f5937e9e530
1 #!/usr/bin/python
2 # coding: utf-8
3
4 # Generic SdA optimization loop, adapted from the deeplearning.net tutorial
5
6 import numpy
7 import theano
8 import time
9 import theano.tensor as T
10 import copy
11 import sys
12
13 from jobman import DD
14 import jobman, jobman.sql
15
16 from stacked_dae import SdA
17
18 def shared_dataset(data_xy):
19 data_x, data_y = data_xy
20 #shared_x = theano.shared(numpy.asarray(data_x, dtype=theano.config.floatX))
21 #shared_y = theano.shared(numpy.asarray(data_y, dtype=theano.config.floatX))
22 #shared_y = T.cast(shared_y, 'int32')
23 shared_x = theano.shared(data_x)
24 shared_y = theano.shared(data_y)
25 return shared_x, shared_y
26
27 class SdaSgdOptimizer:
28 def __init__(self, dataset, hyperparameters, n_ins, n_outs, input_divider=1.0,\
29 job_tree=False, results_db=None,\
30 experiment="",\
31 num_hidden_layers_to_try=[1,2,3], \
32 finetuning_lr_to_try=[0.1, 0.01, 0.001, 0.0001, 0.00001]):
33
34 self.dataset = dataset
35 self.hp = copy.copy(hyperparameters)
36 self.n_ins = n_ins
37 self.n_outs = n_outs
38 self.input_divider = numpy.asarray(input_divider, dtype=theano.config.floatX)
39
40 self.job_tree = job_tree
41 self.results_db = results_db
42 self.experiment = experiment
43 if self.job_tree:
44 assert(not results_db is None)
45 # these hp should not be there, so we insert default values
46 # we use 3 hidden layers as we'll iterate through 1,2,3
47 self.hp.finetuning_lr = 0.1 # dummy value, will be replaced anyway
48 cl = self.hp.corruption_levels
49 nh = self.hp.hidden_layers_sizes
50 self.hp.corruption_levels = [cl,cl,cl]
51 self.hp.hidden_layers_sizes = [nh,nh,nh]
52
53 self.num_hidden_layers_to_try = num_hidden_layers_to_try
54 self.finetuning_lr_to_try = finetuning_lr_to_try
55
56 self.printout_frequency = 1000
57
58 self.rng = numpy.random.RandomState(1234)
59
60 self.init_datasets()
61 self.init_classifier()
62
63 def init_datasets(self):
64 print "init_datasets"
65 train_set, valid_set, test_set = self.dataset
66 self.test_set_x, self.test_set_y = shared_dataset(test_set)
67 self.valid_set_x, self.valid_set_y = shared_dataset(valid_set)
68 self.train_set_x, self.train_set_y = shared_dataset(train_set)
69
70 # compute number of minibatches for training, validation and testing
71 self.n_train_batches = self.train_set_x.value.shape[0] / self.hp.minibatch_size
72 self.n_valid_batches = self.valid_set_x.value.shape[0] / self.hp.minibatch_size
73 self.n_test_batches = self.test_set_x.value.shape[0] / self.hp.minibatch_size
74
75 def init_classifier(self):
76 print "Constructing classifier"
77 # construct the stacked denoising autoencoder class
78 self.classifier = SdA( \
79 train_set_x= self.train_set_x, \
80 train_set_y = self.train_set_y,\
81 batch_size = self.hp.minibatch_size, \
82 n_ins= self.n_ins, \
83 hidden_layers_sizes = self.hp.hidden_layers_sizes, \
84 n_outs = self.n_outs, \
85 corruption_levels = self.hp.corruption_levels,\
86 rng = self.rng,\
87 pretrain_lr = self.hp.pretraining_lr, \
88 finetune_lr = self.hp.finetuning_lr,\
89 input_divider = self.input_divider )
90
91 def train(self):
92 self.pretrain()
93 if not self.job_tree:
94 # if job_tree is True, finetuning was already performed
95 self.finetune()
96
97 def pretrain(self):
98 print "STARTING PRETRAINING"
99
100 printout_acc = 0.0
101 last_error = 0.0
102
103 start_time = time.clock()
104 ## Pre-train layer-wise
105 for i in xrange(self.classifier.n_layers):
106 # go through pretraining epochs
107 for epoch in xrange(self.hp.pretraining_epochs_per_layer):
108 # go through the training set
109 for batch_index in xrange(self.n_train_batches):
110 c = self.classifier.pretrain_functions[i](batch_index)
111
112 printout_acc += c / self.printout_frequency
113 if (batch_index+1) % self.printout_frequency == 0:
114 print batch_index, "reconstruction cost avg=", printout_acc
115 last_error = printout_acc
116 printout_acc = 0.0
117
118 print 'Pre-training layer %i, epoch %d, cost '%(i,epoch),c
119
120 self.job_splitter(i+1, time.clock()-start_time, last_error)
121
122 end_time = time.clock()
123
124 print ('Pretraining took %f minutes' %((end_time-start_time)/60.))
125
126 # Save time by reusing intermediate results
127 def job_splitter(self, current_pretraining_layer, pretraining_time, last_error):
128
129 state_copy = None
130 original_classifier = None
131
132 if self.job_tree and current_pretraining_layer in self.num_hidden_layers_to_try:
133 for lr in self.finetuning_lr_to_try:
134 sys.stdout.flush()
135 sys.stderr.flush()
136
137 state_copy = copy.copy(self.hp)
138
139 self.hp.update({'num_hidden_layers':current_pretraining_layer, \
140 'finetuning_lr':lr,\
141 'pretraining_time':pretraining_time,\
142 'last_reconstruction_error':last_error})
143
144 original_classifier = self.classifier
145 print "ORIGINAL CLASSIFIER MEANS",original_classifier.get_params_means()
146 self.classifier = SdA.copy_reusing_lower_layers(original_classifier, current_pretraining_layer, new_finetuning_lr=lr)
147
148 self.finetune()
149
150 self.insert_finished_job()
151
152 print "NEW CLASSIFIER MEANS AFTERWARDS",self.classifier.get_params_means()
153 print "ORIGINAL CLASSIFIER MEANS AFTERWARDS",original_classifier.get_params_means()
154 self.classifier = original_classifier
155 self.hp = state_copy
156
157 def insert_finished_job(self):
158 job = copy.copy(self.hp)
159 job[jobman.sql.STATUS] = jobman.sql.DONE
160 job[jobman.sql.EXPERIMENT] = self.experiment
161
162 # don,t try to store arrays in db
163 job['hidden_layers_sizes'] = job.hidden_layers_sizes[0]
164 job['corruption_levels'] = job.corruption_levels[0]
165
166 print "Will insert finished job", job
167 jobman.sql.insert_dict(jobman.flatten(job), self.results_db)
168
169 def finetune(self):
170 print "STARTING FINETUNING"
171
172 index = T.lscalar() # index to a [mini]batch
173 minibatch_size = self.hp.minibatch_size
174
175 # create a function to compute the mistakes that are made by the model
176 # on the validation set, or testing set
177 test_model = theano.function([index], self.classifier.errors,
178 givens = {
179 self.classifier.x: self.test_set_x[index*minibatch_size:(index+1)*minibatch_size] / self.input_divider,
180 self.classifier.y: self.test_set_y[index*minibatch_size:(index+1)*minibatch_size]})
181
182 validate_model = theano.function([index], self.classifier.errors,
183 givens = {
184 self.classifier.x: self.valid_set_x[index*minibatch_size:(index+1)*minibatch_size] / self.input_divider,
185 self.classifier.y: self.valid_set_y[index*minibatch_size:(index+1)*minibatch_size]})
186
187
188 # early-stopping parameters
189 patience = 10000 # look as this many examples regardless
190 patience_increase = 2. # wait this much longer when a new best is
191 # found
192 improvement_threshold = 0.995 # a relative improvement of this much is
193 # considered significant
194 validation_frequency = min(self.n_train_batches, patience/2)
195 # go through this many
196 # minibatche before checking the network
197 # on the validation set; in this case we
198 # check every epoch
199
200 best_params = None
201 best_validation_loss = float('inf')
202 test_score = 0.
203 start_time = time.clock()
204
205 done_looping = False
206 epoch = 0
207
208 printout_acc = 0.0
209
210 if not self.hp.has_key('max_finetuning_epochs'):
211 self.hp.max_finetuning_epochs = 1000
212
213 while (epoch < self.hp.max_finetuning_epochs) and (not done_looping):
214 epoch = epoch + 1
215 for minibatch_index in xrange(self.n_train_batches):
216
217 cost_ij = self.classifier.finetune(minibatch_index)
218 iter = epoch * self.n_train_batches + minibatch_index
219
220 printout_acc += cost_ij / float(self.printout_frequency * minibatch_size)
221 if (iter+1) % self.printout_frequency == 0:
222 print iter, "cost avg=", printout_acc
223 printout_acc = 0.0
224
225 if (iter+1) % validation_frequency == 0:
226
227 validation_losses = [validate_model(i) for i in xrange(self.n_valid_batches)]
228 this_validation_loss = numpy.mean(validation_losses)
229 print('epoch %i, minibatch %i/%i, validation error %f %%' % \
230 (epoch, minibatch_index+1, self.n_train_batches, \
231 this_validation_loss*100.))
232
233
234 # if we got the best validation score until now
235 if this_validation_loss < best_validation_loss:
236
237 #improve patience if loss improvement is good enough
238 if this_validation_loss < best_validation_loss * \
239 improvement_threshold :
240 patience = max(patience, iter * patience_increase)
241
242 # save best validation score and iteration number
243 best_validation_loss = this_validation_loss
244 best_iter = iter
245
246 # test it on the test set
247 test_losses = [test_model(i) for i in xrange(self.n_test_batches)]
248 test_score = numpy.mean(test_losses)
249 print((' epoch %i, minibatch %i/%i, test error of best '
250 'model %f %%') %
251 (epoch, minibatch_index+1, self.n_train_batches,
252 test_score*100.))
253
254
255 if patience <= iter :
256 done_looping = True
257 break
258
259 end_time = time.clock()
260 self.hp.update({'finetuning_time':end_time-start_time,\
261 'best_validation_error':best_validation_loss,\
262 'test_score':test_score,
263 'num_finetuning_epochs':epoch})
264 print(('Optimization complete with best validation score of %f %%,'
265 'with test performance %f %%') %
266 (best_validation_loss * 100., test_score*100.))
267 print ('The finetuning ran for %f minutes' % ((end_time-start_time)/60.))
268
269
270