comparison deep/stacked_dae/v_guillaume/stacked_dae.py @ 436:0ca069550abd

Added : single class version of SDA
author Guillaume Sicard <guitch21@gmail.com>
date Mon, 03 May 2010 06:14:05 -0400
parents
children
comparison
equal deleted inserted replaced
435:d8129a09ffb1 436:0ca069550abd
1 #!/usr/bin/python
2 # coding: utf-8
3
4 import numpy
5 import theano
6 import time
7 import theano.tensor as T
8 from theano.tensor.shared_randomstreams import RandomStreams
9 import copy
10
11 from utils import update_locals
12
13 # taken from LeDeepNet/daa.py
14 # has a special case when taking log(0) (defined =0)
15 # modified to not take the mean anymore
16 from theano.tensor.xlogx import xlogx, xlogy0
17 # it's target*log(output)
18 def binary_cross_entropy(target, output, sum_axis=1):
19 XE = xlogy0(target, output) + xlogy0((1 - target), (1 - output))
20 return -T.sum(XE, axis=sum_axis)
21
22 class LogisticRegression(object):
23 def __init__(self, input, n_in, n_out):
24 # initialize with 0 the weights W as a matrix of shape (n_in, n_out)
25 self.W = theano.shared( value=numpy.zeros((n_in,n_out),
26 dtype = theano.config.floatX) )
27 # initialize the baises b as a vector of n_out 0s
28 self.b = theano.shared( value=numpy.zeros((n_out,),
29 dtype = theano.config.floatX) )
30 # compute vector of class-membership. This is a sigmoid instead of
31 #a softmax to be able later to classify as nothing
32 self.p_y_given_x = T.nnet.softmax(T.dot(input, self.W)+self.b) #row-wise
33 ## self.p_y_given_x = T.nnet.sigmoid(T.dot(input, self.W)+self.b)
34
35 # compute prediction as class whose probability is maximal in
36 # symbolic form
37 self.y_pred=T.argmax(self.p_y_given_x, axis=1)
38
39 # list of parameters for this layer
40 self.params = [self.W, self.b]
41
42
43 def negative_log_likelihood(self, y):
44 return -T.mean(T.log(self.p_y_given_x)[T.arange(y.shape[0]),y])
45 ## return -T.mean(T.log(self.p_y_given_x)[T.arange(y.shape[0]),y]+T.sum(T.log(1-self.p_y_given_x), axis=1)-T.log(1-self.p_y_given_x)[T.arange(y.shape[0]),y])
46
47
48 ## def kullback_leibler(self,y):
49 ## return -T.mean(T.log(1/float(self.p_y_given_x))[T.arange(y.shape[0]),y])
50
51
52 def errors(self, y):
53 # check if y has same dimension of y_pred
54 if y.ndim != self.y_pred.ndim:
55 raise TypeError('y should have the same shape as self.y_pred',
56 ('y', target.type, 'y_pred', self.y_pred.type))
57
58 # check if y is of the correct datatype
59 if y.dtype.startswith('int'):
60 # the T.neq operator returns a vector of 0s and 1s, where 1
61 # represents a mistake in prediction
62 return T.mean(T.neq(self.y_pred, y))
63 else:
64 raise NotImplementedError()
65
66
67 class SigmoidalLayer(object):
68 def __init__(self, rng, input, n_in, n_out):
69 self.input = input
70
71 W_values = numpy.asarray( rng.uniform( \
72 low = -numpy.sqrt(6./(n_in+n_out)), \
73 high = numpy.sqrt(6./(n_in+n_out)), \
74 size = (n_in, n_out)), dtype = theano.config.floatX)
75 self.W = theano.shared(value = W_values)
76
77 b_values = numpy.zeros((n_out,), dtype= theano.config.floatX)
78 self.b = theano.shared(value= b_values)
79
80 self.output = T.nnet.sigmoid(T.dot(input, self.W) + self.b)
81 self.params = [self.W, self.b]
82
83
84 class TanhLayer(object):
85 def __init__(self, rng, input, n_in, n_out):
86 self.input = input
87
88 W_values = numpy.asarray( rng.uniform( \
89 low = -numpy.sqrt(6./(n_in+n_out)), \
90 high = numpy.sqrt(6./(n_in+n_out)), \
91 size = (n_in, n_out)), dtype = theano.config.floatX)
92 self.W = theano.shared(value = W_values)
93
94 b_values = numpy.zeros((n_out,), dtype= theano.config.floatX)
95 self.b = theano.shared(value= b_values)
96
97 self.output = (T.tanh(T.dot(input, self.W) + self.b) + 1.0)/2.0
98 # ( *+ 1) /2 is because tanh goes from -1 to 1 and sigmoid goes from 0 to 1
99 # I want to use tanh, but the image has to stay the same. The correction is necessary.
100 self.params = [self.W, self.b]
101
102
103 class dA(object):
104 def __init__(self, n_visible= 784, n_hidden= 500, corruption_level = 0.1,\
105 input = None, shared_W = None, shared_b = None):
106 self.n_visible = n_visible
107 self.n_hidden = n_hidden
108
109 # create a Theano random generator that gives symbolic random values
110 theano_rng = RandomStreams()
111
112 if shared_W != None and shared_b != None :
113 self.W = shared_W
114 self.b = shared_b
115 else:
116 # initial values for weights and biases
117 # note : W' was written as `W_prime` and b' as `b_prime`
118
119 # W is initialized with `initial_W` which is uniformely sampled
120 # from -6./sqrt(n_visible+n_hidden) and 6./sqrt(n_hidden+n_visible)
121 # the output of uniform if converted using asarray to dtype
122 # theano.config.floatX so that the code is runable on GPU
123 initial_W = numpy.asarray( numpy.random.uniform( \
124 low = -numpy.sqrt(6./(n_hidden+n_visible)), \
125 high = numpy.sqrt(6./(n_hidden+n_visible)), \
126 size = (n_visible, n_hidden)), dtype = theano.config.floatX)
127 initial_b = numpy.zeros(n_hidden, dtype = theano.config.floatX)
128
129
130 # theano shared variables for weights and biases
131 self.W = theano.shared(value = initial_W, name = "W")
132 self.b = theano.shared(value = initial_b, name = "b")
133
134
135 initial_b_prime= numpy.zeros(n_visible)
136 # tied weights, therefore W_prime is W transpose
137 self.W_prime = self.W.T
138 self.b_prime = theano.shared(value = initial_b_prime, name = "b'")
139
140 # if no input is given, generate a variable representing the input
141 if input == None :
142 # we use a matrix because we expect a minibatch of several examples,
143 # each example being a row
144 self.x = T.matrix(name = 'input')
145 else:
146 self.x = input
147 # Equation (1)
148 # keep 90% of the inputs the same and zero-out randomly selected subset of 10% of the inputs
149 # note : first argument of theano.rng.binomial is the shape(size) of
150 # random numbers that it should produce
151 # second argument is the number of trials
152 # third argument is the probability of success of any trial
153 #
154 # this will produce an array of 0s and 1s where 1 has a
155 # probability of 1 - ``corruption_level`` and 0 with
156 # ``corruption_level``
157 self.tilde_x = theano_rng.binomial( self.x.shape, 1, 1 - corruption_level, dtype=theano.config.floatX) * self.x
158 # Equation (2)
159 # note : y is stored as an attribute of the class so that it can be
160 # used later when stacking dAs.
161
162 ## self.y = T.nnet.sigmoid(T.dot(self.tilde_x, self.W ) + self.b)
163 ##
164 ## # Equation (3)
165 ## #self.z = T.nnet.sigmoid(T.dot(self.y, self.W_prime) + self.b_prime)
166 ## # Equation (4)
167 ## # note : we sum over the size of a datapoint; if we are using minibatches,
168 ## # L will be a vector, with one entry per example in minibatch
169 ## #self.L = - T.sum( self.x*T.log(self.z) + (1-self.x)*T.log(1-self.z), axis=1 )
170 ## #self.L = binary_cross_entropy(target=self.x, output=self.z, sum_axis=1)
171 ##
172 ## # bypassing z to avoid running to log(0)
173 ## z_a = T.dot(self.y, self.W_prime) + self.b_prime
174 ## log_sigmoid = T.log(1.) - T.log(1.+T.exp(-z_a))
175 ## # log(1-sigmoid(z_a))
176 ## log_1_sigmoid = -z_a - T.log(1.+T.exp(-z_a))
177 ## self.L = -T.sum( self.x * (log_sigmoid) \
178 ## + (1.0-self.x) * (log_1_sigmoid), axis=1 )
179
180 # I added this epsilon to avoid getting log(0) and 1/0 in grad
181 # This means conceptually that there'd be no probability of 0, but that
182 # doesn't seem to me as important (maybe I'm wrong?).
183 #eps = 0.00000001
184 #eps_1 = 1-eps
185 #self.L = - T.sum( self.x * T.log(eps + eps_1*self.z) \
186 # + (1-self.x)*T.log(eps + eps_1*(1-self.z)), axis=1 )
187 # note : L is now a vector, where each element is the cross-entropy cost
188 # of the reconstruction of the corresponding example of the
189 # minibatch. We need to compute the average of all these to get
190 # the cost of the minibatch
191
192 #Or use a Tanh everything is always between 0 and 1, the range is
193 #changed so it remain the same as when sigmoid is used
194 self.y = (T.tanh(T.dot(self.tilde_x, self.W ) + self.b)+1.0)/2.0
195
196 self.z = (T.tanh(T.dot(self.y, self.W_prime) + self.b_prime)+1.0) / 2.0
197 #To ensure to do not have a log(0) operation
198 if self.z <= 0:
199 self.z = 0.000001
200 if self.z >= 1:
201 self.z = 0.999999
202
203 self.L = - T.sum( self.x*T.log(self.z) + (1.0-self.x)*T.log(1.0-self.z), axis=1 )
204
205 self.cost = T.mean(self.L)
206
207 self.params = [ self.W, self.b, self.b_prime ]
208
209
210 class SdA(object):
211 def __init__(self, batch_size, n_ins,
212 hidden_layers_sizes, n_outs,
213 corruption_levels, rng, pretrain_lr, finetune_lr):
214 # Just to make sure those are not modified somewhere else afterwards
215 hidden_layers_sizes = copy.deepcopy(hidden_layers_sizes)
216 corruption_levels = copy.deepcopy(corruption_levels)
217
218 update_locals(self, locals())
219
220 self.layers = []
221 self.pretrain_functions = []
222 self.params = []
223 # MODIF: added this so we also get the b_primes
224 # (not used for finetuning... still using ".params")
225 self.all_params = []
226 self.n_layers = len(hidden_layers_sizes)
227 self.logistic_params = []
228
229 print "Creating SdA with params:"
230 print "batch_size", batch_size
231 print "hidden_layers_sizes", hidden_layers_sizes
232 print "corruption_levels", corruption_levels
233 print "n_ins", n_ins
234 print "n_outs", n_outs
235 print "pretrain_lr", pretrain_lr
236 print "finetune_lr", finetune_lr
237 print "----"
238
239 if len(hidden_layers_sizes) < 1 :
240 raiseException (' You must have at least one hidden layer ')
241
242
243 # allocate symbolic variables for the data
244 #index = T.lscalar() # index to a [mini]batch
245 self.x = T.matrix('x') # the data is presented as rasterized images
246 self.y = T.ivector('y') # the labels are presented as 1D vector of
247 # [int] labels
248 self.finetune_lr = T.fscalar('finetune_lr') #To get a dynamic finetune learning rate
249 self.pretrain_lr = T.fscalar('pretrain_lr') #To get a dynamic pretrain learning rate
250
251 for i in xrange( self.n_layers ):
252 # construct the sigmoidal layer
253
254 # the size of the input is either the number of hidden units of
255 # the layer below or the input size if we are on the first layer
256 if i == 0 :
257 input_size = n_ins
258 else:
259 input_size = hidden_layers_sizes[i-1]
260
261 # the input to this layer is either the activation of the hidden
262 # layer below or the input of the SdA if you are on the first
263 # layer
264 if i == 0 :
265 layer_input = self.x
266 else:
267 layer_input = self.layers[-1].output
268 #We have to choose between sigmoidal layer or tanh layer !
269
270 ## layer = SigmoidalLayer(rng, layer_input, input_size,
271 ## hidden_layers_sizes[i] )
272
273 layer = TanhLayer(rng, layer_input, input_size,
274 hidden_layers_sizes[i] )
275 # add the layer to the
276 self.layers += [layer]
277 self.params += layer.params
278
279 # Construct a denoising autoencoder that shared weights with this
280 # layer
281 dA_layer = dA(input_size, hidden_layers_sizes[i], \
282 corruption_level = corruption_levels[0],\
283 input = layer_input, \
284 shared_W = layer.W, shared_b = layer.b)
285
286 self.all_params += dA_layer.params
287
288 # Construct a function that trains this dA
289 # compute gradients of layer parameters
290 gparams = T.grad(dA_layer.cost, dA_layer.params)
291 # compute the list of updates
292 updates = {}
293 for param, gparam in zip(dA_layer.params, gparams):
294 updates[param] = param - gparam * self.pretrain_lr
295
296 # create a function that trains the dA
297 update_fn = theano.function([self.x, self.pretrain_lr], dA_layer.cost, \
298 updates = updates)#,
299 # givens = {
300 # self.x : ensemble})
301 # collect this function into a list
302 #update_fn = theano.function([index], dA_layer.cost, \
303 # updates = updates,
304 # givens = {
305 # self.x : train_set_x[index*batch_size:(index+1)*batch_size] / self.shared_divider})
306 # collect this function into a list
307 self.pretrain_functions += [update_fn]
308
309
310 # We now need to add a logistic layer on top of the SDA
311 self.logLayer = LogisticRegression(\
312 input = self.layers[-1].output,\
313 n_in = hidden_layers_sizes[-1], n_out = n_outs)
314
315 self.params += self.logLayer.params
316 self.all_params += self.logLayer.params
317 # construct a function that implements one step of finetunining
318
319 # compute the cost, defined as the negative log likelihood
320 cost = self.logLayer.negative_log_likelihood(self.y)
321 # compute the gradients with respect to the model parameters
322 gparams = T.grad(cost, self.params)
323 # compute list of updates
324 updates = {}
325 for param,gparam in zip(self.params, gparams):
326 updates[param] = param - gparam*self.finetune_lr
327
328 self.finetune = theano.function([self.x,self.y,self.finetune_lr], cost,
329 updates = updates)#,
330
331 # symbolic variable that points to the number of errors made on the
332 # minibatch given by self.x and self.y
333
334 self.errors = self.logLayer.errors(self.y)
335
336
337 #STRUCTURE FOR THE FINETUNING OF THE LOGISTIC REGRESSION ON THE TOP WITH
338 #ALL HIDDEN LAYERS AS INPUT
339
340 all_h=[]
341 for i in xrange(self.n_layers):
342 all_h.append(self.layers[i].output)
343 self.all_hidden=T.concatenate(all_h,axis=1)
344
345
346 self.logLayer2 = LogisticRegression(\
347 input = self.all_hidden,\
348 n_in = sum(hidden_layers_sizes), n_out = n_outs)
349 #n_in=hidden_layers_sizes[0],n_out=n_outs)
350
351 #self.logistic_params+= self.logLayer2.params
352 # construct a function that implements one step of finetunining
353
354 self.logistic_params+=self.logLayer2.params
355 # compute the cost, defined as the negative log likelihood
356 cost2 = self.logLayer2.negative_log_likelihood(self.y)
357 # compute the gradients with respect to the model parameters
358 gparams2 = T.grad(cost2, self.logistic_params)
359
360 # compute list of updates
361 updates2 = {}
362 for param,gparam in zip(self.logistic_params, gparams2):
363 updates2[param] = param - gparam*finetune_lr
364
365 self.finetune2 = theano.function([self.x,self.y], cost2,
366 updates = updates2)
367
368 # symbolic variable that points to the number of errors made on the
369 # minibatch given by self.x and self.y
370
371 self.errors2 = self.logLayer2.errors(self.y)
372
373
374 if __name__ == '__main__':
375 import sys
376 args = sys.argv[1:]
377