371
|
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 datetime
|
|
10 import theano.tensor as T
|
|
11 import sys
|
|
12 import pickle
|
|
13
|
|
14 from jobman import DD
|
|
15 import jobman, jobman.sql
|
|
16 from copy import copy
|
|
17
|
|
18 from stacked_dae import SdA
|
|
19
|
|
20 from ift6266.utils.seriestables import *
|
|
21
|
|
22 #For test purpose only
|
|
23 buffersize=1000
|
|
24
|
|
25 default_series = { \
|
|
26 'reconstruction_error' : DummySeries(),
|
|
27 'training_error' : DummySeries(),
|
|
28 'validation_error' : DummySeries(),
|
|
29 'test_error' : DummySeries(),
|
|
30 'params' : DummySeries()
|
|
31 }
|
|
32
|
|
33 def itermax(iter, max):
|
|
34 for i,it in enumerate(iter):
|
|
35 if i >= max:
|
|
36 break
|
|
37 yield it
|
|
38
|
|
39 class SdaSgdOptimizer:
|
|
40 def __init__(self, dataset, hyperparameters, n_ins, n_outs,
|
|
41 examples_per_epoch, series=default_series, max_minibatches=None):
|
|
42 self.dataset = dataset
|
|
43 self.hp = hyperparameters
|
|
44 self.n_ins = n_ins
|
|
45 self.n_outs = n_outs
|
|
46 self.parameters_pre=[]
|
|
47
|
|
48 self.max_minibatches = max_minibatches
|
|
49 print "SdaSgdOptimizer, max_minibatches =", max_minibatches
|
|
50 print "Reduce Label: ", self.hp.reduce_label
|
|
51
|
|
52 self.ex_per_epoch = examples_per_epoch
|
|
53 self.mb_per_epoch = examples_per_epoch / self.hp.minibatch_size
|
|
54
|
|
55 self.series = series
|
|
56
|
|
57 self.rng = numpy.random.RandomState(1234)
|
|
58
|
|
59 self.init_classifier()
|
|
60
|
|
61 sys.stdout.flush()
|
|
62
|
|
63 def init_classifier(self):
|
|
64 print "Constructing classifier"
|
|
65
|
|
66 # we don't want to save arrays in DD objects, so
|
|
67 # we recreate those arrays here
|
|
68 nhl = self.hp.num_hidden_layers
|
|
69 layers_sizes = [self.hp.hidden_layers_sizes] * nhl
|
|
70 corruption_levels = [self.hp.corruption_levels] * nhl
|
|
71
|
|
72 # construct the stacked denoising autoencoder class
|
|
73 self.classifier = SdA( \
|
|
74 batch_size = self.hp.minibatch_size, \
|
|
75 n_ins= self.n_ins, \
|
|
76 hidden_layers_sizes = layers_sizes, \
|
|
77 n_outs = self.n_outs, \
|
|
78 corruption_levels = corruption_levels,\
|
|
79 rng = self.rng,\
|
|
80 pretrain_lr = self.hp.pretraining_lr, \
|
|
81 finetune_lr = self.hp.finetuning_lr, \
|
|
82 detection_mode = self.hp.detection_mode, \
|
|
83 )
|
|
84
|
|
85 #theano.printing.pydotprint(self.classifier.pretrain_functions[0], "function.graph")
|
|
86
|
|
87 sys.stdout.flush()
|
|
88
|
|
89 def train(self):
|
|
90 self.pretrain(self.dataset)
|
|
91 self.finetune(self.dataset)
|
|
92
|
|
93 def pretrain(self,dataset):
|
|
94 print "STARTING PRETRAINING, time = ", datetime.datetime.now()
|
|
95 sys.stdout.flush()
|
|
96
|
|
97 un_fichier=int(819200.0/self.hp.minibatch_size) #Number of batches in a P07 file
|
|
98
|
|
99 start_time = time.clock()
|
|
100 ## Pre-train layer-wise
|
|
101 for i in xrange(self.classifier.n_layers):
|
|
102 # go through pretraining epochs
|
|
103 for epoch in xrange(self.hp.pretraining_epochs_per_layer):
|
|
104 # go through the training set
|
|
105 batch_index=0
|
|
106 count=0
|
|
107 num_files=0
|
|
108 for x,y in dataset.train(self.hp.minibatch_size):
|
|
109 c = self.classifier.pretrain_functions[i](x)
|
|
110 count +=1
|
|
111
|
|
112 self.series["reconstruction_error"].append((epoch, batch_index), c)
|
|
113 batch_index+=1
|
|
114
|
|
115 #if batch_index % 100 == 0:
|
|
116 # print "100 batches"
|
|
117
|
|
118 # useful when doing tests
|
|
119 if self.max_minibatches and batch_index >= self.max_minibatches:
|
|
120 break
|
|
121
|
|
122 #When we pass through the data only once (the case with P07)
|
|
123 #There is approximately 800*1024=819200 examples per file (1k per example and files are 800M)
|
|
124 if self.hp.pretraining_epochs_per_layer == 1 and count%un_fichier == 0:
|
|
125 print 'Pre-training layer %i, epoch %d, cost '%(i,num_files),c
|
|
126 num_files+=1
|
|
127 sys.stdout.flush()
|
|
128 self.series['params'].append((num_files,), self.classifier.all_params)
|
|
129
|
|
130 #When NIST is used
|
|
131 if self.hp.pretraining_epochs_per_layer > 1:
|
|
132 print 'Pre-training layer %i, epoch %d, cost '%(i,epoch),c
|
|
133 sys.stdout.flush()
|
|
134
|
|
135 self.series['params'].append((epoch,), self.classifier.all_params)
|
|
136
|
|
137 end_time = time.clock()
|
|
138
|
|
139 print ('Pretraining took %f minutes' %((end_time-start_time)/60.))
|
|
140 self.hp.update({'pretraining_time': end_time-start_time})
|
|
141
|
|
142 sys.stdout.flush()
|
|
143
|
|
144 #To be able to load them later for tests on finetune
|
|
145 self.parameters_pre=[copy(x.value) for x in self.classifier.params]
|
|
146 f = open('params_pretrain.txt', 'w')
|
|
147 pickle.dump(self.parameters_pre,f)
|
|
148 f.close()
|
|
149
|
|
150
|
|
151 def finetune(self,dataset,dataset_test,num_finetune,ind_test,special=0,decrease=0):
|
|
152
|
|
153 if special != 0 and special != 1:
|
|
154 sys.exit('Bad value for variable special. Must be in {0,1}')
|
|
155 print "STARTING FINETUNING, time = ", datetime.datetime.now()
|
|
156
|
|
157 minibatch_size = self.hp.minibatch_size
|
|
158 if ind_test == 0 or ind_test == 20:
|
|
159 nom_test = "NIST"
|
|
160 nom_train="P07"
|
|
161 else:
|
|
162 nom_test = "P07"
|
|
163 nom_train = "NIST"
|
|
164
|
|
165
|
|
166 # create a function to compute the mistakes that are made by the model
|
|
167 # on the validation set, or testing set
|
|
168 test_model = \
|
|
169 theano.function(
|
|
170 [self.classifier.x,self.classifier.y], self.classifier.errors)
|
|
171 # givens = {
|
|
172 # self.classifier.x: ensemble_x,
|
|
173 # self.classifier.y: ensemble_y]})
|
|
174
|
|
175 validate_model = \
|
|
176 theano.function(
|
|
177 [self.classifier.x,self.classifier.y], self.classifier.errors)
|
|
178 # givens = {
|
|
179 # self.classifier.x: ,
|
|
180 # self.classifier.y: ]})
|
|
181
|
|
182
|
|
183 # early-stopping parameters
|
|
184 patience = 10000 # look as this many examples regardless
|
|
185 patience_increase = 2. # wait this much longer when a new best is
|
|
186 # found
|
|
187 improvement_threshold = 0.995 # a relative improvement of this much is
|
|
188 # considered significant
|
|
189 validation_frequency = min(self.mb_per_epoch, patience/2)
|
|
190 # go through this many
|
|
191 # minibatche before checking the network
|
|
192 # on the validation set; in this case we
|
|
193 # check every epoch
|
|
194 if self.max_minibatches and validation_frequency > self.max_minibatches:
|
|
195 validation_frequency = self.max_minibatches / 2
|
|
196
|
|
197 best_params = None
|
|
198 best_validation_loss = float('inf')
|
|
199 test_score = 0.
|
|
200 start_time = time.clock()
|
|
201
|
|
202 done_looping = False
|
|
203 epoch = 0
|
|
204
|
|
205 total_mb_index = 0
|
|
206 minibatch_index = 0
|
|
207 parameters_finetune=[]
|
|
208
|
|
209 if ind_test == 21:
|
|
210 learning_rate = self.hp.finetuning_lr / 10.0
|
|
211 else:
|
|
212 learning_rate = self.hp.finetuning_lr #The initial finetune lr
|
|
213
|
|
214
|
|
215 while (epoch < num_finetune) and (not done_looping):
|
|
216 epoch = epoch + 1
|
|
217
|
|
218 for x,y in dataset.train(minibatch_size,bufsize=buffersize):
|
|
219 minibatch_index += 1
|
|
220
|
|
221 if self.hp.reduce_label:
|
|
222 y[y > 35] = y[y > 35]-26
|
|
223
|
|
224 if special == 0:
|
|
225 cost_ij = self.classifier.finetune(x,y,learning_rate)
|
|
226 elif special == 1:
|
|
227 cost_ij = self.classifier.finetune2(x,y)
|
|
228 total_mb_index += 1
|
|
229
|
|
230 self.series["training_error"].append((epoch, minibatch_index), cost_ij)
|
|
231
|
|
232 if (total_mb_index+1) % validation_frequency == 0:
|
|
233 #minibatch_index += 1
|
|
234 #The validation set is always NIST (we want the model to be good on NIST)
|
|
235 if ind_test == 0 | ind_test == 20:
|
|
236 iter=dataset_test.valid(minibatch_size,bufsize=buffersize)
|
|
237 else:
|
|
238 iter = dataset.valid(minibatch_size,bufsize=buffersize)
|
|
239 if self.max_minibatches:
|
|
240 iter = itermax(iter, self.max_minibatches)
|
|
241 validation_losses = [validate_model(x,y) for x,y in iter]
|
|
242 this_validation_loss = numpy.mean(validation_losses)
|
|
243
|
|
244 self.series["validation_error"].\
|
|
245 append((epoch, minibatch_index), this_validation_loss*100.)
|
|
246
|
|
247 print('epoch %i, minibatch %i, validation error on NIST : %f %%' % \
|
|
248 (epoch, minibatch_index+1, \
|
|
249 this_validation_loss*100.))
|
|
250
|
|
251
|
|
252 # if we got the best validation score until now
|
|
253 if this_validation_loss < best_validation_loss:
|
|
254
|
|
255 #improve patience if loss improvement is good enough
|
|
256 if this_validation_loss < best_validation_loss * \
|
|
257 improvement_threshold :
|
|
258 patience = max(patience, total_mb_index * patience_increase)
|
|
259
|
|
260 # save best validation score, iteration number and parameters
|
|
261 best_validation_loss = this_validation_loss
|
|
262 best_iter = total_mb_index
|
|
263 parameters_finetune=[copy(x.value) for x in self.classifier.params]
|
|
264
|
|
265 # test it on the test set
|
|
266 iter = dataset.test(minibatch_size,bufsize=buffersize)
|
|
267 if self.max_minibatches:
|
|
268 iter = itermax(iter, self.max_minibatches)
|
|
269 test_losses = [test_model(x,y) for x,y in iter]
|
|
270 test_score = numpy.mean(test_losses)
|
|
271
|
|
272 #test it on the second test set
|
|
273 iter2 = dataset_test.test(minibatch_size,bufsize=buffersize)
|
|
274 if self.max_minibatches:
|
|
275 iter2 = itermax(iter2, self.max_minibatches)
|
|
276 test_losses2 = [test_model(x,y) for x,y in iter2]
|
|
277 test_score2 = numpy.mean(test_losses2)
|
|
278
|
|
279 self.series["test_error"].\
|
|
280 append((epoch, minibatch_index), test_score*100.)
|
|
281
|
|
282 print((' epoch %i, minibatch %i, test error on dataset %s (train data) of best '
|
|
283 'model %f %%') %
|
|
284 (epoch, minibatch_index+1,nom_train,
|
|
285 test_score*100.))
|
|
286
|
|
287 print((' epoch %i, minibatch %i, test error on dataset %s of best '
|
|
288 'model %f %%') %
|
|
289 (epoch, minibatch_index+1,nom_test,
|
|
290 test_score2*100.))
|
|
291
|
|
292 if patience <= total_mb_index:
|
|
293 done_looping = True
|
|
294 break #to exit the FOR loop
|
|
295
|
|
296 sys.stdout.flush()
|
|
297
|
|
298 # useful when doing tests
|
|
299 if self.max_minibatches and minibatch_index >= self.max_minibatches:
|
|
300 break
|
|
301
|
|
302 if decrease == 1:
|
|
303 learning_rate /= 2 #divide the learning rate by 2 for each new epoch
|
|
304
|
|
305 self.series['params'].append((epoch,), self.classifier.all_params)
|
|
306
|
|
307 if done_looping == True: #To exit completly the fine-tuning
|
|
308 break #to exit the WHILE loop
|
|
309
|
|
310 end_time = time.clock()
|
|
311 self.hp.update({'finetuning_time':end_time-start_time,\
|
|
312 'best_validation_error':best_validation_loss,\
|
|
313 'test_score':test_score,
|
|
314 'num_finetuning_epochs':epoch})
|
|
315
|
|
316 print(('\nOptimization complete with best validation score of %f %%,'
|
|
317 'with test performance %f %% on dataset %s ') %
|
|
318 (best_validation_loss * 100., test_score*100.,nom_train))
|
|
319 print(('The test score on the %s dataset is %f')%(nom_test,test_score2*100.))
|
|
320
|
|
321 print ('The finetuning ran for %f minutes' % ((end_time-start_time)/60.))
|
|
322
|
|
323 sys.stdout.flush()
|
|
324
|
|
325 #Save a copy of the parameters in a file to be able to get them in the future
|
|
326
|
|
327 if special == 1: #To keep a track of the value of the parameters
|
|
328 f = open('params_finetune_stanford.txt', 'w')
|
|
329 pickle.dump(parameters_finetune,f)
|
|
330 f.close()
|
|
331
|
|
332 elif ind_test == 0 | ind_test == 20: #To keep a track of the value of the parameters
|
|
333 f = open('params_finetune_P07.txt', 'w')
|
|
334 pickle.dump(parameters_finetune,f)
|
|
335 f.close()
|
|
336
|
|
337
|
|
338 elif ind_test== 1: #For the run with 2 finetunes. It will be faster.
|
|
339 f = open('params_finetune_NIST.txt', 'w')
|
|
340 pickle.dump(parameters_finetune,f)
|
|
341 f.close()
|
|
342
|
|
343 elif ind_test== 21: #To keep a track of the value of the parameters
|
|
344 f = open('params_finetune_P07_then_NIST.txt', 'w')
|
|
345 pickle.dump(parameters_finetune,f)
|
|
346 f.close()
|
|
347
|
|
348
|
|
349 #Set parameters like they where right after pre-train or finetune
|
|
350 def reload_parameters(self,which):
|
|
351
|
|
352 #self.parameters_pre=pickle.load('params_pretrain.txt')
|
|
353 f = open(which)
|
|
354 self.parameters_pre=pickle.load(f)
|
|
355 f.close()
|
|
356 for idx,x in enumerate(self.parameters_pre):
|
|
357 if x.dtype=='float64':
|
|
358 self.classifier.params[idx].value=theano._asarray(copy(x),dtype=theano.config.floatX)
|
|
359 else:
|
|
360 self.classifier.params[idx].value=copy(x)
|
|
361
|
|
362 def training_error(self,dataset):
|
|
363 # create a function to compute the mistakes that are made by the model
|
|
364 # on the validation set, or testing set
|
|
365 test_model = \
|
|
366 theano.function(
|
|
367 [self.classifier.x,self.classifier.y], self.classifier.errors)
|
|
368
|
|
369 iter2 = dataset.train(self.hp.minibatch_size,bufsize=buffersize)
|
|
370 train_losses2 = [test_model(x,y) for x,y in iter2]
|
|
371 train_score2 = numpy.mean(train_losses2)
|
|
372 print "Training error is: " + str(train_score2)
|
|
373
|
|
374
|
|
375
|
|
376
|