-
Notifications
You must be signed in to change notification settings - Fork 0
/
cdpcn.py
executable file
·1124 lines (915 loc) · 41.7 KB
/
cdpcn.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
__authors__ = "Eder Santana"
__copyright__ = "Copyright 2014-2015, University of Florida"
__credits__ = "Eder Santana"
__license__ = "3-clause BSD"
__maintainer__ = "Eder Santana"
import logging
logger = logging.getLogger(__name__)
from pylearn2.space import VectorSpace, Conv2DSpace
from pylearn2.models.mlp import Layer, Linear, ConvElemwise, MLP
from theano.tensor.signal.downsample import max_pool_2d as max_pool
from pylearn2.utils import sharedX
from pylearn2.utils import wraps
from pylearn2.space import Space, CompositeSpace
from pylearn2.utils import wraps
from pylearn2.linear.matrixmul import MatrixMul
from pylearn2.linear import conv2d
import functools
import theano
from theano import tensor as T
from theano.printing import Print
from theano.compat.python2x import OrderedDict
from theano.gof.op import get_debug_values
import top
import numpy as np
from pylearn2.models.mlp import IdentityConvNonlinearity, RectifierConvNonlinearity
class SparseCodingLayer(Linear):
def __init__(self, batch_size, fprop_code=True, lr=.01, n_steps=10, lbda=0, top_most=False,
nonlinearity=RectifierConvNonlinearity(),*args, **kwargs):
'''
Compiled version: the sparse code is calulated using 'top' and is not just simbolic.
Parameters for the optimization/feedforward operation:
lr : learning rate
n_steps : number of steps or uptades of the hidden code
truncate: truncate the gradient after this number (default -1 which means do not truncate)
'''
super(SparseCodingLayer, self).__init__(*args, **kwargs)
self.batch_size = batch_size
self.fprop_code = fprop_code
self.n_steps = n_steps
self.lr = lr
self.lbda = lbda
self.top_most = top_most
self.nonlin = nonlinearity
@wraps(Linear.set_input_space)
def set_input_space(self, space):
self.input_space = space
if isinstance(space, VectorSpace):
self.requires_reformat = False
self.input_dim = space.dim
else:
self.requires_reformat = True
self.input_dim = space.get_total_dimension()
self.desired_space = VectorSpace(self.input_dim)
if self.fprop_code==True:
self.output_space = VectorSpace(self.dim)
else:
self.output_space = VectorSpace(self.input_dim)
rng = self.mlp.rng
W = rng.randn(self.input_dim, self.dim)
self.W = sharedX(W.T, self.layer_name + '_W')
self.transformer = MatrixMul(self.W)
self.W, = self.transformer.get_params()
b = np.zeros((self.input_dim,))
self.b = sharedX(b, self.layer_name + '_b') # We need both to pass input_dim valid
X = .001 * rng.randn(self.batch_size, self.dim)
self.X = sharedX(X, self.layer_name + '_X')
S = rng.normal(0, .001, size=(self.batch_size, self.input_dim))
self.S = sharedX(S, self.layer_name + '_S')
self._params = [self.W, self.b]
#self.state_below = T.zeros((self.batch_size, self.input_dim))
cost = self.get_local_cost()
self.opt = top.Optimizer(self.X, cost,
method='rmsprop',
learning_rate=self.lr, momentum=.9)
self._reconstruction = theano.function([], T.dot(self.X, self.W))
def get_local_cost(self):
er = T.sqr(self.S - T.dot(self.X, self.W)).sum()
l1 = T.sqrt(T.sqr(self.X) + 1e-6).sum()
top_down = self.get_top_down_flow()
return er + .1 * l1 + top_down
def update_top_state(self, state_above=None):
if self.lbda is not 0:
assert state_above is not None
self.top_flow.set_value(state_above)
def get_nonlin_output(self):
return self.nonlin(self.X)
def get_top_down_flow(self):
if self.lbda == 0:
rval = 0.
elif self.top_flow == True:
rval = (self.lbda * (self.top_flow - self.X)**2).sum()
else:
out = self.get_nonlin_output()
rval = (self.lbda * (self.top_flow - out)**2).sum()
return rval
def _renormW(self):
A = self.W.get_value(borrow=True)
A = np.dot(A.T, np.diag(1./np.sqrt(np.sum(A**2, axis=1)))).T
self.W.set_value( A )
def get_reconstruction(self):
return self._reconstruction()
def get_sparse_code(self, state_below):
# Renorm W
self._renormW()
if hasattr(state_below, 'get_value'):
#print '!!!! state_below does have get_value'
self.S.set_value(state_below.get_value(borrow=True))
self.opt.run(self.n_steps)
if isinstance(state_below, np.ndarray):
self.S.set_value(state_below.astype('float32'))
self.opt.run(self.n_steps) #,
#np.arange(self.batch_size))
return self.X
@wraps(Layer.fprop)
def fprop(self, state_below):
self._renormW()
rval = self.get_sparse_code(state_below)
if self.fprop_code == True:
#rval = T.switch(rval > 0., rval, 0.)
rval = self.nonlin.apply(rval)
else:
# Fprops the filtered input instead
rval = T.dot(rval, self.W)
return rval
@wraps(Layer.get_params)
def get_params(self):
return self.W
@functools.wraps(Layer.get_layer_monitoring_channels)
def get_layer_monitoring_channels(self, state_below=None,
state=None, targets=None):
#sc = abs(self.Xout).sum() #Get last local_error get_local_error()
#le = self.local_reconstruction_error
W, = self.transformer.get_params()
assert W.ndim == 2
sq_W = T.sqr(W)
row_norms = T.sqrt(sq_W.sum(axis=1))
col_norms = T.sqrt(sq_W.sum(axis=0))
row_norms_min = row_norms.min()
row_norms_min.__doc__ = ("The smallest norm of any row of the "
"weight matrix W. This is a measure of the "
"least influence any visible unit has.")
'''
rval = OrderedDict([('row_norms_min', row_norms_min),
('row_norms_mean', row_norms.mean()),
('row_norms_max', row_norms.max()),
('col_norms_min', col_norms.min()),
('col_norms_mean', col_norms.mean()),
('col_norms_max', col_norms.max())])#,
#('sparse_code_l1_norm', sc.mean())])
'''
rval = OrderedDict()
if False:
#(state is not None) or (state_below is not None):
if state is None:
state = self.fprop(state_below)
P = state
#if self.pool_size == 1:
vars_and_prefixes = [(P, '')]
#else:
# vars_and_prefixes = [(P, 'p_')]
for var, prefix in vars_and_prefixes:
v_max = var.max(axis=0)
v_min = var.min(axis=0)
v_mean = var.mean(axis=0)
v_range = v_max - v_min
# max_x.mean_u is "the mean over *u*nits of the max over
# e*x*amples" The x and u are included in the name because
# otherwise its hard to remember which axis is which when
# reading the monitor I use inner.outer
# rather than outer_of_inner or
# something like that because I want mean_x.* to appear next to
# each other in the alphabetical list, as these are commonly
# plotted together
for key, val in [('max_x.max_u', v_max.max()),
('max_x.mean_u', v_max.mean()),
('max_x.min_u', v_max.min()),
('min_x.max_u', v_min.max()),
('min_x.mean_u', v_min.mean()),
('min_x.min_u', v_min.min()),
('range_x.max_u', v_range.max()),
('range_x.mean_u', v_range.mean()),
('range_x.min_u', v_range.min()),
('mean_x.max_u', v_mean.max()),
('mean_x.mean_u', v_mean.mean()),
('mean_x.min_u', v_mean.min())]:
rval[prefix+key] = val
return rval
class ConvSparseCoding(ConvElemwise):
'''
Parameters for the optimization/feedforward operation:
lr : learning rate
n_steps : number of steps or uptades of the hidden code
truncate: truncate the gradient after this number (default -1 which
means do not truncate)
'''
def __init__(self, batch_size, input_channels=1, x_axes=['b', 'c', 0, 1],
fprop_code=True, lr=.01, n_steps=10, lbda=0, top_most = False,
**kwargs):
super(ConvSparseCoding, self).__init__(**kwargs)
self.batch_size = batch_size
self.fprop_code = fprop_code
self.n_steps = n_steps
self.lr = lr
self.input_channels = input_channels
self.lbda = lbda
self.top_most = top_most
def initialize_x_space(self,rng):
"""
This function initializes the coding space and dimmensions
X is how I generally call the sparse code variables.
Thus, X_space has its dimmensions
"""
dummy_batch_size = self.mlp.batch_size
if dummy_batch_size is None:
dummy_batch_size = self.batch_size
dummy_detector =\
sharedX(self.detector_space.get_origin_batch(dummy_batch_size))
if self.pool_type is not None:
assert self.pool_type in ['max', 'mean']
if self.pool_type == 'max':
dummy_p = max_pool(dummy_detector,
self.pool_shape)
''',
pool_stride=self.pool_stride,
image_shape=self.detector_space.shape)
'''
elif self.pool_type == 'mean':
dummy_p = mean_pool(dummy_detector,
self.pool_shape)
''',
pool_stride=self.pool_stride,
image_shape=self.detector_shape.shape)
'''
dummy_p = dummy_p.eval()
self.x_space = Conv2DSpace(shape=[dummy_p.shape[2],
dummy_p.shape[3]],
num_channels=self.output_channels,
axes=('b', 'c', 0, 1))
else:
dummy_detector = dummy_detector.eval()
self.x_space = Conv2DSpace(shape=[dummy_detector.shape[2],
dummy_detector.shape[3]],
num_channels=self.output_channels,
axes=('b', 'c', 0, 1))
X = rng.normal(0, .001, size=(dummy_batch_size,
self.output_channels,
self.detector_space.shape[0],
self.detector_space.shape[1]))
self.X = sharedX(X, self.layer_name+'_X')
S = rng.normal(0, .001, size=(dummy_batch_size,
self.input_channels,
self.input_space.shape[0],
self.input_space.shape[1]))
self.S = sharedX(S, self.layer_name+'_S')
# This is the statistic that comes from the layer above
top_flow = rng.binomial(1, .1, size=(dummy_batch_size,
self.output_channels,
self.x_space.shape[0],
self.x_space.shape[0]))
self.top_flow = sharedX(top_flow, self.layer_name+'_top_flow')
logger.info('Code space: {0}'.format(self.x_space.shape))
@wraps(ConvElemwise.initialize_transformer)
def initialize_transformer(self, rng):
"""
This function initializes the transformer of the class. Re-running
this function will reset the transformer.
X is how I generally call the sparse code variables.
Thus, X_space has its dimmensions
Parameters
----------
rng : object
random number generator object.
"""
if self.irange is not None:
assert self.sparse_init is None
self.transformer = conv2d.make_random_conv2D(
irange=self.irange,
input_space=self.x_space,
output_space=self.input_space,
kernel_shape=self.kernel_shape,
subsample=self.kernel_stride,
border_mode=self.border_mode,
rng=rng)
elif self.sparse_init is not None:
self.transformer = conv2d.make_sparse_random_conv2D(
num_nonzero=self.sparse_init,
input_space=self.X_space,
output_space=self.detector_space,
kernel_shape=self.kernel_shape,
subsample=self.kernel_stride,
border_mode=self.border_mode,
rng=rng)
self._reconstruction = theano.function([], self.transformer.lmul(self.X))
@wraps(ConvElemwise.initialize_output_space)
def initialize_output_space(self):
if self.fprop_code is True:
self.output_space = self.x_space
'''
if self.pool_shape is not None:
self.output_space.shape = [self.output_space.shape[0] / self.pool_stride[0],
self.output_space.shape[1] / self.pool_stride[1]]
'''
else:
self.output_space = self.input_space
logger.info('Output space: {0}'.format(self.output_space.shape))
@wraps(Layer.set_input_space)
def set_input_space(self, space):
""" Note: this function will reset the parameters! """
self.input_space = space
if not isinstance(space, Conv2DSpace):
raise BadInputSpaceError(self.__class__.__name__ +
".set_input_space "
"expected a Conv2DSpace, got " +
str(space) + " of type " +
str(type(space)))
rng = self.mlp.rng
output_shape = [(self.input_space.shape[0] + self.kernel_shape[0])
/ self.kernel_stride[0] - 1,
(self.input_space.shape[1] + self.kernel_shape[1])
/ self.kernel_stride[1] - 1]
self.detector_space = Conv2DSpace(shape=output_shape,
num_channels=self.output_channels,
axes=('b', 'c', 0, 1))
self.initialize_x_space(rng)
self.initialize_transformer(rng)
W, = self.transformer.get_params()
W.name = self.layer_name + '_W'
if self.tied_b:
self.b = sharedX(np.zeros((self.detector_space.num_channels)) +
self.init_bias)
else:
self.b = sharedX(self.detector_space.get_origin() + self.init_bias)
self.b.name = self.layer_name + '_b'
logger.info('Input shape: {0}'.format(self.input_space.shape))
logger.info('Detector space: {0}'.format(self.detector_space.shape))
self.initialize_output_space()
cost = self.get_local_cost()
self.opt = top.Optimizer(self.X, cost, method='rmsprop',
learning_rate=self.lr, momentum=.9)
def get_reconstruction(self):
return self._reconstruction()
def get_local_cost(self):
er = T.sqr(self.S - self.transformer.lmul(self.X)).sum()
l1 = T.sqrt( T.sqr(self.X) + 1e-6).sum()
top_down = self.get_top_down_flow()
return er + .1 * l1 + top_down
def update_top_state(self, state_above=None):
if self.lbda is not 0:
assert state_above is not None
self.top_flow.set_value(state_above)
def get_nonlin_output(self):
rval = max_pool(self.X, self.pool_shape)
''',
self.pool_stride,
[self.X.shape[2], self.X.shape[3]])
'''
#rval = T.switch(rval > 0., rval, 0.)
#rval = T.maximum(rval, 0.)
rval = self.nonlin.apply(rval)
return rval
def get_top_down_flow(self):
if self.lbda == 0:
rval = 0.
elif self.top_flow == True:
rval = (self.lbda * (self.top_flow - self.X)**2).sum()
else:
out = self.get_nonlin_output()
rval = (self.lbda * (self.top_flow - out)**2).sum()
return rval
def _renormW(self):
A = self.transformer.get_params()[0].get_value(borrow=True)
Ashape = A.shape
A = A.reshape((Ashape[0]*Ashape[1],Ashape[2]*Ashape[3]))
A = np.dot(A.T, np.diag(1./np.sqrt(np.sum(A**2, axis=1)))).T
A = A.reshape(Ashape)
self.transformer.get_params()[0].set_value( A )
def get_sparse_code(self, state_below):
# Define code optimizer
# Renorm W
self._renormW()
if hasattr(state_below, 'get_value'):
#print '!!!! state_below does have get_value'
assert state_below.get_value().shape == self.S.get_value().shape
s_below = state_below.get_value(borrow=True)
s_below = s_below[:,:self.input_channels,:,:]
self.S.set_value(s_below)
self.opt.run(self.n_steps)#,
#np.arange(self.batch_size))
elif isinstance(state_below, np.ndarray):
#print '!!! state_below is np.ndarray'
s_below = state_below[:,:self.input_channels,:,:].astype('float32')
self.S.set_value(s_below)
self.opt.run(self.n_steps)#,
#np.arange(self.batch_size))
#else:
# state_below = state_below[:,0,:,:].dimshuffle(0,'x',1,2)
#self.state_below = state_below
#self.local_reconstruction_error = \
# ((state_below - T.dot(self.Xout, self.W) - 0*self.b) ** 2).sum() + \
# .1 * T.sqrt(self.Xout**2 + 1e-6).sum()
return self.X
@wraps(Layer.fprop)
def fprop(self, state_below):
self.input_space.validate(state_below)
rval = self.get_sparse_code(state_below)
if self.fprop_code == True:
'''
rval = max_pool(rval, self.pool_shape,
self.pool_stride,
self.x_space.shape)
rval = T.switch(rval > 0., rval, 0.)
'''
rval = self.get_nonlin_output()
else:
# Fprops the filtered input instead
#rval = self.transformer.lmul(rval)
rval = self.transformer.lmul(self.X)
self.output_space.validate(rval)
return rval
#@wraps(Layer.get_params)
#def get_params(self):
# return [self.transformer.get_params()[0]]
class CompositeSparseCoding(Linear):
def __init__(self, batch_size, fprop_code=True, lr=.01, n_steps=10, lbda=0, top_most=False,
nonlinearity=RectifierConvNonlinearity(),*args, **kwargs):
'''
Compiled version: the sparse code is calulated using 'top' and is not just simbolic.
Parameters for the optimization/feedforward operation:
lr : learning rate
n_steps : number of steps or uptades of the hidden code
truncate: truncate the gradient after this number (default -1 which means do not truncate)
'''
super(CompositeSparseCoding, self).__init__(*args, **kwargs)
self.batch_size = batch_size
self.fprop_code = fprop_code
self.n_steps = n_steps
self.lr = lr
self.lbda = lbda
self.top_most = top_most
self.nonlin = nonlinearity
@wraps(Linear.set_input_space)
def set_input_space(self, space):
self.input_space = space
assert isinstance(space, CompositeSpace)
self.input_dim = []
self.desired_space = []
for sp in space.components:
if isinstance(sp, VectorSpace):
self.requires_reformat = False
self.input_dim.append(sp.dim)
else:
self.requires_reformat = True
self.input_dim.append(sp.get_total_dimension())
self.desired_space.append( VectorSpace(self.input_dim[-1]) )
if self.fprop_code==True:
self.output_space = VectorSpace(self.dim)
else:
#self.output_space = VectorSpace(self.input_dim)
# TODO: return composite space
raise NotImplementedError
rng = self.mlp.rng
self.W = []
self.S = []
self.b = []
self.transformer = []
self._params = []
X = .001 * rng.randn(self.batch_size, self.dim)
self.X = sharedX(X, self.layer_name + '_X')
for c in range(len(self.input_space.components)):
W = rng.randn(self.input_dim[c], self.dim)
self.W += [ sharedX(W.T, self.layer_name + '_W' + str(c)) ]
self.transformer += [ MatrixMul(self.W[c]) ]
self.W[-1], = self.transformer[-1].get_params()
b = np.zeros((self.input_dim[c],))
self.b += [ sharedX(b, self.layer_name + '_b' + str(c)) ] # We need both to pass input_dim valid
S = rng.normal(0, .001, size=(self.batch_size, self.input_dim[c]))
self.S += [ sharedX(S, self.layer_name + '_S' + str(c)) ]
self._params += [self.W[-1], self.b[-1]]
#self.state_below = T.zeros((self.batch_size, self.input_dim))
cost = self.get_local_cost()
self.opt = top.Optimizer(self.X, cost,
method='rmsprop',
learning_rate=self.lr, momentum=.9)
def get_nonlin_ouput(self):
return self.nonlin(self.X)
def get_local_cost(self):
er = 0.
tflow = self.get_top_down_flow()
flag = 0
for s,w in zip(self.S, self.W):
if flag==0:
er += T.sqr(s - T.dot(self.X, w)).sum()
flag = 1
l1 = T.sqrt(T.sqr(self.X) + 1e-6).sum()
return er + .2 * l1 + tflow
def update_top_state(self, state_above=None):
if self.lbda is not 0:
assert state_above is not None
self.top_flow.set_value(state_above)
def get_top_down_flow(self):
if self.lbda == 0:
rval = 0.
elif self.top_flow == True:
rval = (self.lbda * (self.top_flow - self.X)**2).sum()
else:
out = self.get_nonlin_output()
rval = (self.lbda * (self.top_flow - out)**2).sum()
return rval
def _renormW(self):
for w in self.W:
A = w.get_value(borrow=True)
A = np.dot(A.T, np.diag(1./np.sqrt(np.sum(A**2, axis=1)))).T
w.set_value( A )
def get_reconstruction(self):
raise NotImplementedError
def get_sparse_code(self, state_below):
# Renorm W
flag = False
self._renormW()
for sbelow, s in zip(state_below, self.S):
if hasattr(sbelow, 'get_value'):
#print '!!!! state_below does have get_value'
s.set_value(sbelow.get_value(borrow=True))
flag = True
if isinstance(state_below, np.ndarray):
s.set_value(sbelow.astype('float32'))
flag = True
#np.arange(self.batch_size))
if flag is True:
self.opt.run(self.n_steps)
return self.X
@wraps(Layer.fprop)
def fprop(self, state_below):
self._renormW()
rval = self.get_sparse_code(state_below)
if self.fprop_code == True:
#rval = T.switch(rval > 0., rval, 0.)
rval = self.nonlin.apply(rval)
else:
# Fprops the filtered input instead
rval = T.dot(rval, self.W)
return rval
@wraps(Layer.get_params)
def get_params(self):
return self.W
@functools.wraps(Layer.get_layer_monitoring_channels)
def get_layer_monitoring_channels(self, state_below=None,
state=None, targets=None):
rval = OrderedDict()
return rval
class CompositeConvLin(ConvElemwise):
'''
Parameters for the optimization/feedforward operation:
lr : learning rate
n_steps : number of steps or uptades of the hidden code
truncate: truncate the gradient after this number (default -1 which
means do not truncate)
'''
def __init__(self, batch_size, dim, input_channels=1, x_axes=['b', 'c', 0, 1],
fprop_code=True, lr=.01, n_steps=10, lbda=0, top_most = False,
**kwargs):
super(CompositeConvLin, self).__init__(**kwargs)
self.batch_size = batch_size
self.fprop_code = fprop_code
self.n_steps = n_steps
self.lr = lr
self.input_channels = input_channels
self.lbda = lbda
self.top_most = top_most
self.dim = dim
def initialize_x_space(self,rng):
"""
This function initializes the coding space and dimmensions
X is how I generally call the sparse code variables.
Thus, X_space has its dimmensions
"""
dummy_batch_size = self.mlp.batch_size
if dummy_batch_size is None:
dummy_batch_size = self.batch_size
dummy_detector =\
sharedX(self.detector_space.get_origin_batch(dummy_batch_size))
if self.pool_type is not None:
assert self.pool_type in ['max', 'mean']
if self.pool_type == 'max':
dummy_p = max_pool(dummy_detector,
self.pool_shape)
''',
pool_stride=self.pool_stride,
image_shape=self.detector_space.shape)
'''
elif self.pool_type == 'mean':
dummy_p = mean_pool(dummy_detector,
self.pool_shape)
''',
pool_stride=self.pool_stride,
image_shape=self.detector_shape.shape)
'''
dummy_p = dummy_p.eval()
self.x_space = Conv2DSpace(shape=[dummy_p.shape[2],
dummy_p.shape[3]],
num_channels=self.output_channels,
axes=('b', 'c', 0, 1))
else:
dummy_detector = dummy_detector.eval()
self.x_space = Conv2DSpace(shape=[dummy_detector.shape[2],
dummy_detector.shape[3]],
num_channels=self.output_channels,
axes=('b', 'c', 0, 1))
X = rng.normal(0, .001, size=(dummy_batch_size,
self.output_channels,
self.detector_space.shape[0],
self.detector_space.shape[1]))
self.dim_x = self.output_channels * self.detector_space.shape[0] \
* self.detector_space.shape[1]
self.X = sharedX(X, self.layer_name+'_X')
S0 = rng.normal(0, .001, size=(dummy_batch_size,
self.input_channels,
self.input_space.components[0].shape[0],
self.input_space.components[0].shape[1]))
self.S0 = sharedX(S0, self.layer_name+'_S0')
S1 = rng.normal(0, .001,
size=(dummy_batch_size, self.dim))
self.S1 = sharedX(S1, self.layer_name+'_S1')
# This is the statistic that comes from the layer above
top_flow = rng.binomial(1, .1, size=(dummy_batch_size,
self.output_channels,
self.x_space.shape[0],
self.x_space.shape[0]))
self.top_flow = sharedX(top_flow, self.layer_name+'_top_flow')
logger.info('Code space: {0}'.format(self.x_space.shape))
@wraps(ConvElemwise.initialize_transformer)
def initialize_transformer(self, rng):
"""
This function initializes the transformer of the class. Re-running
this function will reset the transformer.
X is how I generally call the sparse code variables.
Thus, X_space has its dimmensions
Parameters
----------
rng : object
random number generator object.
"""
if self.irange is not None:
assert self.sparse_init is None
self.transformer = conv2d.make_random_conv2D(
irange=self.irange,
input_space=self.x_space,
output_space=self.input_space.components[0],
kernel_shape=self.kernel_shape,
subsample=self.kernel_stride,
border_mode=self.border_mode,
rng=rng)
elif self.sparse_init is not None:
self.transformer = conv2d.make_sparse_random_conv2D(
num_nonzero=self.sparse_init,
input_space=self.X_space,
output_space=self.detector_space,
kernel_shape=self.kernel_shape,
subsample=self.kernel_stride,
border_mode=self.border_mode,
rng=rng)
@wraps(ConvElemwise.initialize_output_space)
def initialize_output_space(self):
if self.fprop_code is True:
self.output_space = self.x_space
'''
if self.pool_shape is not None:
self.output_space.shape = [self.output_space.shape[0] / self.pool_stride[0],
self.output_space.shape[1] / self.pool_stride[1]]
'''
else:
#self.output_space = self.input_space
raise NotImplementedError
logger.info('Output space: {0}'.format(self.output_space.shape))
@wraps(Layer.set_input_space)
def set_input_space(self, space):
""" Note: this function will reset the parameters! """
self.input_space = space
if not isinstance(space, CompositeSpace):
raise BadInputSpaceError(self.__class__.__name__ +
".set_input_space "
"expected a CompositeSpace, got " +
str(space) + " of type " +
str(type(space)))
rng = self.mlp.rng
output_shape = [(self.input_space.components[0].shape[0] + self.kernel_shape[0])
/ self.kernel_stride[0] - 1,
(self.input_space.components[0].shape[1] + self.kernel_shape[1])
/ self.kernel_stride[1] - 1]
self.detector_space = Conv2DSpace(shape=output_shape,
num_channels=self.output_channels,
axes=('b', 'c', 0, 1))
self.initialize_x_space(rng)
self.initialize_transformer(rng)
W, = self.transformer.get_params()
W.name = self.layer_name + '_W'
W1 = rng.normal(0, .001, size=(self.dim_x, self.dim))
self.W1 = sharedX(W1, name=self.layer_name + '_W1')
if self.tied_b:
self.b = sharedX(np.zeros((self.detector_space.num_channels)) +
self.init_bias)
else:
self.b = sharedX(self.detector_space.get_origin() + self.init_bias)
self.b.name = self.layer_name + '_b'
logger.info('Input 0 shape: {0}'.format(self.input_space.components[0].shape))
logger.info('Input 1 shape: {0}'.format(self.input_space.components[1].shape))
logger.info('Detector space: {0}'.format(self.detector_space.shape))
self.initialize_output_space()
cost = self.get_local_cost()
self.opt = top.Optimizer(self.X, cost, method='rmsprop',
learning_rate=self.lr, momentum=.9)
def get_reconstruction(self):
raise NotImplementedError
def get_local_cost(self):
er = T.sqr(self.S0 - self.transformer.lmul(self.X)).sum()
flatX = self.X.reshape((self.mlp.batch_size, self.dim_x))
er1 = T.sqr(self.S1 - T.dot(flatX, self.W1)).sum()
l1 = T.sqrt( T.sqr(self.X) + 1e-6).sum()
top_down = self.get_top_down_flow()
return er + er1 + .1 * l1 + top_down
def update_top_state(self, state_above=None):
if self.lbda is not 0:
assert state_above is not None
self.top_flow.set_value(state_above)
def get_nonlin_output(self):
rval = max_pool(self.X, self.pool_shape)
''',
self.pool_stride,
[self.X.shape[2], self.X.shape[3]])
'''
#rval = T.switch(rval > 0., rval, 0.)
#rval = T.maximum(rval, 0.)
rval = self.nonlin.apply(rval)
return rval
def get_top_down_flow(self):
if self.lbda == 0:
rval = 0.
elif self.top_flow == True:
rval = (self.lbda * (self.top_flow - self.X)**2).sum()
else:
out = self.get_nonlin_output()
rval = (self.lbda * (self.top_flow - out)**2).sum()
return rval
def get_params(self):
params = []
params += self.transformer.get_params()
params += [self.W1]
return params
def _renormW(self):
A = self.transformer.get_params()[0].get_value(borrow=True)
Ashape = A.shape
A = A.reshape((Ashape[0]*Ashape[1],Ashape[2]*Ashape[3]))
A = np.dot(A.T, np.diag(1./np.sqrt(np.sum(A**2, axis=1)))).T
A = A.reshape(Ashape)
self.transformer.get_params()[0].set_value( A )
def get_sparse_code(self, state_below):
# Define code optimizer
# Renorm W
self._renormW()
if isinstance(state_below, tuple):
#print state_below[0].dtype
if hasattr(state_below[0], 'get_value'):
#print '!!!! state_below does have get_value'
assert state_below[0].get_value().shape == self.S0.get_value().shape
s_below0 = state_below[0].get_value(borrow=True)
#s_below0 = s_below[:,:self.input_channels,:,:]
self.S0.set_value(s_below0)
s_below1 = state_below[1].get_value(borrow=True).reshape((self.mlp.batch_size,self.dim))
self.S1.set_value(s_below1)
self.opt.run(self.n_steps)#,
#np.arange(self.batch_size))
elif isinstance(state_below[0], np.ndarray):
#print '!!! state_below is np.ndarray'
#s_below = state_below[:,:self.input_channels,:,:].astype('float32')
self.S0.set_value(state_below[0])
self.S1.set_value(state_below[1].reshape((self.mlp.batch_size,self.dim)))
self.opt.run(self.n_steps)#,
return self.X
@wraps(Layer.fprop)
def fprop(self, state_below):
self.input_space.validate(state_below)
rval = self.get_sparse_code(state_below)
if self.fprop_code == True:
'''
rval = max_pool(rval, self.pool_shape,
self.pool_stride,
self.x_space.shape)
rval = T.switch(rval > 0., rval, 0.)
'''
rval = self.get_nonlin_output()
else:
# Fprops the filtered input instead
#rval = self.transformer.lmul(rval)
raise NotImplementedError
self.output_space.validate(rval)
return rval
#@wraps(Layer.get_params)
#def get_params(self):
# return [self.transformer.get_params()[0]]
class DPCN(MLP):
'''
A Deep Predictive Coding Network
Since pylearn2 MLPs can be considered a single layer,
we do so for DPCNs.
DPCN has a characteristic top-down flow despite of the regular
botton-up that is common to all Neural Networks.
Here, we make the top-down flow to be help by the DPCN class
instead of handling it to the trainer algorithm.