/
s3c.py
2431 lines (1803 loc) · 78.2 KB
/
s3c.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
"""
Spike-and-slab sparse coding (S3C)
"""
__authors__ = "Ian Goodfellow"
__copyright__ = "Copyright 2011, Universite de Montreal"
__credits__ = ["Ian Goodfellow"]
__license__ = "3-clause BSD"
__maintainer__ = "LISA Lab"
import logging
import time
import warnings
import numpy as np
from theano.compat.six.moves import input, xrange
from theano import config, function
from theano import scan
from theano.gof.op import get_debug_values, debug_error_message, debug_assert
import theano.tensor as T
from pylearn2.compat import OrderedDict
from pylearn2.utils import make_name, sharedX, as_floatX
from pylearn2.blocks import Block
from pylearn2.expr.information_theory import entropy_binary_vector
from pylearn2.models import Model
from pylearn2.space import VectorSpace
from pylearn2.utils.rng import make_np_rng
from pylearn2.utils import contains_nan
from pylearn2.utils import isfinite
from pylearn2.expr.basic import (full_min,
full_max, numpy_norms, theano_norms)
logger = logging.getLogger(__name__)
logger.debug('s3c changing the recursion limit')
import sys
sys.setrecursionlimit(50000)
def rotate_towards(old_W, new_W, new_coeff):
"""
.. todo::
WRITEME properly
For each column, rotates old_w toward new_w by new_coeff * theta,
where theta is the angle between them
Parameters
----------
old_W : WRITEME
every column is a unit vector
new_W : WRITEME
new_coeff : WRITEME
"""
norms = theano_norms(new_W)
# update, scaled back onto unit sphere
scal_points = new_W / norms.dimshuffle('x',0)
# dot product between scaled update and current W
dot_update = (old_W * scal_points).sum(axis=0)
theta = T.arccos(dot_update)
rot_amt = new_coeff * theta
new_basis_dir = scal_points - dot_update * old_W
new_basis_norms = theano_norms(new_basis_dir)
new_basis = new_basis_dir / new_basis_norms
rval = T.cos(rot_amt) * old_W + T.sin(rot_amt) * new_basis
return rval
class SufficientStatistics:
"""
The SufficientStatistics class computes several sufficient
statistics of a minibatch of examples / variational parameters.
This is mostly for convenience since several expressions are easy
to express in terms of these same sufficient statistics. Also,
re-using the same expression for the sufficient statistics in
multiple code locations can reduce theano compilation time. The
current version of the S3C code no longer supports features like
decaying sufficient statistics since these were not found to be
particularly beneficial relative to the burden of computing the
O(nhid^2) second moment matrix. The current version of the code
merely computes the sufficient statistics apart from the second
moment matrix as a notational convenience. Expressions that most
naturally are expressed in terms of the second moment matrix are
now written with a different order of operations that avoids
O(nhid^2) operations but whose dependence on the dataset cannot be
expressed in terms only of sufficient statistics.
Parameters
----------
d : WRITEME
"""
def __init__(self, d):
self. d = {}
for key in d:
self.d[key] = d[key]
@classmethod
def from_observations(cls, needed_stats, V, H_hat, S_hat, var_s0_hat, var_s1_hat):
"""
Returns a SufficientStatistics
.. todo::
WRITEME properly
Parameters
----------
needed_stats : WRITEME
a set of string names of the statistics to include
V : WRITEME
a num_examples x nvis matrix of input examples
H_hat : WRITEME
a num_examples x nhid matrix of \hat{h} variational parameters
S_hat : WRITEME
variational parameters for expectation of s given h=1
var_s0_hat : WRITEME
variational parameters for variance of s given h=0
(only a vector of length nhid, since this is the same for
all inputs)
var_s1_hat : WRITEME
variational parameters for variance of s given h=1
(again, a vector of length nhid)
"""
m = T.cast(V.shape[0],config.floatX)
H_name = make_name(H_hat, 'anon_H_hat')
S_name = make_name(S_hat, 'anon_S_hat')
#mean_h
assert H_hat.dtype == config.floatX
mean_h = T.mean(H_hat, axis=0)
assert H_hat.dtype == mean_h.dtype
assert mean_h.dtype == config.floatX
mean_h.name = 'mean_h('+H_name+')'
#mean_v
mean_v = T.mean(V,axis=0)
#mean_sq_v
mean_sq_v = T.mean(T.sqr(V),axis=0)
#mean_s1
mean_s1 = T.mean(S_hat,axis=0)
#mean_sq_s
mean_sq_S = H_hat * (var_s1_hat + T.sqr(S_hat)) + (1. - H_hat)*(var_s0_hat)
mean_sq_s = T.mean(mean_sq_S,axis=0)
#mean_hs
mean_HS = H_hat * S_hat
mean_hs = T.mean(mean_HS,axis=0)
mean_hs.name = 'mean_hs(%s,%s)' % (H_name, S_name)
mean_s = mean_hs #this here refers to the expectation of the s variable, not s_hat
mean_D_sq_mean_Q_hs = T.mean(T.sqr(mean_HS), axis=0)
#mean_sq_hs
mean_sq_HS = H_hat * (var_s1_hat + T.sqr(S_hat))
mean_sq_hs = T.mean(mean_sq_HS, axis=0)
mean_sq_hs.name = 'mean_sq_hs(%s,%s)' % (H_name, S_name)
#mean_sq_mean_hs
mean_sq_mean_hs = T.mean(T.sqr(mean_HS), axis=0)
mean_sq_mean_hs.name = 'mean_sq_mean_hs(%s,%s)' % (H_name, S_name)
#mean_hsv
sum_hsv = T.dot(mean_HS.T,V)
sum_hsv.name = 'sum_hsv<from_observations>'
mean_hsv = sum_hsv / m
d = {
"mean_h" : mean_h,
"mean_v" : mean_v,
"mean_sq_v" : mean_sq_v,
"mean_s" : mean_s,
"mean_s1" : mean_s1,
"mean_sq_s" : mean_sq_s,
"mean_hs" : mean_hs,
"mean_sq_hs" : mean_sq_hs,
"mean_sq_mean_hs" : mean_sq_mean_hs,
"mean_hsv" : mean_hsv,
}
final_d = {}
for stat in needed_stats:
final_d[stat] = d[stat]
final_d[stat].name = 'observed_'+stat
return SufficientStatistics(final_d)
class S3C(Model, Block):
"""
If you use S3C in published work, please cite:
Large-Scale Feature Learning With Spike-and-Slab Sparse Coding.
Goodfellow, I., Courville, A., & Bengio, Y. ICML 2012.
Parameters
----------
nvis : WRITEME
# of visible units
nhid : WRITEME
# of hidden units
irange : WRITEME
(scalar) weights are initinialized ~U( [-irange,irange] )
init_bias_hid : WRITEME
initial value of hidden biases (scalar or vector)
init_B : WRITEME
initial value of B (scalar or vector)
min_B : WRITEME
See `max_B`
max_B : WRITEME
(scalar) learning updates to B are clipped to [min_B, max_B]
init_alpha : WRITEME
initial value of alpha (scalar or vector)
min_alpha : WRITEME
See `max_alpha`
max_alpha : WRITEME
(scalar) learning updates to alpha are clipped to [min_alpha, max_alpha]
init_mu : WRITEME
initial value of mu (scalar or vector)
min_mu : WRITEME
See `max_mu`
max_mu : WRITEME
clip mu updates to this range.
e_step : WRITEME
An E_Step object that determines what kind of E-step to do
if None, assumes that the S3C model is being driven by
a larger model, and does not generate theano functions
necessary for autonomous operation
m_step : WRITEME
An M_Step object that determines what kind of M-step to do
tied_B : WRITEME
if True, use a scalar times identity for the precision on visible units.
otherwise use a diagonal matrix for the precision on visible units
constrain_W_norm : bool
if true, norm of each column of W must be 1 at all times
init_unit_W : bool
if true, each column of W is initialized to have unit norm
monitor_stats : WRITEME
a list of sufficient statistics to monitor on the monitoring dataset
monitor_params : WRITEME
a list of parameters to monitor TODO: push this into Model base class
monitor_functional : WRITEME
if true, monitors the EM functional on the monitoring dataset
monitor_norms : bool
if true, monitors the norm of W at the end of each solve step, but before
blending with old W by new_coeff
This lets us see how much distortion is introduced by norm clipping
Note that unless new_coeff = 1, the post-solve norm monitored by this
flag will not be equal to the norm of the final parameter value, even
if no norm clipping is activated.
recycle_q : WRITEME
if nonzero, initializes the e-step with the output of the previous iteration's
e-step. obviously this should only be used if you are using the same data
in each batch. when recycle_q is nonzero, it should be set to the batch size.
disable_W_update : WRITEME
if true, doesn't update W (useful for experiments where you only learn the prior)
random_patches_src : WRITEME
if not None, should be a dataset
will set W to a batch
local_rf_src : Dataset, optional
if not None, it should be a dataset.
it requires the following other params:
- local_rf_shape : a 2 tuple
- One of:
- local_rf_stride: a 2 tuple or None
if specified, pull out patches on a regular grid
- local_rf_max_shape: a 2 tuple or None
if specified, pull out patches of random shape and
location
- local_rf_draw_patches : WRITEME
if true, local receptive fields are patches from
local_rf_src. otherwise, they're random patches.
will initialize the weights to have only local
receptive fields. (won't make a sparse matrix or
anything like that)
incompatible with random_patches_src for now
init_unit_W : bool
if True, initializes weights with unit norm
"""
def __init__(self, nvis, nhid, irange, init_bias_hid,
init_B, min_B, max_B,
init_alpha, min_alpha, max_alpha, init_mu,
m_step,
min_bias_hid=-1e30,
max_bias_hid=1e30,
min_mu=-1e30,
max_mu=1e30,
e_step=None,
tied_B=False,
monitor_stats=None,
monitor_params=None,
monitor_functional=False,
recycle_q=0,
seed=None,
disable_W_update=False,
constrain_W_norm=False,
monitor_norms=False,
random_patches_src=None,
local_rf_src=None,
local_rf_shape=None,
local_rf_max_shape=None,
local_rf_stride=None,
local_rf_draw_patches=False,
init_unit_W=None,
debug_m_step=False,
print_interval=10000,
stop_after_hack=None,
set_B_to_marginal_precision=False,
init_momentum=None,
final_momentum=None,
momentum_saturation_example=None):
Model.__init__(self)
Block.__init__(self)
self.debug_m_step = debug_m_step
self.set_B_to_marginal_precision = set_B_to_marginal_precision
self.monitoring_channel_prefix = ''
if init_unit_W is not None and not init_unit_W:
assert not constrain_W_norm
self.init_momentum = init_momentum
self.final_momentum = final_momentum
self.momentum_saturation_example = momentum_saturation_example
self.seed = seed
self.reset_rng()
self.irange = irange
self.nvis = nvis
self.input_space = VectorSpace(nvis)
self.nhid = nhid
if random_patches_src is not None:
self.init_W = random_patches_src.get_batch_design(nhid).T
assert local_rf_src is None
elif local_rf_src is not None:
s = local_rf_src.view_shape()
height, width, channels = s
W_img = np.zeros( (self.nhid, height, width, channels) )
last_row = s[0] - local_rf_shape[0]
last_col = s[1] - local_rf_shape[1]
if local_rf_stride is not None:
#local_rf_stride specified, make local_rfs on a grid
assert last_row % local_rf_stride[0] == 0
num_row_steps = last_row / local_rf_stride[0] + 1
assert last_col % local_rf_stride[1] == 0
num_col_steps = last_col /local_rf_stride[1] + 1
total_rfs = num_row_steps * num_col_steps
if self.nhid % total_rfs != 0:
raise ValueError('nhid modulo total_rfs should be 0, but we get %d modulo %d = %d' % (self.nhid, total_rfs, self.nhid % total_rfs))
filters_per_rf = self.nhid / total_rfs
idx = 0
for r in xrange(num_row_steps):
rc = r * local_rf_stride[0]
for c in xrange(num_col_steps):
cc = c * local_rf_stride[1]
for i in xrange(filters_per_rf):
if local_rf_draw_patches:
img = local_rf_src.get_batch_topo(1)[0]
local_rf = img[rc:rc+local_rf_shape[0],
cc:cc+local_rf_shape[1],
:]
else:
local_rf = self.rng.uniform(-self.irange,
self.irange,
(local_rf_shape[0], local_rf_shape[1], s[2]) )
W_img[idx,rc:rc+local_rf_shape[0],
cc:cc+local_rf_shape[1],:] = local_rf
idx += 1
assert idx == self.nhid
else:
#no stride specified, use random shaped patches
assert local_rf_max_shape is not None
for idx in xrange(nhid):
shape = [ self.rng.randint(min_shape,max_shape+1) for
min_shape, max_shape in zip(
local_rf_shape,
local_rf_max_shape) ]
loc = [self.rng.randint(0, bound - cur_width + 1) for
bound, cur_width in zip(s, shape)]
rc, cc = loc
if local_rf_draw_patches:
img = local_rf_src.get_batch_topo(1)[0]
local_rf = img[rc:rc+shape[0],
cc:cc+shape[1],
:]
else:
local_rf = self.rng.uniform(-self.irange,
self.irange,
(shape[0], shape[1], s[2]) )
W_img[idx,rc:rc+shape[0],
cc:cc+shape[1],:] = local_rf
self.init_W = local_rf_src.view_converter.topo_view_to_design_mat(W_img).T
else:
self.init_W = None
self.register_names_to_del(['init_W'])
if monitor_stats is None:
self.monitor_stats = []
else:
self.monitor_stats = [ elem for elem in monitor_stats ]
if monitor_params is None:
self.monitor_params = []
else:
self.monitor_params = [ elem for elem in monitor_params ]
self.init_unit_W = init_unit_W
self.print_interval = print_interval
self.constrain_W_norm = constrain_W_norm
self.stop_after_hack = stop_after_hack
self.monitor_norms = monitor_norms
self.disable_W_update = disable_W_update
self.monitor_functional = monitor_functional
self.init_bias_hid = init_bias_hid
def nostrings(x):
if isinstance(x,str):
return float(x)
return x
self.init_alpha = nostrings(init_alpha)
self.min_alpha = nostrings(min_alpha)
self.max_alpha = nostrings(max_alpha)
self.init_B = nostrings(init_B)
self.min_B = nostrings(min_B)
self.max_B = nostrings(max_B)
self.m_step = m_step
self.e_step = e_step
if e_step is None:
self.autonomous = False
assert not self.m_step.autonomous
#create a non-autonomous E step
self.e_step = E_Step(h_new_coeff_schedule = None,
rho = None,
monitor_kl = None,
monitor_energy_functional = None,
clip_reflections = None)
assert not self.e_step.autonomous
else:
self.autonomous = True
assert e_step.autonomous
assert self.m_step.autonomous
self.init_mu = init_mu
self.min_mu = np.cast[config.floatX](float(min_mu))
self.max_mu = np.cast[config.floatX](float(max_mu))
self.min_bias_hid = float(min_bias_hid)
self.max_bias_hid = float(max_bias_hid)
self.recycle_q = recycle_q
self.tied_B = tied_B
self.redo_everything()
def reset_rng(self):
"""
.. todo::
WRITEME
"""
self.rng = make_np_rng(self.seed, [1,2,3], which_method="uniform")
def redo_everything(self):
"""
.. todo::
WRITEME
"""
if self.init_W is not None:
W = self.init_W.copy()
else:
W = self.rng.uniform(-self.irange, self.irange, (self.nvis, self.nhid))
if self.constrain_W_norm or self.init_unit_W:
norms = numpy_norms(W)
W /= norms
self.W = sharedX(W, name = 'W')
self.bias_hid = sharedX(np.zeros(self.nhid)+self.init_bias_hid, name='bias_hid')
self.alpha = sharedX(np.zeros(self.nhid)+self.init_alpha, name = 'alpha')
self.mu = sharedX(np.zeros(self.nhid)+self.init_mu, name='mu')
if self.tied_B:
self.B_driver = sharedX(0.0+self.init_B, name='B')
else:
self.B_driver = sharedX(np.zeros(self.nvis)+self.init_B, name='B')
if self.recycle_q:
self.prev_H = sharedX(np.zeros((self.recycle_q,self.nhid)), name="prev_H")
self.prev_S = sharedX(np.zeros((self.recycle_q,self.nhid)), name="prev_S")
if self.debug_m_step:
warnings.warn('M step debugging activated-- this is only valid for certain settings, and causes a performance slowdown.')
self.energy_functional_diff = sharedX(0.)
if self.momentum_saturation_example is not None:
self.params_to_incs = {}
for param in self.get_params():
self.params_to_incs[param] = sharedX(np.zeros(param.get_value().shape), name = param.name + '_inc')
self.momentum = sharedX(self.init_momentum, name='momentum')
if self.monitor_norms:
self.debug_norms = sharedX(np.zeros(self.nhid))
self.redo_theano()
@classmethod
def energy_functional_needed_stats(cls):
"""
.. todo::
WRITEME
"""
return S3C.expected_log_prob_vhs_needed_stats()
def energy_functional(self, H_hat, S_hat, var_s0_hat, var_s1_hat, stats):
"""
.. todo::
WRITEME
Returns the energy_functional for a single batch of data stats is
assumed to be computed from and only from the same data points that
yielded H
"""
entropy_term = self.entropy_hs(H_hat = H_hat, var_s0_hat = var_s0_hat, var_s1_hat = var_s1_hat).mean()
likelihood_term = self.expected_log_prob_vhs(stats, H_hat = H_hat, S_hat = S_hat)
energy_functional = likelihood_term + entropy_term
assert len(energy_functional.type.broadcastable) == 0
return energy_functional
def energy_functional_batch(self, V, H_hat, S_hat, var_s0_hat, var_s1_hat):
"""
.. todo::
WRITEME
Returns the energy_functional for a single batch of data stats is
assumed to be computed from and only from the same data points that
yielded H
"""
entropy_term = self.entropy_hs(H_hat = H_hat, var_s0_hat = var_s0_hat, var_s1_hat = var_s1_hat)
assert len(entropy_term.type.broadcastable) == 1
likelihood_term = self.expected_log_prob_vhs_batch(V = V, H_hat = H_hat, S_hat = S_hat, var_s0_hat = var_s0_hat, var_s1_hat = var_s1_hat)
assert len(likelihood_term.type.broadcastable) == 1
energy_functional = likelihood_term + entropy_term
assert len(energy_functional.type.broadcastable) == 1
return energy_functional
def set_monitoring_channel_prefix(self, prefix):
"""
.. todo::
WRITEME
"""
self.monitoring_channel_prefix = prefix
def get_monitoring_channels(self, data):
"""
.. todo::
WRITEME
"""
space, source = self.get_monitoring_data_specs()
space.validate(data)
V = data
try:
self.compile_mode()
if self.m_step != None:
rval = self.m_step.get_monitoring_channels(V, self)
else:
rval = {}
if self.momentum_saturation_example is not None:
rval['momentum'] = self.momentum
from_e_step = self.e_step.get_monitoring_channels(V)
rval.update(from_e_step)
if self.debug_m_step:
rval['m_step_diff'] = self.energy_functional_diff
monitor_stats = len(self.monitor_stats) > 0
if monitor_stats or self.monitor_functional:
obs = self.infer(V)
needed_stats = set(self.monitor_stats)
if self.monitor_functional:
needed_stats = needed_stats.union(S3C.expected_log_prob_vhs_needed_stats())
stats = SufficientStatistics.from_observations( needed_stats = needed_stats,
V = V, ** obs )
H_hat = obs['H_hat']
S_hat = obs['S_hat']
var_s0_hat = obs['var_s0_hat']
var_s1_hat = obs['var_s1_hat']
if self.monitor_functional:
energy_functional = self.energy_functional(H_hat = H_hat, S_hat = S_hat, var_s0_hat = var_s0_hat,
var_s1_hat = var_s1_hat, stats = stats)
rval['energy_functional'] = energy_functional
if monitor_stats:
for stat in self.monitor_stats:
stat_val = stats.d[stat]
rval[stat+'_min'] = T.min(stat_val)
rval[stat+'_mean'] = T.mean(stat_val)
rval[stat+'_max'] = T.max(stat_val)
#end for stat
#end if monitor_stats
#end if monitor_stats or monitor_functional
if len(self.monitor_params) > 0:
for param in self.monitor_params:
param_val = getattr(self, param)
rval[param+'_min'] = full_min(param_val)
rval[param+'_mean'] = T.mean(param_val)
mx = full_max(param_val)
assert len(mx.type.broadcastable) == 0
rval[param+'_max'] = mx
if param == 'mu':
abs_mu = abs(self.mu)
rval['mu_abs_min'] = full_min(abs_mu)
rval['mu_abs_mean'] = T.mean(abs_mu)
rval['mu_abs_max'] = full_max(abs_mu)
if param == 'W':
norms = theano_norms(self.W)
rval['W_norm_min'] = full_min(norms)
rval['W_norm_mean'] = T.mean(norms)
rval['W_norm_max'] = T.max(norms)
if self.monitor_norms:
rval['post_solve_norms_min'] = T.min(self.debug_norms)
rval['post_solve_norms_max'] = T.max(self.debug_norms)
rval['post_solve_norms_mean'] = T.mean(self.debug_norms)
new_rval = {}
for key in rval:
new_rval[self.monitoring_channel_prefix+key] = rval[key]
rval = new_rval
return rval
finally:
self.deploy_mode()
def get_monitoring_data_specs(self):
"""
Get the data_specs describing the data for get_monitoring_channel.
This implementation returns specification corresponding to unlabeled
inputs.
WRITEME: Returns section
"""
return (self.get_input_space(), self.get_input_source())
def __call__(self, V):
"""
.. todo::
WRITEME
This is the symbolic transformation for the Block class
"""
if not hasattr(self,'w'):
self.make_pseudoparams()
obs = self.infer(V)
return obs['H_hat']
def compile_mode(self):
"""
If any shared variables need to have batch-size dependent sizes, sets
them all to the sizes used for interactive debugging during graph
construction
"""
if self.recycle_q:
self.prev_H.set_value(
np.cast[self.prev_H.dtype](
np.zeros((self._test_batch_size, self.nhid)) \
+ 1./(1.+np.exp(-self.bias_hid.get_value()))))
self.prev_S.set_value(
np.cast[self.prev_S.dtype](
np.zeros((self._test_batch_size, self.nhid)) + self.mu.get_value() ) )
def deploy_mode(self):
"""
If any shared variables need to have batch-size dependent sizes, sets
them all to their runtime sizes
"""
if self.recycle_q:
self.prev_H.set_value( np.cast[self.prev_H.dtype]( np.zeros((self.recycle_q, self.nhid)) + 1./(1.+np.exp(-self.bias_hid.get_value()))))
self.prev_S.set_value( np.cast[self.prev_S.dtype]( np.zeros((self.recycle_q, self.nhid)) + self.mu.get_value() ) )
def get_params(self):
"""
.. todo::
WRITEME
"""
return [self.W, self.bias_hid, self.alpha, self.mu, self.B_driver ]
def energy_vhs(self, V, H, S):
"""
.. todo::
WRITEME
H MUST be binary
"""
h_term = - T.dot(H, self.bias_hid)
assert len(h_term.type.broadcastable) == 1
s_term_1 = T.dot(T.sqr(S), self.alpha)/2.
s_term_2 = -T.dot(S * self.mu * H , self.alpha)
#s_term_3 = T.dot(T.sqr(self.mu * H), self.alpha)/2.
s_term_3 = T.dot(T.sqr(self.mu) * H, self.alpha) / 2.
s_term = s_term_1 + s_term_2 + s_term_3
#s_term = T.dot( T.sqr( S - self.mu * H) , self.alpha) / 2.
assert len(s_term.type.broadcastable) == 1
recons = T.dot(H*S, self.W.T)
v_term_1 = T.dot( T.sqr(V), self.B) / 2.
v_term_2 = T.dot( - V * recons, self.B)
v_term_3 = T.dot( T.sqr(recons), self.B) / 2.
v_term = v_term_1 + v_term_2 + v_term_3
#v_term = T.dot( T.sqr( V - recons), self. B) / 2.
assert len(v_term.type.broadcastable) == 1
rval = h_term + s_term + v_term
assert len(rval.type.broadcastable) == 1
return rval
def expected_energy_vhs(self, V, H_hat, S_hat, var_s0_hat, var_s1_hat):
"""
.. todo::
WRITEME
This is not the same as negative expected log prob,
which includes the constant term for the log partition function
"""
var_HS = H_hat * var_s1_hat + (1.-H_hat) * var_s0_hat
half = as_floatX(.5)
HS = H_hat * S_hat
sq_HS = H_hat * ( var_s1_hat + T.sqr(S_hat))
sq_S = sq_HS + (1.-H_hat)*(var_s0_hat)
presign = T.dot(H_hat, self.bias_hid)
presign.name = 'presign'
h_term = - presign
assert len(h_term.type.broadcastable) == 1
precoeff = T.dot(sq_S, self.alpha)
precoeff.name = 'precoeff'
s_term_1 = half * precoeff
assert len(s_term_1.type.broadcastable) == 1
presign2 = T.dot(HS, self.alpha * self.mu)
presign2.name = 'presign2'
s_term_2 = - presign2
assert len(s_term_2.type.broadcastable) == 1
s_term_3 = half * T.dot(H_hat, T.sqr(self.mu) * self.alpha)
assert len(s_term_3.type.broadcastable) == 1
s_term = s_term_1 + s_term_2 + s_term_3
v_term_1 = half * T.dot(T.sqr(V),self.B)
assert len(v_term_1.type.broadcastable) == 1
term6_factor1 = V * self.B
term6_factor2 = T.dot(HS, self.W.T)
v_term_2 = - (term6_factor1 * term6_factor2).sum(axis=1)
assert len(v_term_2.type.broadcastable) == 1
term7_subterm1 = T.dot(T.sqr(T.dot(HS, self.W.T)), self.B)
assert len(term7_subterm1.type.broadcastable) == 1
term7_subterm2 = - T.dot( T.dot(T.sqr(HS), T.sqr(self.W.T)), self.B)
term7_subterm3 = T.dot( T.dot(sq_HS, T.sqr(self.W.T)), self.B )
v_term_3 = half * (term7_subterm1 + term7_subterm2 + term7_subterm3)
assert len(v_term_3.type.broadcastable) == 1
v_term = v_term_1 + v_term_2 + v_term_3
rval = h_term + s_term + v_term
return rval
def entropy_h(self, H_hat):
"""
.. todo::
WRITEME
"""
for H_hat_v in get_debug_values(H_hat):
assert H_hat_v.min() >= 0.0
assert H_hat_v.max() <= 1.0
return entropy_binary_vector(H_hat)
def entropy_hs(self, H_hat, var_s0_hat, var_s1_hat):
"""
.. todo::
WRITEME
"""
half = as_floatX(.5)
one = as_floatX(1.)
two = as_floatX(2.)
pi = as_floatX(np.pi)
for H_hat_v in get_debug_values(H_hat):
assert H_hat_v.min() >= 0.0
assert H_hat_v.max() <= 1.0
term1_plus_term2 = self.entropy_h(H_hat)
assert len(term1_plus_term2.type.broadcastable) == 1
term3 = T.sum( H_hat * ( half * (T.log(var_s1_hat) + T.log(two*pi) + one ) ) , axis= 1)
assert len(term3.type.broadcastable) == 1
term4 = T.dot( 1.-H_hat, half * (T.log(var_s0_hat) + T.log(two*pi) + one ))
assert len(term4.type.broadcastable) == 1
for t12, t3, t4 in get_debug_values(term1_plus_term2, term3, term4):
debug_assert(not contains_nan(t12))
debug_assert(not contains_nan(t3))
debug_assert(not contains_nan(t4))
rval = term1_plus_term2 + term3 + term4
assert len(rval.type.broadcastable) == 1
return rval
def infer(self, V, return_history=False):
"""
.. todo::
WRITEME
"""
return self.e_step.infer(V, return_history)
def make_learn_func(self, V):
"""
WRITEME
Parameters
----------
V : tensor_like
A symbolic design matrix
WRITEME: Returns section
"""
#E step
hidden_obs = self.infer(V)
stats = SufficientStatistics.from_observations(needed_stats = self.m_step.needed_stats(),
V = V, **hidden_obs)
H_hat = hidden_obs['H_hat']
S_hat = hidden_obs['S_hat']
learning_updates = self.m_step.get_updates(self, stats, H_hat, S_hat)
if self.recycle_q:
learning_updates[self.prev_H] = H_hat
learning_updates[self.prev_S] = S_hat
self.modify_updates(learning_updates)
if self.debug_m_step:
energy_functional_before = self.energy_functional(H = hidden_obs['H'],
var_s0_hat = hidden_obs['var_s0_hat'],
var_s1_hat = hidden_obs['var_s1_hat'],
stats = stats)
tmp_bias_hid = self.bias_hid
tmp_mu = self.mu
tmp_alpha = self.alpha
tmp_W = self.W
tmp_B_driver = self.B_driver
self.bias_hid = learning_updates[self.bias_hid]
self.mu = learning_updates[self.mu]
self.alpha = learning_updates[self.alpha]
if self.W in learning_updates:
self.W = learning_updates[self.W]
self.B_driver = learning_updates[self.B_driver]
self.make_pseudoparams()
try:
energy_functional_after = self.energy_functional(H_hat = hidden_obs['H_hat'],
var_s0_hat = hidden_obs['var_s0_hat'],
var_s1_hat = hidden_obs['var_s1_hat'],
stats = stats)
finally:
self.bias_hid = tmp_bias_hid
self.mu = tmp_mu
self.alpha = tmp_alpha
self.W = tmp_W
self.B_driver = tmp_B_driver
self.make_pseudoparams()
energy_functional_diff = energy_functional_after - energy_functional_before