Mercurial > ift6266
annotate baseline/mlp/mlp_nist.py @ 353:bc4464c0894c
Ajout d'une fonctionnalite pour pouvoir avoir un taux d'apprentissage decroissant dans le pretrain
author | SylvainPL <sylvain.pannetier.lebeuf@umontreal.ca> |
---|---|
date | Wed, 21 Apr 2010 14:51:14 -0400 |
parents | 22efb4968054 |
children | 76b7182dd32e |
rev | line source |
---|---|
110 | 1 """ |
2 This tutorial introduces the multilayer perceptron using Theano. | |
3 | |
4 A multilayer perceptron is a logistic regressor where | |
5 instead of feeding the input to the logistic regression you insert a | |
6 intermidiate layer, called the hidden layer, that has a nonlinear | |
7 activation function (usually tanh or sigmoid) . One can use many such | |
8 hidden layers making the architecture deep. The tutorial will also tackle | |
9 the problem of MNIST digit classification. | |
10 | |
11 .. math:: | |
12 | |
13 f(x) = G( b^{(2)} + W^{(2)}( s( b^{(1)} + W^{(1)} x))), | |
14 | |
15 References: | |
16 | |
17 - textbooks: "Pattern Recognition and Machine Learning" - | |
18 Christopher M. Bishop, section 5 | |
19 | |
20 TODO: recommended preprocessing, lr ranges, regularization ranges (explain | |
21 to do lr first, then add regularization) | |
22 | |
23 """ | |
24 __docformat__ = 'restructedtext en' | |
25 | |
26 import pdb | |
27 import numpy | |
28 import pylab | |
29 import theano | |
30 import theano.tensor as T | |
31 import time | |
32 import theano.tensor.nnet | |
143
f341a4efb44a
added adaptive lr, weight file save, traine error and error curves
XavierMuller
parents:
110
diff
changeset
|
33 import pylearn |
304
1e4bf5a5b46d
added type 2 adaptive learning configurable learning weight + versionning
xaviermuller
parents:
237
diff
changeset
|
34 import theano,pylearn.version,ift6266 |
110 | 35 from pylearn.io import filetensor as ft |
322 | 36 from ift6266 import datasets |
110 | 37 |
38 data_path = '/data/lisa/data/nist/by_class/' | |
39 | |
40 class MLP(object): | |
41 """Multi-Layer Perceptron Class | |
42 | |
43 A multilayer perceptron is a feedforward artificial neural network model | |
44 that has one layer or more of hidden units and nonlinear activations. | |
45 Intermidiate layers usually have as activation function thanh or the | |
46 sigmoid function while the top layer is a softamx layer. | |
47 """ | |
48 | |
49 | |
50 | |
143
f341a4efb44a
added adaptive lr, weight file save, traine error and error curves
XavierMuller
parents:
110
diff
changeset
|
51 def __init__(self, input, n_in, n_hidden, n_out,learning_rate): |
110 | 52 """Initialize the parameters for the multilayer perceptron |
53 | |
54 :param input: symbolic variable that describes the input of the | |
55 architecture (one minibatch) | |
56 | |
57 :param n_in: number of input units, the dimension of the space in | |
58 which the datapoints lie | |
59 | |
60 :param n_hidden: number of hidden units | |
61 | |
62 :param n_out: number of output units, the dimension of the space in | |
63 which the labels lie | |
64 | |
65 """ | |
66 | |
67 # initialize the parameters theta = (W1,b1,W2,b2) ; note that this | |
68 # example contains only one hidden layer, but one can have as many | |
69 # layers as he/she wishes, making the network deeper. The only | |
70 # problem making the network deep this way is during learning, | |
71 # backpropagation being unable to move the network from the starting | |
72 # point towards; this is where pre-training helps, giving a good | |
73 # starting point for backpropagation, but more about this in the | |
74 # other tutorials | |
75 | |
76 # `W1` is initialized with `W1_values` which is uniformely sampled | |
77 # from -6./sqrt(n_in+n_hidden) and 6./sqrt(n_in+n_hidden) | |
78 # the output of uniform if converted using asarray to dtype | |
79 # theano.config.floatX so that the code is runable on GPU | |
80 W1_values = numpy.asarray( numpy.random.uniform( \ | |
81 low = -numpy.sqrt(6./(n_in+n_hidden)), \ | |
82 high = numpy.sqrt(6./(n_in+n_hidden)), \ | |
83 size = (n_in, n_hidden)), dtype = theano.config.floatX) | |
84 # `W2` is initialized with `W2_values` which is uniformely sampled | |
85 # from -6./sqrt(n_hidden+n_out) and 6./sqrt(n_hidden+n_out) | |
86 # the output of uniform if converted using asarray to dtype | |
87 # theano.config.floatX so that the code is runable on GPU | |
88 W2_values = numpy.asarray( numpy.random.uniform( | |
89 low = -numpy.sqrt(6./(n_hidden+n_out)), \ | |
90 high= numpy.sqrt(6./(n_hidden+n_out)),\ | |
91 size= (n_hidden, n_out)), dtype = theano.config.floatX) | |
92 | |
93 self.W1 = theano.shared( value = W1_values ) | |
94 self.b1 = theano.shared( value = numpy.zeros((n_hidden,), | |
95 dtype= theano.config.floatX)) | |
96 self.W2 = theano.shared( value = W2_values ) | |
97 self.b2 = theano.shared( value = numpy.zeros((n_out,), | |
98 dtype= theano.config.floatX)) | |
99 | |
143
f341a4efb44a
added adaptive lr, weight file save, traine error and error curves
XavierMuller
parents:
110
diff
changeset
|
100 #include the learning rate in the classifer so |
f341a4efb44a
added adaptive lr, weight file save, traine error and error curves
XavierMuller
parents:
110
diff
changeset
|
101 #we can modify it on the fly when we want |
f341a4efb44a
added adaptive lr, weight file save, traine error and error curves
XavierMuller
parents:
110
diff
changeset
|
102 lr_value=learning_rate |
f341a4efb44a
added adaptive lr, weight file save, traine error and error curves
XavierMuller
parents:
110
diff
changeset
|
103 self.lr=theano.shared(value=lr_value) |
110 | 104 # symbolic expression computing the values of the hidden layer |
105 self.hidden = T.tanh(T.dot(input, self.W1)+ self.b1) | |
143
f341a4efb44a
added adaptive lr, weight file save, traine error and error curves
XavierMuller
parents:
110
diff
changeset
|
106 |
f341a4efb44a
added adaptive lr, weight file save, traine error and error curves
XavierMuller
parents:
110
diff
changeset
|
107 |
110 | 108 |
109 # symbolic expression computing the values of the top layer | |
110 self.p_y_given_x= T.nnet.softmax(T.dot(self.hidden, self.W2)+self.b2) | |
111 | |
112 # compute prediction as class whose probability is maximal in | |
113 # symbolic form | |
114 self.y_pred = T.argmax( self.p_y_given_x, axis =1) | |
143
f341a4efb44a
added adaptive lr, weight file save, traine error and error curves
XavierMuller
parents:
110
diff
changeset
|
115 self.y_pred_num = T.argmax( self.p_y_given_x[0:9], axis =1) |
f341a4efb44a
added adaptive lr, weight file save, traine error and error curves
XavierMuller
parents:
110
diff
changeset
|
116 |
f341a4efb44a
added adaptive lr, weight file save, traine error and error curves
XavierMuller
parents:
110
diff
changeset
|
117 |
f341a4efb44a
added adaptive lr, weight file save, traine error and error curves
XavierMuller
parents:
110
diff
changeset
|
118 |
110 | 119 |
120 # L1 norm ; one regularization option is to enforce L1 norm to | |
121 # be small | |
122 self.L1 = abs(self.W1).sum() + abs(self.W2).sum() | |
123 | |
124 # square of L2 norm ; one regularization option is to enforce | |
125 # square of L2 norm to be small | |
126 self.L2_sqr = (self.W1**2).sum() + (self.W2**2).sum() | |
127 | |
128 | |
129 | |
130 def negative_log_likelihood(self, y): | |
131 """Return the mean of the negative log-likelihood of the prediction | |
132 of this model under a given target distribution. | |
133 | |
134 .. math:: | |
135 | |
136 \frac{1}{|\mathcal{D}|}\mathcal{L} (\theta=\{W,b\}, \mathcal{D}) = | |
137 \frac{1}{|\mathcal{D}|}\sum_{i=0}^{|\mathcal{D}|} \log(P(Y=y^{(i)}|x^{(i)}, W,b)) \\ | |
138 \ell (\theta=\{W,b\}, \mathcal{D}) | |
139 | |
140 | |
141 :param y: corresponds to a vector that gives for each example the | |
142 :correct label | |
143 """ | |
144 return -T.mean(T.log(self.p_y_given_x)[T.arange(y.shape[0]),y]) | |
145 | |
146 | |
147 | |
148 | |
149 def errors(self, y): | |
150 """Return a float representing the number of errors in the minibatch | |
151 over the total number of examples of the minibatch | |
152 """ | |
153 | |
154 # check if y has same dimension of y_pred | |
155 if y.ndim != self.y_pred.ndim: | |
156 raise TypeError('y should have the same shape as self.y_pred', | |
157 ('y', target.type, 'y_pred', self.y_pred.type)) | |
158 # check if y is of the correct datatype | |
159 if y.dtype.startswith('int'): | |
160 # the T.neq operator returns a vector of 0s and 1s, where 1 | |
161 # represents a mistake in prediction | |
162 return T.mean(T.neq(self.y_pred, y)) | |
163 else: | |
164 raise NotImplementedError() | |
165 | |
338
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
166 def mlp_get_nist_error(model_name='/u/mullerx/ift6266h10_sandbox_db/xvm_final_lr1_p073/8/best_model.npy.npz', |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
167 data_set=0): |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
168 |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
169 |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
170 |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
171 # allocate symbolic variables for the data |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
172 x = T.fmatrix() # the data is presented as rasterized images |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
173 y = T.lvector() # the labels are presented as 1D vector of |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
174 # [long int] labels |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
175 |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
176 # load the data set and create an mlp based on the dimensions of the model |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
177 model=numpy.load(model_name) |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
178 W1=model['W1'] |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
179 W2=model['W2'] |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
180 b1=model['b1'] |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
181 b2=model['b2'] |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
182 nb_hidden=b1.shape[0] |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
183 input_dim=W1.shape[0] |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
184 nb_targets=b2.shape[0] |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
185 learning_rate=0.1 |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
186 |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
187 |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
188 if data_set==0: |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
189 dataset=datasets.nist_all() |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
190 elif data_set==1: |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
191 dataset=datasets.nist_P07() |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
192 |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
193 |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
194 classifier = MLP( input=x,\ |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
195 n_in=input_dim,\ |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
196 n_hidden=nb_hidden,\ |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
197 n_out=nb_targets, |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
198 learning_rate=learning_rate) |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
199 |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
200 |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
201 #overwrite weights with weigths from model |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
202 classifier.W1.value=W1 |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
203 classifier.W2.value=W2 |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
204 classifier.b1.value=b1 |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
205 classifier.b2.value=b2 |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
206 |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
207 |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
208 cost = classifier.negative_log_likelihood(y) \ |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
209 + 0.0 * classifier.L1 \ |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
210 + 0.0 * classifier.L2_sqr |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
211 |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
212 # compiling a theano function that computes the mistakes that are made by |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
213 # the model on a minibatch |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
214 test_model = theano.function([x,y], classifier.errors(y)) |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
215 |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
216 |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
217 |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
218 #get the test error |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
219 #use a batch size of 1 so we can get the sub-class error |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
220 #without messing with matrices (will be upgraded later) |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
221 test_score=0 |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
222 temp=0 |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
223 for xt,yt in dataset.test(20): |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
224 test_score += test_model(xt,yt) |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
225 temp = temp+1 |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
226 test_score /= temp |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
227 |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
228 |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
229 return test_score*100 |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
230 |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
231 |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
232 |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
233 |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
234 |
110 | 235 |
304
1e4bf5a5b46d
added type 2 adaptive learning configurable learning weight + versionning
xaviermuller
parents:
237
diff
changeset
|
236 def mlp_full_nist( verbose = 1,\ |
145
8ceaaf812891
changed adaptive lr flag from bool to int for jobman issues
XavierMuller
parents:
143
diff
changeset
|
237 adaptive_lr = 0,\ |
322 | 238 data_set=0,\ |
110 | 239 learning_rate=0.01,\ |
240 L1_reg = 0.00,\ | |
241 L2_reg = 0.0001,\ | |
242 nb_max_exemples=1000000,\ | |
243 batch_size=20,\ | |
322 | 244 nb_hidden = 30,\ |
212
e390b0454515
added classic lr time decay and py code to calculate the error based on a saved model
xaviermuller
parents:
169
diff
changeset
|
245 nb_targets = 62, |
338
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
246 tau=1e6,\ |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
247 lr_t2_factor=0.5,\ |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
248 init_model=0,\ |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
249 channel=0): |
110 | 250 |
251 | |
338
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
252 if channel!=0: |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
253 channel.save() |
143
f341a4efb44a
added adaptive lr, weight file save, traine error and error curves
XavierMuller
parents:
110
diff
changeset
|
254 configuration = [learning_rate,nb_max_exemples,nb_hidden,adaptive_lr] |
f341a4efb44a
added adaptive lr, weight file save, traine error and error curves
XavierMuller
parents:
110
diff
changeset
|
255 |
212
e390b0454515
added classic lr time decay and py code to calculate the error based on a saved model
xaviermuller
parents:
169
diff
changeset
|
256 #save initial learning rate if classical adaptive lr is used |
e390b0454515
added classic lr time decay and py code to calculate the error based on a saved model
xaviermuller
parents:
169
diff
changeset
|
257 initial_lr=learning_rate |
338
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
258 max_div_count=1000 |
323 | 259 |
212
e390b0454515
added classic lr time decay and py code to calculate the error based on a saved model
xaviermuller
parents:
169
diff
changeset
|
260 |
143
f341a4efb44a
added adaptive lr, weight file save, traine error and error curves
XavierMuller
parents:
110
diff
changeset
|
261 total_validation_error_list = [] |
f341a4efb44a
added adaptive lr, weight file save, traine error and error curves
XavierMuller
parents:
110
diff
changeset
|
262 total_train_error_list = [] |
f341a4efb44a
added adaptive lr, weight file save, traine error and error curves
XavierMuller
parents:
110
diff
changeset
|
263 learning_rate_list=[] |
f341a4efb44a
added adaptive lr, weight file save, traine error and error curves
XavierMuller
parents:
110
diff
changeset
|
264 best_training_error=float('inf'); |
323 | 265 divergence_flag_list=[] |
143
f341a4efb44a
added adaptive lr, weight file save, traine error and error curves
XavierMuller
parents:
110
diff
changeset
|
266 |
322 | 267 if data_set==0: |
268 dataset=datasets.nist_all() | |
323 | 269 elif data_set==1: |
270 dataset=datasets.nist_P07() | |
349
22efb4968054
added pnist support, will check in code for data set iterator later
xaviermuller
parents:
338
diff
changeset
|
271 elif data_set==2: |
22efb4968054
added pnist support, will check in code for data set iterator later
xaviermuller
parents:
338
diff
changeset
|
272 dataset=datasets.PNIST07() |
143
f341a4efb44a
added adaptive lr, weight file save, traine error and error curves
XavierMuller
parents:
110
diff
changeset
|
273 |
212
e390b0454515
added classic lr time decay and py code to calculate the error based on a saved model
xaviermuller
parents:
169
diff
changeset
|
274 |
110 | 275 |
276 | |
277 ishape = (32,32) # this is the size of NIST images | |
278 | |
279 # allocate symbolic variables for the data | |
280 x = T.fmatrix() # the data is presented as rasterized images | |
281 y = T.lvector() # the labels are presented as 1D vector of | |
282 # [long int] labels | |
283 | |
322 | 284 |
110 | 285 # construct the logistic regression class |
322 | 286 classifier = MLP( input=x,\ |
110 | 287 n_in=32*32,\ |
288 n_hidden=nb_hidden,\ | |
143
f341a4efb44a
added adaptive lr, weight file save, traine error and error curves
XavierMuller
parents:
110
diff
changeset
|
289 n_out=nb_targets, |
f341a4efb44a
added adaptive lr, weight file save, traine error and error curves
XavierMuller
parents:
110
diff
changeset
|
290 learning_rate=learning_rate) |
f341a4efb44a
added adaptive lr, weight file save, traine error and error curves
XavierMuller
parents:
110
diff
changeset
|
291 |
f341a4efb44a
added adaptive lr, weight file save, traine error and error curves
XavierMuller
parents:
110
diff
changeset
|
292 |
338
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
293 # check if we want to initialise the weights with a previously calculated model |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
294 # dimensions must be consistent between old model and current configuration!!!!!! (nb_hidden and nb_targets) |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
295 if init_model!=0: |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
296 old_model=numpy.load(init_model) |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
297 classifier.W1.value=old_model['W1'] |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
298 classifier.W2.value=old_model['W2'] |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
299 classifier.b1.value=old_model['b1'] |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
300 classifier.b2.value=old_model['b2'] |
143
f341a4efb44a
added adaptive lr, weight file save, traine error and error curves
XavierMuller
parents:
110
diff
changeset
|
301 |
110 | 302 |
303 # the cost we minimize during training is the negative log likelihood of | |
304 # the model plus the regularization terms (L1 and L2); cost is expressed | |
305 # here symbolically | |
306 cost = classifier.negative_log_likelihood(y) \ | |
307 + L1_reg * classifier.L1 \ | |
308 + L2_reg * classifier.L2_sqr | |
309 | |
310 # compiling a theano function that computes the mistakes that are made by | |
311 # the model on a minibatch | |
312 test_model = theano.function([x,y], classifier.errors(y)) | |
313 | |
314 # compute the gradient of cost with respect to theta = (W1, b1, W2, b2) | |
315 g_W1 = T.grad(cost, classifier.W1) | |
316 g_b1 = T.grad(cost, classifier.b1) | |
317 g_W2 = T.grad(cost, classifier.W2) | |
318 g_b2 = T.grad(cost, classifier.b2) | |
319 | |
320 # specify how to update the parameters of the model as a dictionary | |
321 updates = \ | |
143
f341a4efb44a
added adaptive lr, weight file save, traine error and error curves
XavierMuller
parents:
110
diff
changeset
|
322 { classifier.W1: classifier.W1 - classifier.lr*g_W1 \ |
f341a4efb44a
added adaptive lr, weight file save, traine error and error curves
XavierMuller
parents:
110
diff
changeset
|
323 , classifier.b1: classifier.b1 - classifier.lr*g_b1 \ |
f341a4efb44a
added adaptive lr, weight file save, traine error and error curves
XavierMuller
parents:
110
diff
changeset
|
324 , classifier.W2: classifier.W2 - classifier.lr*g_W2 \ |
f341a4efb44a
added adaptive lr, weight file save, traine error and error curves
XavierMuller
parents:
110
diff
changeset
|
325 , classifier.b2: classifier.b2 - classifier.lr*g_b2 } |
110 | 326 |
327 # compiling a theano function `train_model` that returns the cost, but in | |
328 # the same time updates the parameter of the model based on the rules | |
329 # defined in `updates` | |
330 train_model = theano.function([x, y], cost, updates = updates ) | |
322 | 331 |
332 | |
333 | |
110 | 334 |
335 | |
336 | |
143
f341a4efb44a
added adaptive lr, weight file save, traine error and error curves
XavierMuller
parents:
110
diff
changeset
|
337 |
f341a4efb44a
added adaptive lr, weight file save, traine error and error curves
XavierMuller
parents:
110
diff
changeset
|
338 |
110 | 339 |
340 #conditions for stopping the adaptation: | |
323 | 341 #1) we have reached nb_max_exemples (this is rounded up to be a multiple of the train size so we always do at least 1 epoch) |
143
f341a4efb44a
added adaptive lr, weight file save, traine error and error curves
XavierMuller
parents:
110
diff
changeset
|
342 #2) validation error is going up twice in a row(probable overfitting) |
110 | 343 |
344 # This means we no longer stop on slow convergence as low learning rates stopped | |
323 | 345 # too fast but instead we will wait for the valid error going up 3 times in a row |
346 # We save the curb of the validation error so we can always go back to check on it | |
347 # and we save the absolute best model anyway, so we might as well explore | |
348 # a bit when diverging | |
143
f341a4efb44a
added adaptive lr, weight file save, traine error and error curves
XavierMuller
parents:
110
diff
changeset
|
349 |
323 | 350 #approximate number of samples in the nist training set |
322 | 351 #this is just to have a validation frequency |
323 | 352 #roughly proportionnal to the original nist training set |
322 | 353 n_minibatches = 650000/batch_size |
354 | |
355 | |
323 | 356 patience =2*nb_max_exemples/batch_size #in units of minibatch |
110 | 357 validation_frequency = n_minibatches/4 |
358 | |
359 | |
360 | |
361 | |
322 | 362 |
110 | 363 best_validation_loss = float('inf') |
364 best_iter = 0 | |
365 test_score = 0. | |
366 start_time = time.clock() | |
212
e390b0454515
added classic lr time decay and py code to calculate the error based on a saved model
xaviermuller
parents:
169
diff
changeset
|
367 time_n=0 #in unit of exemples |
322 | 368 minibatch_index=0 |
369 epoch=0 | |
370 temp=0 | |
323 | 371 divergence_flag=0 |
322 | 372 |
212
e390b0454515
added classic lr time decay and py code to calculate the error based on a saved model
xaviermuller
parents:
169
diff
changeset
|
373 |
143
f341a4efb44a
added adaptive lr, weight file save, traine error and error curves
XavierMuller
parents:
110
diff
changeset
|
374 |
304
1e4bf5a5b46d
added type 2 adaptive learning configurable learning weight + versionning
xaviermuller
parents:
237
diff
changeset
|
375 if verbose == 1: |
323 | 376 print 'starting training' |
322 | 377 while(minibatch_index*batch_size<nb_max_exemples): |
143
f341a4efb44a
added adaptive lr, weight file save, traine error and error curves
XavierMuller
parents:
110
diff
changeset
|
378 |
322 | 379 for x, y in dataset.train(batch_size): |
110 | 380 |
323 | 381 #if we are using the classic learning rate deacay, adjust it before training of current mini-batch |
322 | 382 if adaptive_lr==2: |
383 classifier.lr.value = tau*initial_lr/(tau+time_n) | |
384 | |
385 | |
386 #train model | |
387 cost_ij = train_model(x,y) | |
388 | |
338
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
389 if (minibatch_index) % validation_frequency == 0: |
322 | 390 #save the current learning rate |
391 learning_rate_list.append(classifier.lr.value) | |
323 | 392 divergence_flag_list.append(divergence_flag) |
338
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
393 |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
394 #save temp results to check during training |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
395 numpy.savez('temp_results.npy',config=configuration,total_validation_error_list=total_validation_error_list,\ |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
396 learning_rate_list=learning_rate_list, divergence_flag_list=divergence_flag_list) |
322 | 397 |
398 # compute the validation error | |
399 this_validation_loss = 0. | |
400 temp=0 | |
401 for xv,yv in dataset.valid(1): | |
402 # sum up the errors for each minibatch | |
323 | 403 this_validation_loss += test_model(xv,yv) |
322 | 404 temp=temp+1 |
405 # get the average by dividing with the number of minibatches | |
406 this_validation_loss /= temp | |
407 #save the validation loss | |
408 total_validation_error_list.append(this_validation_loss) | |
304
1e4bf5a5b46d
added type 2 adaptive learning configurable learning weight + versionning
xaviermuller
parents:
237
diff
changeset
|
409 if verbose == 1: |
322 | 410 print(('epoch %i, minibatch %i, learning rate %f current validation error %f ') % |
411 (epoch, minibatch_index+1,classifier.lr.value, | |
412 this_validation_loss*100.)) | |
413 | |
414 # if we got the best validation score until now | |
415 if this_validation_loss < best_validation_loss: | |
416 # save best validation score and iteration number | |
417 best_validation_loss = this_validation_loss | |
418 best_iter = minibatch_index | |
323 | 419 #reset divergence flag |
420 divergence_flag=0 | |
421 | |
422 #save the best model. Overwrite the current saved best model so | |
423 #we only keep the best | |
424 numpy.savez('best_model.npy', config=configuration, W1=classifier.W1.value, W2=classifier.W2.value, b1=classifier.b1.value,\ | |
425 b2=classifier.b2.value, minibatch_index=minibatch_index) | |
426 | |
322 | 427 # test it on the test set |
428 test_score = 0. | |
429 temp =0 | |
430 for xt,yt in dataset.test(batch_size): | |
431 test_score += test_model(xt,yt) | |
432 temp = temp+1 | |
433 test_score /= temp | |
434 if verbose == 1: | |
435 print(('epoch %i, minibatch %i, test error of best ' | |
436 'model %f %%') % | |
437 (epoch, minibatch_index+1, | |
438 test_score*100.)) | |
439 | |
440 # if the validation error is going up, we are overfitting (or oscillating) | |
323 | 441 # check if we are allowed to continue and if we will adjust the learning rate |
322 | 442 elif this_validation_loss >= best_validation_loss: |
323 | 443 |
444 | |
445 # In non-classic learning rate decay, we modify the weight only when | |
446 # validation error is going up | |
447 if adaptive_lr==1: | |
448 classifier.lr.value=classifier.lr.value*lr_t2_factor | |
449 | |
450 | |
451 #cap the patience so we are allowed to diverge max_div_count times | |
452 #if we are going up max_div_count in a row, we will stop immediatelty by modifying the patience | |
453 divergence_flag = divergence_flag +1 | |
454 | |
455 | |
322 | 456 #calculate the test error at this point and exit |
457 # test it on the test set | |
458 test_score = 0. | |
459 temp=0 | |
460 for xt,yt in dataset.test(batch_size): | |
461 test_score += test_model(xt,yt) | |
462 temp=temp+1 | |
463 test_score /= temp | |
464 if verbose == 1: | |
465 print ' validation error is going up, possibly stopping soon' | |
466 print((' epoch %i, minibatch %i, test error of best ' | |
467 'model %f %%') % | |
468 (epoch, minibatch_index+1, | |
469 test_score*100.)) | |
470 | |
471 | |
472 | |
323 | 473 # check early stop condition |
474 if divergence_flag==max_div_count: | |
475 minibatch_index=nb_max_exemples | |
476 print 'we have diverged, early stopping kicks in' | |
477 break | |
478 | |
479 #check if we have seen enough exemples | |
480 #force one epoch at least | |
481 if epoch>0 and minibatch_index*batch_size>nb_max_exemples: | |
322 | 482 break |
338
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
483 |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
484 |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
485 |
322 | 486 |
487 | |
488 time_n= time_n + batch_size | |
323 | 489 minibatch_index = minibatch_index + 1 |
490 | |
491 # we have finished looping through the training set | |
322 | 492 epoch = epoch+1 |
110 | 493 end_time = time.clock() |
304
1e4bf5a5b46d
added type 2 adaptive learning configurable learning weight + versionning
xaviermuller
parents:
237
diff
changeset
|
494 if verbose == 1: |
110 | 495 print(('Optimization complete. Best validation score of %f %% ' |
496 'obtained at iteration %i, with test performance %f %%') % | |
497 (best_validation_loss * 100., best_iter, test_score*100.)) | |
498 print ('The code ran for %f minutes' % ((end_time-start_time)/60.)) | |
322 | 499 print minibatch_index |
143
f341a4efb44a
added adaptive lr, weight file save, traine error and error curves
XavierMuller
parents:
110
diff
changeset
|
500 |
f341a4efb44a
added adaptive lr, weight file save, traine error and error curves
XavierMuller
parents:
110
diff
changeset
|
501 #save the model and the weights |
f341a4efb44a
added adaptive lr, weight file save, traine error and error curves
XavierMuller
parents:
110
diff
changeset
|
502 numpy.savez('model.npy', config=configuration, W1=classifier.W1.value,W2=classifier.W2.value, b1=classifier.b1.value,b2=classifier.b2.value) |
f341a4efb44a
added adaptive lr, weight file save, traine error and error curves
XavierMuller
parents:
110
diff
changeset
|
503 numpy.savez('results.npy',config=configuration,total_train_error_list=total_train_error_list,total_validation_error_list=total_validation_error_list,\ |
323 | 504 learning_rate_list=learning_rate_list, divergence_flag_list=divergence_flag_list) |
143
f341a4efb44a
added adaptive lr, weight file save, traine error and error curves
XavierMuller
parents:
110
diff
changeset
|
505 |
f341a4efb44a
added adaptive lr, weight file save, traine error and error curves
XavierMuller
parents:
110
diff
changeset
|
506 return (best_training_error*100.0,best_validation_loss * 100.,test_score*100.,best_iter*batch_size,(end_time-start_time)/60) |
110 | 507 |
508 | |
509 if __name__ == '__main__': | |
510 mlp_full_mnist() | |
511 | |
512 def jobman_mlp_full_nist(state,channel): | |
143
f341a4efb44a
added adaptive lr, weight file save, traine error and error curves
XavierMuller
parents:
110
diff
changeset
|
513 (train_error,validation_error,test_error,nb_exemples,time)=mlp_full_nist(learning_rate=state.learning_rate,\ |
304
1e4bf5a5b46d
added type 2 adaptive learning configurable learning weight + versionning
xaviermuller
parents:
237
diff
changeset
|
514 nb_max_exemples=state.nb_max_exemples,\ |
1e4bf5a5b46d
added type 2 adaptive learning configurable learning weight + versionning
xaviermuller
parents:
237
diff
changeset
|
515 nb_hidden=state.nb_hidden,\ |
1e4bf5a5b46d
added type 2 adaptive learning configurable learning weight + versionning
xaviermuller
parents:
237
diff
changeset
|
516 adaptive_lr=state.adaptive_lr,\ |
1e4bf5a5b46d
added type 2 adaptive learning configurable learning weight + versionning
xaviermuller
parents:
237
diff
changeset
|
517 tau=state.tau,\ |
1e4bf5a5b46d
added type 2 adaptive learning configurable learning weight + versionning
xaviermuller
parents:
237
diff
changeset
|
518 verbose = state.verbose,\ |
324 | 519 lr_t2_factor=state.lr_t2_factor, |
338
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
520 data_set=state.data_set, |
fca22114bb23
added async save, restart from old model and independant error calculation based on Arnaud's iterator
xaviermuller
parents:
324
diff
changeset
|
521 channel=channel) |
143
f341a4efb44a
added adaptive lr, weight file save, traine error and error curves
XavierMuller
parents:
110
diff
changeset
|
522 state.train_error=train_error |
110 | 523 state.validation_error=validation_error |
524 state.test_error=test_error | |
525 state.nb_exemples=nb_exemples | |
526 state.time=time | |
304
1e4bf5a5b46d
added type 2 adaptive learning configurable learning weight + versionning
xaviermuller
parents:
237
diff
changeset
|
527 pylearn.version.record_versions(state,[theano,ift6266,pylearn]) |
110 | 528 return channel.COMPLETE |
529 | |
530 |