forked from benanne/kaggle-galaxies
-
Notifications
You must be signed in to change notification settings - Fork 0
/
layers.py
1466 lines (1113 loc) · 62.3 KB
/
layers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import numpy as np
import theano.tensor as T
import theano
from theano.tensor.signal.conv import conv2d as sconv2d
from theano.tensor.signal.downsample import max_pool_2d
from theano.tensor.nnet.conv import conv2d
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
import sys
import os
import cPickle as pickle
srng = RandomStreams()
# nonlinearities
sigmoid = T.nnet.sigmoid
tanh = T.tanh
def rectify(x):
return T.maximum(x, 0.0)
def identity(x):
# To create a linear layer.
return x
def compress(x, C=10000.0):
return T.log(1 + C * x ** 2) # no binning matrix here of course
def compress_abs(x, C=10000.0):
return T.log(1 + C * abs(x))
def all_layers(layer):
"""
Recursive function to gather all layers below the given layer (including the given layer)
"""
if isinstance(layer, InputLayer) or isinstance(layer, Input2DLayer):
return [layer]
elif isinstance(layer, ConcatenateLayer):
return sum([all_layers(i) for i in layer.input_layers], [layer])
else:
return [layer] + all_layers(layer.input_layer)
def all_parameters(layer):
"""
Recursive function to gather all parameters, starting from the output layer
"""
if isinstance(layer, InputLayer) or isinstance(layer, Input2DLayer):
return []
elif isinstance(layer, ConcatenateLayer):
return sum([all_parameters(i) for i in layer.input_layers], [])
else:
return layer.params + all_parameters(layer.input_layer)
def all_bias_parameters(layer):
"""
Recursive function to gather all bias parameters, starting from the output layer
"""
if isinstance(layer, InputLayer) or isinstance(layer, Input2DLayer):
return []
elif isinstance(layer, ConcatenateLayer):
return sum([all_bias_parameters(i) for i in layer.input_layers], [])
else:
return layer.bias_params + all_bias_parameters(layer.input_layer)
def all_non_bias_parameters(layer):
return [p for p in all_parameters(layer) if p not in all_bias_parameters(layer)]
def gather_rescaling_updates(layer, c):
"""
Recursive function to gather weight rescaling updates when the constant is the same for all layers.
"""
if isinstance(layer, InputLayer) or isinstance(layer, Input2DLayer):
return []
elif isinstance(layer, ConcatenateLayer):
return sum([gather_rescaling_updates(i, c) for i in layer.input_layers], [])
else:
if hasattr(layer, 'rescaling_updates'):
updates = layer.rescaling_updates(c)
else:
updates = []
return updates + gather_rescaling_updates(layer.input_layer, c)
def get_param_values(layer):
params = all_parameters(layer)
return [p.get_value() for p in params]
def set_param_values(layer, param_values):
params = all_parameters(layer)
for p, pv in zip(params, param_values):
p.set_value(pv)
def reset_all_params(layer):
for l in all_layers(layer):
if hasattr(l, 'reset_params'):
l.reset_params()
def gen_updates_regular_momentum(loss, all_parameters, learning_rate, momentum, weight_decay):
all_grads = [theano.grad(loss, param) for param in all_parameters]
updates = []
for param_i, grad_i in zip(all_parameters, all_grads):
mparam_i = theano.shared(param_i.get_value()*0.)
v = momentum * mparam_i - weight_decay * learning_rate * param_i - learning_rate * grad_i
updates.append((mparam_i, v))
updates.append((param_i, param_i + v))
return updates
# using the alternative formulation of nesterov momentum described at https://github.com/lisa-lab/pylearn2/pull/136
# such that the gradient can be evaluated at the current parameters.
def gen_updates_nesterov_momentum(loss, all_parameters, learning_rate, momentum, weight_decay):
all_grads = [theano.grad(loss, param) for param in all_parameters]
updates = []
for param_i, grad_i in zip(all_parameters, all_grads):
mparam_i = theano.shared(param_i.get_value()*0.)
full_grad = grad_i + weight_decay * param_i
v = momentum * mparam_i - learning_rate * full_grad # new momemtum
w = param_i + momentum * v - learning_rate * full_grad # new parameter values
updates.append((mparam_i, v))
updates.append((param_i, w))
return updates
def gen_updates_nesterov_momentum_no_bias_decay(loss, all_parameters, all_bias_parameters, learning_rate, momentum, weight_decay):
"""
Nesterov momentum, but excluding the biases from the weight decay.
"""
all_grads = [theano.grad(loss, param) for param in all_parameters]
updates = []
for param_i, grad_i in zip(all_parameters, all_grads):
mparam_i = theano.shared(param_i.get_value()*0.)
if param_i in all_bias_parameters:
full_grad = grad_i
else:
full_grad = grad_i + weight_decay * param_i
v = momentum * mparam_i - learning_rate * full_grad # new momemtum
w = param_i + momentum * v - learning_rate * full_grad # new parameter values
updates.append((mparam_i, v))
updates.append((param_i, w))
return updates
gen_updates = gen_updates_nesterov_momentum
def gen_updates_sgd(loss, all_parameters, learning_rate):
all_grads = [theano.grad(loss, param) for param in all_parameters]
updates = []
for param_i, grad_i in zip(all_parameters, all_grads):
updates.append((param_i, param_i - learning_rate * grad_i))
return updates
def gen_updates_adagrad(loss, all_parameters, learning_rate=1.0, epsilon=1e-6):
"""
epsilon is not included in the typical formula,
See "Notes on AdaGrad" by Chris Dyer for more info.
"""
all_grads = [theano.grad(loss, param) for param in all_parameters]
all_accumulators = [theano.shared(param.get_value()*0.) for param in all_parameters] # initialise to zeroes with the right shape
updates = []
for param_i, grad_i, acc_i in zip(all_parameters, all_grads, all_accumulators):
acc_i_new = acc_i + grad_i**2
updates.append((acc_i, acc_i_new))
updates.append((param_i, param_i - learning_rate * grad_i / T.sqrt(acc_i_new + epsilon)))
return updates
def gen_updates_rmsprop(loss, all_parameters, learning_rate=1.0, rho=0.9, epsilon=1e-6):
"""
epsilon is not included in Hinton's video, but to prevent problems with relus repeatedly having 0 gradients, it is included here.
Watch this video for more info: http://www.youtube.com/watch?v=O3sxAc4hxZU (formula at 5:20)
also check http://climin.readthedocs.org/en/latest/rmsprop.html
"""
all_grads = [theano.grad(loss, param) for param in all_parameters]
all_accumulators = [theano.shared(param.get_value()*0.) for param in all_parameters] # initialise to zeroes with the right shape
# all_accumulators = [theano.shared(param.get_value()*1.) for param in all_parameters] # initialise with 1s to damp initial gradients
updates = []
for param_i, grad_i, acc_i in zip(all_parameters, all_grads, all_accumulators):
acc_i_new = rho * acc_i + (1 - rho) * grad_i**2
updates.append((acc_i, acc_i_new))
updates.append((param_i, param_i - learning_rate * grad_i / T.sqrt(acc_i_new + epsilon)))
return updates
def gen_updates_adadelta(loss, all_parameters, learning_rate=1.0, rho=0.95, epsilon=1e-6):
"""
in the paper, no learning rate is considered (so learning_rate=1.0). Probably best to keep it at this value.
epsilon is important for the very first update (so the numerator does not become 0).
rho = 0.95 and epsilon=1e-6 are suggested in the paper and reported to work for multiple datasets (MNIST, speech).
see "Adadelta: an adaptive learning rate method" by Matthew Zeiler for more info.
"""
all_grads = [theano.grad(loss, param) for param in all_parameters]
all_accumulators = [theano.shared(param.get_value()*0.) for param in all_parameters] # initialise to zeroes with the right shape
all_delta_accumulators = [theano.shared(param.get_value()*0.) for param in all_parameters]
# all_accumulators: accumulate gradient magnitudes
# all_delta_accumulators: accumulate update magnitudes (recursive!)
updates = []
for param_i, grad_i, acc_i, acc_delta_i in zip(all_parameters, all_grads, all_accumulators, all_delta_accumulators):
acc_i_new = rho * acc_i + (1 - rho) * grad_i**2
updates.append((acc_i, acc_i_new))
update_i = grad_i * T.sqrt(acc_delta_i + epsilon) / T.sqrt(acc_i_new + epsilon) # use the 'old' acc_delta here
updates.append((param_i, param_i - learning_rate * update_i))
acc_delta_i_new = rho * acc_delta_i + (1 - rho) * update_i**2
updates.append((acc_delta_i, acc_delta_i_new))
return updates
def shared_single(dim=2):
"""
Shortcut to create an undefined single precision Theano shared variable.
"""
shp = tuple([1] * dim)
return theano.shared(np.zeros(shp, dtype='float32'))
class InputLayer(object):
def __init__(self, mb_size, n_features, length):
self.mb_size = mb_size
self.n_features = n_features
self.length = length
self.input_var = T.tensor3('input')
def get_output_shape(self):
return (self.mb_size, self.n_features, self.length)
def output(self, *args, **kwargs):
"""
return theano variable
"""
return self.input_var
class FlatInputLayer(InputLayer):
def __init__(self, mb_size, n_features):
self.mb_size = mb_size
self.n_features = n_features
self.input_var = T.matrix('input')
def get_output_shape(self):
return (self.mb_size, self.n_features)
def output(self, *args, **kwargs):
"""
return theano variable
"""
return self.input_var
class Input2DLayer(object):
def __init__(self, mb_size, n_features, width, height):
self.mb_size = mb_size
self.n_features = n_features
self.width = width
self.height = height
self.input_var = T.tensor4('input')
def get_output_shape(self):
return (self.mb_size, self.n_features, self.width, self.height)
def output(self, *args, **kwargs):
return self.input_var
class PoolingLayer(object):
def __init__(self, input_layer, ds_factor, ignore_border=False):
self.ds_factor = ds_factor
self.input_layer = input_layer
self.ignore_border = ignore_border
self.params = []
self.bias_params = []
self.mb_size = self.input_layer.mb_size
def get_output_shape(self):
output_shape = list(self.input_layer.get_output_shape()) # convert to list because we cannot assign to a tuple element
if self.ignore_border:
output_shape[-1] = int(np.floor(float(output_shape[-1]) / self.ds_factor))
else:
output_shape[-1] = int(np.ceil(float(output_shape[-1]) / self.ds_factor))
return tuple(output_shape)
def output(self, *args, **kwargs):
input = self.input_layer.output(*args, **kwargs)
return max_pool_2d(input, (1, self.ds_factor), self.ignore_border)
class Pooling2DLayer(object):
def __init__(self, input_layer, pool_size, ignore_border=False): # pool_size is a tuple
self.pool_size = pool_size # a tuple
self.input_layer = input_layer
self.ignore_border = ignore_border
self.params = []
self.bias_params = []
self.mb_size = self.input_layer.mb_size
def get_output_shape(self):
output_shape = list(self.input_layer.get_output_shape()) # convert to list because we cannot assign to a tuple element
if self.ignore_border:
output_shape[-2] = int(np.floor(float(output_shape[-2]) / self.pool_size[0]))
output_shape[-1] = int(np.floor(float(output_shape[-1]) / self.pool_size[1]))
else:
output_shape[-2] = int(np.ceil(float(output_shape[-2]) / self.pool_size[0]))
output_shape[-1] = int(np.ceil(float(output_shape[-1]) / self.pool_size[1]))
return tuple(output_shape)
def output(self, *args, **kwargs):
input = self.input_layer.output(*args, **kwargs)
return max_pool_2d(input, self.pool_size, self.ignore_border)
class GlobalPooling2DLayer(object):
"""
Global pooling across the entire feature map, useful in NINs.
"""
def __init__(self, input_layer, pooling_function='mean'):
self.input_layer = input_layer
self.pooling_function = pooling_function
self.params = []
self.bias_params = []
self.mb_size = self.input_layer.mb_size
def get_output_shape(self):
return self.input_layer.get_output_shape()[:2] # this effectively removes the last 2 dimensions
def output(self, *args, **kwargs):
input = self.input_layer.output(*args, **kwargs)
if self.pooling_function == 'mean':
out = input.mean([2, 3])
elif self.pooling_function == 'max':
out = input.max([2, 3])
elif self.pooling_function == 'l2':
out = T.sqrt((input ** 2).mean([2, 3]))
return out
class DenseLayer(object):
def __init__(self, input_layer, n_outputs, weights_std, init_bias_value, nonlinearity=rectify, dropout=0.):
self.n_outputs = n_outputs
self.input_layer = input_layer
self.weights_std = np.float32(weights_std)
self.init_bias_value = np.float32(init_bias_value)
self.nonlinearity = nonlinearity
self.dropout = dropout
self.mb_size = self.input_layer.mb_size
input_shape = self.input_layer.get_output_shape()
self.n_inputs = int(np.prod(input_shape[1:]))
self.flatinput_shape = (self.mb_size, self.n_inputs)
self.W = shared_single(2) # theano.shared(np.random.randn(self.n_inputs, n_outputs).astype(np.float32) * weights_std)
self.b = shared_single(1) # theano.shared(np.ones(n_outputs).astype(np.float32) * self.init_bias_value)
self.params = [self.W, self.b]
self.bias_params = [self.b]
self.reset_params()
def reset_params(self):
self.W.set_value(np.random.randn(self.n_inputs, self.n_outputs).astype(np.float32) * self.weights_std)
self.b.set_value(np.ones(self.n_outputs).astype(np.float32) * self.init_bias_value)
def get_output_shape(self):
return (self.mb_size, self.n_outputs)
def output(self, input=None, dropout_active=True, *args, **kwargs): # use the 'dropout_active' keyword argument to disable it at test time. It is on by default.
if input == None:
input = self.input_layer.output(dropout_active=dropout_active, *args, **kwargs)
if len(self.input_layer.get_output_shape()) > 2:
input = input.reshape(self.flatinput_shape)
if dropout_active and (self.dropout > 0.):
retain_prob = 1 - self.dropout
input = input / retain_prob * srng.binomial(input.shape, p=retain_prob, dtype='int32').astype('float32')
# apply the input mask and rescale the input accordingly. By doing this it's no longer necessary to rescale the weights at test time.
return self.nonlinearity(T.dot(input, self.W) + self.b.dimshuffle('x', 0))
def rescaled_weights(self, c): # c is the maximal norm of the weight vector going into a single filter.
norms = T.sqrt(T.sqr(self.W).mean(0, keepdims=True))
scale_factors = T.minimum(c / norms, 1)
return self.W * scale_factors
def rescaling_updates(self, c):
return [(self.W, self.rescaled_weights(c))]
class ConvLayer(object):
def __init__(self, input_layer, n_filters, filter_length, weights_std, init_bias_value, nonlinearity=rectify, flip_conv_dims=False, dropout=0.):
self.n_filters = n_filters
self.filter_length = filter_length
self.stride = 1
self.input_layer = input_layer
self.weights_std = np.float32(weights_std)
self.init_bias_value = np.float32(init_bias_value)
self.nonlinearity = nonlinearity
self.flip_conv_dims = flip_conv_dims
self.dropout = dropout
self.mb_size = self.input_layer.mb_size
self.input_shape = self.input_layer.get_output_shape()
' MB_size, N_filters, Filter_length '
# if len(self.input_shape) == 2:
# self.filter_shape = (n_filters, 1, filter_length)
# elif len(self.input_shape) == 3:
# self.filter_shape = (n_filters, self.input_shape[1], filter_length)
# else:
# raise
self.filter_shape = (n_filters, self.input_shape[1], filter_length)
self.W = shared_single(3) # theano.shared(np.random.randn(*self.filter_shape).astype(np.float32) * self.weights_std)
self.b = shared_single(1) # theano.shared(np.ones(n_filters).astype(np.float32) * self.init_bias_value)
self.params = [self.W, self.b]
self.bias_params = [self.b]
self.reset_params()
def reset_params(self):
self.W.set_value(np.random.randn(*self.filter_shape).astype(np.float32) * self.weights_std)
self.b.set_value(np.ones(self.n_filters).astype(np.float32) * self.init_bias_value)
def get_output_shape(self):
output_length = (self.input_shape[2] - self.filter_length + self.stride) / self.stride # integer division
output_shape = (self.input_shape[0], self.n_filters, output_length)
return output_shape
def output(self, input=None, *args, **kwargs):
if input == None:
input = self.input_layer.output(*args, **kwargs)
if self.flip_conv_dims: # flip the conv dims to get a faster convolution when the filter_height is 1.
flipped_input_shape = (self.input_shape[1], self.input_shape[0], self.input_shape[2])
flipped_input = input.dimshuffle(1, 0, 2)
conved = sconv2d(flipped_input, self.W, subsample=(1, self.stride), image_shape=flipped_input_shape, filter_shape=self.filter_shape)
conved = T.addbroadcast(conved, 0) # else dimshuffle complains about dropping a non-broadcastable dimension
conved = conved.dimshuffle(2, 1, 3)
else:
conved = sconv2d(input, self.W, subsample=(1, self.stride), image_shape=self.input_shape, filter_shape=self.filter_shape)
conved = conved.dimshuffle(0, 1, 3) # gets rid of the obsolete filter height dimension
return self.nonlinearity(conved + self.b.dimshuffle('x', 0, 'x'))
# def dropoutput_train(self):
# p = self.dropout
# input = self.input_layer.dropoutput_train()
# if p > 0.:
# srng = RandomStreams()
# input = input * srng.binomial(self.input_layer.get_output_shape(), p=1 - p, dtype='int32').astype('float32')
# return self.output(input)
# def dropoutput_predict(self):
# p = self.dropout
# input = self.input_layer.dropoutput_predict()
# if p > 0.:
# input = input * (1 - p)
# return self.output(input)
class StridedConvLayer(object):
def __init__(self, input_layer, n_filters, filter_length, stride, weights_std, init_bias_value, nonlinearity=rectify, dropout=0.):
if filter_length % stride != 0:
print 'ERROR: the filter_length should be a multiple of the stride '
raise
if stride == 1:
print 'ERROR: use the normal ConvLayer instead (stride=1) '
raise
self.n_filters = n_filters
self.filter_length = filter_length
self.stride = 1
self.input_layer = input_layer
self.stride = stride
self.weights_std = np.float32(weights_std)
self.init_bias_value = np.float32(init_bias_value)
self.nonlinearity = nonlinearity
self.dropout = dropout
self.mb_size = self.input_layer.mb_size
self.input_shape = self.input_layer.get_output_shape()
' MB_size, N_filters, Filter_length '
self.filter_shape = (n_filters, self.input_shape[1], filter_length)
self.W = shared_single(3) # theano.shared(np.random.randn(*self.filter_shape).astype(np.float32) * self.weights_std)
self.b = shared_single(1) # theano.shared(np.ones(n_filters).astype(np.float32) * self.init_bias_value)
self.params = [self.W, self.b]
self.bias_params = [self.b]
self.reset_params()
def reset_params(self):
self.W.set_value(np.random.randn(*self.filter_shape).astype(np.float32) * self.weights_std)
self.b.set_value(np.ones(self.n_filters).astype(np.float32) * self.init_bias_value)
def get_output_shape(self):
output_length = (self.input_shape[2] - self.filter_length + self.stride) / self.stride # integer division
output_shape = (self.input_shape[0], self.n_filters, output_length)
return output_shape
def output(self, input=None, *args, **kwargs):
if input == None:
input = self.input_layer.output(*args, **kwargs)
input_shape = list(self.input_shape) # make a mutable copy
# if the input is not a multiple of the stride, cut off the end
if input_shape[2] % self.stride != 0:
input_shape[2] = self.stride * (input_shape[2] / self.stride)
input_truncated = input[:, :, :input_shape[2]] # integer division
else:
input_truncated = input
r_input_shape = (input_shape[0], input_shape[1], input_shape[2] / self.stride, self.stride) # (mb size, #out, length/stride, stride)
r_input = input_truncated.reshape(r_input_shape)
if self.stride == self.filter_length:
print " better use a tensordot"
# r_input = r_input.dimshuffle(0, 2, 1, 3) # (mb size, length/stride, #out, stride)
conved = T.tensordot(r_input, self.W, np.asarray([[1, 3], [1, 2]]))
conved = conved.dimshuffle(0, 2, 1)
elif self.stride == self.filter_length / 2:
print " better use two tensordots"
# define separate shapes for the even and odd parts, as they may differ depending on whether the sequence length
# is an even or an odd multiple of the stride.
length_even = input_shape[2] // self.filter_length
length_odd = (input_shape[2] - self.stride) // self.filter_length
r2_input_shape_even = (input_shape[0], input_shape[1], length_even, self.filter_length)
r2_input_shape_odd = (input_shape[0], input_shape[1], length_odd, self.filter_length)
r2_input_even = input[:, :, :length_even * self.filter_length].reshape(r2_input_shape_even)
r2_input_odd = input[:, :, self.stride:length_odd * self.filter_length + self.stride].reshape(r2_input_shape_odd)
conved_even = T.tensordot(r2_input_even, self.W, np.asarray([[1,3], [1, 2]]))
conved_odd = T.tensordot(r2_input_odd, self.W, np.asarray([[1, 3], [1, 2]]))
conved_even = conved_even.dimshuffle(0, 2, 1)
conved_odd = conved_odd.dimshuffle(0, 2, 1)
conved = T.zeros((conved_even.shape[0], conved_even.shape[1], conved_even.shape[2] + conved_odd.shape[2]))
conved = T.set_subtensor(conved[:, :, ::2], conved_even)
conved = T.set_subtensor(conved[:, :, 1::2], conved_odd)
else:
" use a convolution"
r_filter_shape = (self.filter_shape[0], self.filter_shape[1], self.filter_shape[2] / self.stride, self.stride)
r_W = self.W.reshape(r_filter_shape)
conved = conv2d(r_input, r_W, image_shape=r_input_shape, filter_shape=r_filter_shape)
conved = conved[:, :, :, 0] # get rid of the obsolete 'stride' dimension
return self.nonlinearity(conved + self.b.dimshuffle('x', 0, 'x'))
# def dropoutput_train(self):
# p = self.dropout
# input = self.input_layer.dropoutput_train()
# if p > 0.:
# srng = RandomStreams()
# input = input * srng.binomial(self.input_layer.get_output_shape(), p=1 - p, dtype='int32').astype('float32')
# return self.output(input)
# def dropoutput_predict(self):
# p = self.dropout
# input = self.input_layer.dropoutput_predict()
# if p > 0.:
# input = input * (1 - p)
# return self.output(input)
class Conv2DLayer(object):
def __init__(self, input_layer, n_filters, filter_width, filter_height, weights_std, init_bias_value, nonlinearity=rectify, dropout=0., dropout_tied=False, border_mode='valid'):
self.n_filters = n_filters
self.filter_width = filter_width
self.filter_height = filter_height
self.input_layer = input_layer
self.weights_std = np.float32(weights_std)
self.init_bias_value = np.float32(init_bias_value)
self.nonlinearity = nonlinearity
self.dropout = dropout
self.dropout_tied = dropout_tied # if this is on, the same dropout mask is applied across the entire input map
self.border_mode = border_mode
self.mb_size = self.input_layer.mb_size
self.input_shape = self.input_layer.get_output_shape()
' mb_size, n_filters, filter_width, filter_height '
self.filter_shape = (n_filters, self.input_shape[1], filter_width, filter_height)
self.W = shared_single(4) # theano.shared(np.random.randn(*self.filter_shape).astype(np.float32) * self.weights_std)
self.b = shared_single(1) # theano.shared(np.ones(n_filters).astype(np.float32) * self.init_bias_value)
self.params = [self.W, self.b]
self.bias_params = [self.b]
self.reset_params()
def reset_params(self):
self.W.set_value(np.random.randn(*self.filter_shape).astype(np.float32) * self.weights_std)
self.b.set_value(np.ones(self.n_filters).astype(np.float32) * self.init_bias_value)
def get_output_shape(self):
if self.border_mode == 'valid':
output_width = self.input_shape[2] - self.filter_width + 1
output_height = self.input_shape[3] - self.filter_height + 1
elif self.border_mode == 'full':
output_width = self.input_shape[2] + self.filter_width - 1
output_height = self.input_shape[3] + self.filter_width - 1
elif self.border_mode == 'same':
output_width = self.input_shape[2]
output_height = self.input_shape[3]
else:
raise RuntimeError("Invalid border mode: '%s'" % self.border_mode)
output_shape = (self.input_shape[0], self.n_filters, output_width, output_height)
return output_shape
def output(self, input=None, dropout_active=True, *args, **kwargs):
if input == None:
input = self.input_layer.output(dropout_active=dropout_active, *args, **kwargs)
if dropout_active and (self.dropout > 0.):
retain_prob = 1 - self.dropout
if self.dropout_tied:
# tying of the dropout masks across the entire feature maps, so broadcast across the feature maps.
mask = srng.binomial((input.shape[0], input.shape[1]), p=retain_prob, dtype='int32').astype('float32').dimshuffle(0, 1, 'x', 'x')
else:
mask = srng.binomial(input.shape, p=retain_prob, dtype='int32').astype('float32')
# apply the input mask and rescale the input accordingly. By doing this it's no longer necessary to rescale the weights at test time.
input = input / retain_prob * mask
if self.border_mode in ['valid', 'full']:
conved = conv2d(input, self.W, subsample=(1, 1), image_shape=self.input_shape, filter_shape=self.filter_shape, border_mode=self.border_mode)
elif self.border_mode == 'same':
conved = conv2d(input, self.W, subsample=(1, 1), image_shape=self.input_shape, filter_shape=self.filter_shape, border_mode='full')
shift_x = (self.filter_width - 1) // 2
shift_y = (self.filter_height - 1) // 2
conved = conved[:, :, shift_x:self.input_shape[2] + shift_x, shift_y:self.input_shape[3] + shift_y]
else:
raise RuntimeError("Invalid border mode: '%s'" % self.border_mode)
return self.nonlinearity(conved + self.b.dimshuffle('x', 0, 'x', 'x'))
def rescaled_weights(self, c): # c is the maximal norm of the weight vector going into a single filter.
weights_shape = self.W.shape
W_flat = self.W.reshape((weights_shape[0], T.prod(weights_shape[1:])))
norms = T.sqrt(T.sqr(W_flat).mean(1))
scale_factors = T.minimum(c / norms, 1)
return self.W * scale_factors.dimshuffle(0, 'x', 'x', 'x')
def rescaling_updates(self, c):
return [(self.W, self.rescaled_weights(c))]
class MaxoutLayer(object):
def __init__(self, input_layer, n_filters_per_unit, dropout=0.):
self.n_filters_per_unit = n_filters_per_unit
self.input_layer = input_layer
self.input_shape = self.input_layer.get_output_shape()
self.dropout = dropout
self.mb_size = self.input_layer.mb_size
self.params = []
self.bias_params = []
def get_output_shape(self):
return (self.input_shape[0], self.input_shape[1] / self.n_filters_per_unit, self.input_shape[2])
def output(self, input=None, dropout_active=True, *args, **kwargs):
if input == None:
input = self.input_layer.output(dropout_active=dropout_active, *args, **kwargs)
if dropout_active and (self.dropout > 0.):
retain_prob = 1 - self.dropout
input = input / retain_prob * srng.binomial(input.shape, p=retain_prob, dtype='int32').astype('float32')
# apply the input mask and rescale the input accordingly. By doing this it's no longer necessary to rescale the weights at test time.
output = input.reshape((self.input_shape[0], self.input_shape[1] / self.n_filters_per_unit, self.n_filters_per_unit, self.input_shape[2]))
output = T.max(output, 2)
return output
class NIN2DLayer(object):
def __init__(self, input_layer, n_outputs, weights_std, init_bias_value, nonlinearity=rectify, dropout=0., dropout_tied=False):
self.n_outputs = n_outputs
self.input_layer = input_layer
self.weights_std = np.float32(weights_std)
self.init_bias_value = np.float32(init_bias_value)
self.nonlinearity = nonlinearity
self.dropout = dropout
self.dropout_tied = dropout_tied # if this is on, the same dropout mask is applied to all instances of the layer across the map.
self.mb_size = self.input_layer.mb_size
self.input_shape = self.input_layer.get_output_shape()
self.n_inputs = self.input_shape[1]
self.W = shared_single(2) # theano.shared(np.random.randn(self.n_inputs, n_outputs).astype(np.float32) * weights_std)
self.b = shared_single(1) # theano.shared(np.ones(n_outputs).astype(np.float32) * self.init_bias_value)
self.params = [self.W, self.b]
self.bias_params = [self.b]
self.reset_params()
def reset_params(self):
self.W.set_value(np.random.randn(self.n_inputs, self.n_outputs).astype(np.float32) * self.weights_std)
self.b.set_value(np.ones(self.n_outputs).astype(np.float32) * self.init_bias_value)
def get_output_shape(self):
return (self.mb_size, self.n_outputs, self.input_shape[2], self.input_shape[3])
def output(self, input=None, dropout_active=True, *args, **kwargs): # use the 'dropout_active' keyword argument to disable it at test time. It is on by default.
if input == None:
input = self.input_layer.output(dropout_active=dropout_active, *args, **kwargs)
if dropout_active and (self.dropout > 0.):
retain_prob = 1 - self.dropout
if self.dropout_tied:
# tying of the dropout masks across the entire feature maps, so broadcast across the feature maps.
mask = srng.binomial((input.shape[0], input.shape[1]), p=retain_prob, dtype='int32').astype('float32').dimshuffle(0, 1, 'x', 'x')
else:
mask = srng.binomial(input.shape, p=retain_prob, dtype='int32').astype('float32')
# apply the input mask and rescale the input accordingly. By doing this it's no longer necessary to rescale the weights at test time.
input = input / retain_prob * mask
prod = T.tensordot(input, self.W, [[1], [0]]) # this has shape (batch_size, width, height, out_maps)
prod = prod.dimshuffle(0, 3, 1, 2) # move the feature maps to the 1st axis, where they were in the input
return self.nonlinearity(prod + self.b.dimshuffle('x', 0, 'x', 'x'))
class FilterPoolingLayer(object):
"""
pools filter outputs from the previous layer. If the pooling function is 'max', the result is maxout.
supported pooling function:
- 'max': maxout (max pooling)
- 'ss': sum of squares (L2 pooling)
- 'rss': root of the sum of the squares (L2 pooling)
"""
def __init__(self, input_layer, n_filters_per_unit, dropout=0., pooling_function='max'):
self.n_filters_per_unit = n_filters_per_unit
self.input_layer = input_layer
self.input_shape = self.input_layer.get_output_shape()
self.dropout = dropout
self.pooling_function = pooling_function
self.mb_size = self.input_layer.mb_size
self.params = []
self.bias_params = []
def get_output_shape(self):
return (self.input_shape[0], self.input_shape[1] / self.n_filters_per_unit, self.input_shape[2])
def output(self, input=None, dropout_active=True, *args, **kwargs):
if input == None:
input = self.input_layer.output(dropout_active=dropout_active, *args, **kwargs)
if dropout_active and (self.dropout > 0.):
retain_prob = 1 - self.dropout
input = input / retain_prob * srng.binomial(input.shape, p=retain_prob, dtype='int32').astype('float32')
# apply the input mask and rescale the input accordingly. By doing this it's no longer necessary to rescale the weights at test time.
output = input.reshape((self.input_shape[0], self.input_shape[1] / self.n_filters_per_unit, self.n_filters_per_unit, self.input_shape[2]))
if self.pooling_function == "max":
output = T.max(output, 2)
elif self.pooling_function == "ss":
output = T.mean(output**2, 2)
elif self.pooling_function == "rss":
# a stabilising constant to prevent NaN in the gradient
padding = 0.000001
output = T.sqrt(T.mean(output**2, 2) + padding)
else:
raise "Unknown pooling function: %s" % self.pooling_function
return output
class OutputLayer(object):
def __init__(self, input_layer, error_measure='mse'):
self.input_layer = input_layer
self.input_shape = self.input_layer.get_output_shape()
self.params = []
self.bias_params = []
self.error_measure = error_measure
self.mb_size = self.input_layer.mb_size
self.target_var = T.matrix() # variable for the labels
if error_measure == 'maha':
self.target_cov_var = T.tensor3()
def error(self, *args, **kwargs):
input = self.input_layer.output(*args, **kwargs)
# never actually dropout anything on the output layer, just pass it along!
if self.error_measure == 'mse':
error = T.mean((input - self.target_var) ** 2)
elif self.error_measure == 'ce': # cross entropy
error = T.mean(T.nnet.binary_crossentropy(input, self.target_var))
elif self.error_measure == 'nca':
epsilon = 1e-8
#dist_ij = - T.dot(input, input.T)
# dist_ij = input
dist_ij = T.sum((input.dimshuffle(0, 'x', 1) - input.dimshuffle('x', 0, 1)) ** 2, axis=2)
p_ij_unnormalised = T.exp(-dist_ij) + epsilon
p_ij_unnormalised = p_ij_unnormalised * (1 - T.eye(self.mb_size)) # set the diagonal to 0
p_ij = p_ij_unnormalised / T.sum(p_ij_unnormalised, axis=1)
return - T.mean(p_ij * self.target_var)
#
# p_ij = p_ij_unnormalised / T.sum(p_ij_unnormalised, axis=1)
# return np.mean(p_ij * self.target_var)
elif self.error_measure == 'maha':
# e = T.shape_padright(input - self.target_var)
# e = (input - self.target_var).dimshuffle((0, 'x', 1))
# error = T.sum(T.sum(self.target_cov_var * e, 2) ** 2) / self.mb_size
e = (input - self.target_var)
eTe = e.dimshuffle((0, 'x', 1)) * e.dimshuffle((0, 1, 'x'))
error = T.sum(self.target_cov_var * eTe) / self.mb_size
else:
1 / 0
return error
def error_rate(self, *args, **kwargs):
input = self.input_layer.output(*args, **kwargs)
error_rate = T.mean(T.neq(input > 0.5, self.target_var))
return error_rate
def predictions(self, *args, **kwargs):
return self.input_layer.output(*args, **kwargs)
class FlattenLayer(object):
def __init__(self, input_layer):
self.input_layer = input_layer
self.params = []
self.bias_params = []
self.mb_size = self.input_layer.mb_size
def get_output_shape(self):
input_shape = self.input_layer.get_output_shape()
size = int(np.prod(input_shape[1:]))
return (self.mb_size, size)
def output(self, *args, **kwargs):
input = self.input_layer.output(*args, **kwargs)
return input.reshape(self.get_output_shape())
class ConcatenateLayer(object):
def __init__(self, input_layers):
self.input_layers = input_layers
self.params = []
self.bias_params = []
self.mb_size = self.input_layers[0].mb_size
def get_output_shape(self):
sizes = [i.get_output_shape()[1] for i in self.input_layers] # this assumes the layers are already flat!
return (self.mb_size, sum(sizes))
def output(self, *args, **kwargs):
inputs = [i.output(*args, **kwargs) for i in self.input_layers]
return T.concatenate(inputs, axis=1)
class ResponseNormalisationLayer(object):
def __init__(self, input_layer, n, k, alpha, beta):
"""
n: window size
k: bias
alpha: scaling
beta: power
"""
self.input_layer = input_layer
self.params = []
self.bias_params = []
self.n = n
self.k = k
self.alpha = alpha
self.beta = beta
self.mb_size = self.input_layer.mb_size
def get_output_shape(self):
return self.input_layer.get_output_shape()
def output(self, *args, **kwargs):
"""
Code is based on https://github.com/lisa-lab/pylearn2/blob/master/pylearn2/expr/normalize.py
"""
input = self.input_layer.output(*args, **kwargs)
half = self.n // 2
sq = T.sqr(input)
b, ch, r, c = input.shape
extra_channels = T.alloc(0., b, ch + 2*half, r, c)
sq = T.set_subtensor(extra_channels[:,half:half+ch,:,:], sq)
scale = self.k
for i in xrange(self.n):
scale += self.alpha * sq[:,i:i+ch,:,:]
scale = scale ** self.beta
return input / scale
class StridedConv2DLayer(object):
def __init__(self, input_layer, n_filters, filter_width, filter_height, stride_x, stride_y, weights_std, init_bias_value, nonlinearity=rectify, dropout=0., dropout_tied=False, implementation='convolution'):
"""
implementation can be:
- convolution: use conv2d with the subsample parameter
- unstrided: use conv2d + reshaping so the result is a convolution with strides (1, 1)
- single_dot: use a large tensor product
- many_dots: use a bunch of tensor products
"""
self.n_filters = n_filters
self.filter_width = filter_width
self.filter_height = filter_height
self.stride_x = stride_x
self.stride_y = stride_y
self.input_layer = input_layer
self.weights_std = np.float32(weights_std)
self.init_bias_value = np.float32(init_bias_value)
self.nonlinearity = nonlinearity
self.dropout = dropout
self.dropout_tied = dropout_tied # if this is on, the same dropout mask is applied across the entire input map
self.implementation = implementation # this controls whether the convolution is computed using theano's op,
# as a bunch of tensor products, or a single stacked tensor product.
self.mb_size = self.input_layer.mb_size
self.input_shape = self.input_layer.get_output_shape()
' mb_size, n_filters, filter_width, filter_height '
self.filter_shape = (n_filters, self.input_shape[1], filter_width, filter_height)
if self.filter_width % self.stride_x != 0:
raise RuntimeError("Filter width is not a multiple of the stride in the X direction")
if self.filter_height % self.stride_y != 0:
raise RuntimeError("Filter height is not a multiple of the stride in the Y direction")
self.W = shared_single(4) # theano.shared(np.random.randn(*self.filter_shape).astype(np.float32) * self.weights_std)
self.b = shared_single(1) # theano.shared(np.ones(n_filters).astype(np.float32) * self.init_bias_value)
self.params = [self.W, self.b]
self.bias_params = [self.b]
self.reset_params()