-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
dbm.py
1954 lines (1598 loc) · 67.1 KB
/
dbm.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
"""
This module contains cost functions to use with deep Boltzmann machines
(pylearn2.models.dbm).
"""
__authors__ = ["Ian Goodfellow", "Vincent Dumoulin"]
__copyright__ = "Copyright 2012, Universite de Montreal"
__credits__ = ["Ian Goodfellow"]
__license__ = "3-clause BSD"
__maintainer__ = "LISA Lab"
import collections
from functools import wraps
import logging
import numpy as np
import operator
import warnings
from theano.compat.six.moves import reduce, xrange
from theano import config
from theano.sandbox.rng_mrg import MRG_RandomStreams
RandomStreams = MRG_RandomStreams
from theano import tensor as T
import pylearn2
from pylearn2.compat import OrderedDict
from pylearn2.costs.cost import Cost
from pylearn2.costs.cost import (
FixedVarDescr, DefaultDataSpecsMixin, NullDataSpecsMixin
)
from pylearn2.models import dbm
from pylearn2.models.dbm import BinaryVectorMaxPool
from pylearn2.models.dbm import flatten
from pylearn2.models.dbm.layer import BinaryVector
from pylearn2.models.dbm import Softmax
from pylearn2 import utils
from pylearn2.utils import make_name
from pylearn2.utils import safe_izip
from pylearn2.utils import safe_zip
from pylearn2.utils import sharedX
from pylearn2.utils.rng import make_theano_rng
logger = logging.getLogger(__name__)
class BaseCD(Cost):
"""
Parameters
----------
num_chains : int
The number of negative chains to use with PCD / SML.
WRITEME : how is this meant to be used with CD? Do you just need to
set it to be equal to the batch size? If so: TODO, get rid of this
redundant aspect of the interface.
num_gibbs_steps : int
The number of Gibbs steps to use in the negative phase. (i.e., if
you want to use CD-k or PCD-k, this is "k").
supervised : bool
If True, requests class labels and models the joint distrbution over
features and labels.
toronto_neg : bool
If True, use a bit of mean field in the negative phase.
Ruslan Salakhutdinov's matlab code does this.
theano_rng : MRG_RandomStreams, optional
If specified, uses this object to generate all random numbers.
Otherwise, makes its own random number generator.
"""
def __init__(self, num_chains, num_gibbs_steps, supervised=False,
toronto_neg=False, theano_rng=None):
self.__dict__.update(locals())
del self.self
self.theano_rng = make_theano_rng(theano_rng, 2012 + 10 + 14,
which_method="binomial")
assert supervised in [True, False]
def expr(self, model, data):
"""
The partition function makes this intractable.
Parameters
----------
model : DBM
data : Batch in get_data_specs format
"""
self.get_data_specs(model)[0].validate(data)
return None
@wraps(Cost.get_monitoring_channels)
def get_monitoring_channels(self, model, data):
self.get_data_specs(model)[0].validate(data)
rval = OrderedDict()
if self.supervised:
X, Y = data
else:
X = data
Y = None
history = model.mf(X, return_history=True)
q = history[-1]
if self.supervised:
assert len(data) == 2
Y_hat = q[-1]
true = T.argmax(Y, axis=1)
pred = T.argmax(Y_hat, axis=1)
# true = Print('true')(true)
# pred = Print('pred')(pred)
wrong = T.neq(true, pred)
err = T.cast(wrong.mean(), X.dtype)
rval['misclass'] = err
if len(model.hidden_layers) > 1:
q = model.mf(X, Y=Y)
pen = model.hidden_layers[-2].upward_state(q[-2])
Y_recons = model.hidden_layers[-1].mf_update(state_below=pen)
pred = T.argmax(Y_recons, axis=1)
wrong = T.neq(true, pred)
rval['recons_misclass'] = T.cast(wrong.mean(), X.dtype)
return rval
@wraps(Cost.get_gradients)
def get_gradients(self, model, data):
self.get_data_specs(model)[0].validate(data)
if self.supervised:
X, Y = data
assert Y is not None
else:
X = data
Y = None
pos_phase_grads, pos_updates = self._get_positive_phase(model, X, Y)
neg_phase_grads, neg_updates = self._get_negative_phase(model, X, Y)
updates = OrderedDict()
for key, val in pos_updates.items():
updates[key] = val
for key, val in neg_updates.items():
updates[key] = val
gradients = OrderedDict()
for param in list(pos_phase_grads.keys()):
gradients[param] = neg_phase_grads[param] + pos_phase_grads[param]
return gradients, updates
def _get_toronto_neg(self, model, layer_to_chains):
"""
.. todo::
WRITEME
"""
# Ruslan Salakhutdinov's undocumented negative phase from
# http://www.mit.edu/~rsalakhu/code_DBM/dbm_mf.m
# IG copied it here without fully understanding it, so it
# only applies to exactly the same model structure as
# in that code.
assert isinstance(model.visible_layer, BinaryVector)
assert isinstance(model.hidden_layers[0], BinaryVectorMaxPool)
assert model.hidden_layers[0].pool_size == 1
assert isinstance(model.hidden_layers[1], BinaryVectorMaxPool)
assert model.hidden_layers[1].pool_size == 1
assert isinstance(model.hidden_layers[2], Softmax)
assert len(model.hidden_layers) == 3
params = list(model.get_params())
V_samples = layer_to_chains[model.visible_layer]
H1_samples, H2_samples, Y_samples = [layer_to_chains[layer] for
layer in model.hidden_layers]
H1_mf = model.hidden_layers[0].mf_update(
state_below=model.visible_layer.upward_state(V_samples),
state_above=model.hidden_layers[1].downward_state(H2_samples),
layer_above=model.hidden_layers[1])
Y_mf = model.hidden_layers[2].mf_update(
state_below=model.hidden_layers[1].upward_state(H2_samples))
H2_mf = model.hidden_layers[1].mf_update(
state_below=model.hidden_layers[0].upward_state(H1_mf),
state_above=model.hidden_layers[2].downward_state(Y_mf),
layer_above=model.hidden_layers[2])
expected_energy_p = model.energy(
V_samples, [H1_mf, H2_mf, Y_samples]
).mean()
constants = flatten([V_samples, H1_mf, H2_mf, Y_samples])
neg_phase_grads = OrderedDict(
safe_zip(params, T.grad(-expected_energy_p, params,
consider_constant=constants)))
return neg_phase_grads
def _get_standard_neg(self, model, layer_to_chains):
"""
.. todo::
WRITEME
TODO:reduce variance of negative phase by
integrating out the even-numbered layers. The
Rao-Blackwellize method can do this for you when
expected gradient = gradient of expectation, but
doing this in general is trickier.
"""
params = list(model.get_params())
# layer_to_chains = model.rao_blackwellize(layer_to_chains)
expected_energy_p = model.energy(
layer_to_chains[model.visible_layer],
[layer_to_chains[layer] for layer in model.hidden_layers]
).mean()
samples = flatten(layer_to_chains.values())
for i, sample in enumerate(samples):
if sample.name is None:
sample.name = 'sample_' + str(i)
neg_phase_grads = OrderedDict(
safe_zip(params, T.grad(-expected_energy_p, params,
consider_constant=samples,
disconnected_inputs='ignore'))
)
return neg_phase_grads
def _get_variational_pos(self, model, X, Y):
"""
.. todo::
WRITEME
"""
if self.supervised:
assert Y is not None
# note: if the Y layer changes to something without linear energy,
# we'll need to make the expected energy clamp Y in the positive
# phase
assert isinstance(model.hidden_layers[-1], Softmax)
q = model.mf(X, Y)
"""
Use the non-negativity of the KL divergence to construct a lower
bound on the log likelihood. We can drop all terms that are
constant with repsect to the model parameters:
log P(v) = L(v, q) + KL(q || P(h|v))
L(v, q) = log P(v) - KL(q || P(h|v))
L(v, q) = log P(v) - sum_h q(h) log q(h) + q(h) log P(h | v)
L(v, q) = log P(v) + sum_h q(h) log P(h | v) + const
L(v, q) = log P(v) + sum_h q(h) log P(h, v)
- sum_h q(h) log P(v) + const
L(v, q) = sum_h q(h) log P(h, v) + const
L(v, q) = sum_h q(h) -E(h, v) - log Z + const
so the cost we want to minimize is
expected_energy + log Z + const
Note: for the RBM, this bound is exact, since the KL divergence
goes to 0.
"""
variational_params = flatten(q)
# The gradients of the expected energy under q are easy, we can just
# do that in theano
expected_energy_q = model.expected_energy(X, q).mean()
params = list(model.get_params())
gradients = OrderedDict(
safe_zip(params, T.grad(expected_energy_q,
params,
consider_constant=variational_params,
disconnected_inputs='ignore'))
)
return gradients
def _get_sampling_pos(self, model, X, Y):
"""
.. todo::
WRITEME
"""
layer_to_clamp = OrderedDict([(model.visible_layer, True)])
layer_to_pos_samples = OrderedDict([(model.visible_layer, X)])
if self.supervised:
# note: if the Y layer changes to something without linear energy,
# we'll need to make the expected energy clamp Y in the
# positive phase
assert isinstance(model.hidden_layers[-1], Softmax)
layer_to_clamp[model.hidden_layers[-1]] = True
layer_to_pos_samples[model.hidden_layers[-1]] = Y
hid = model.hidden_layers[:-1]
else:
assert Y is None
hid = model.hidden_layers
for layer in hid:
mf_state = layer.init_mf_state()
def recurse_zeros(x):
if isinstance(x, tuple):
return tuple([recurse_zeros(e) for e in x])
return x.zeros_like()
layer_to_pos_samples[layer] = recurse_zeros(mf_state)
layer_to_pos_samples = model.sampling_procedure.sample(
layer_to_state=layer_to_pos_samples,
layer_to_clamp=layer_to_clamp,
num_steps=self.num_gibbs_steps,
theano_rng=self.theano_rng)
q = [layer_to_pos_samples[layer] for layer in model.hidden_layers]
pos_samples = flatten(q)
# The gradients of the expected energy under q are easy, we can just
# do that in theano
expected_energy_q = model.energy(X, q).mean()
params = list(model.get_params())
gradients = OrderedDict(
safe_zip(params, T.grad(expected_energy_q, params,
consider_constant=pos_samples,
disconnected_inputs='ignore'))
)
return gradients
class PCD(DefaultDataSpecsMixin, BaseCD):
"""
An intractable cost representing the negative log likelihood of a DBM.
The gradient of this bound is computed using a persistent
markov chain.
TODO add citation to Tieleman paper, Younes paper
Parameters
----------
Same as BaseCD
See Also
--------
BaseCD : The base class of this class (where the constructor
parameters are documented)
"""
def _get_positive_phase(self, model, X, Y=None):
"""
Computes the positive phase using Gibbs sampling.
Returns
-------
gradients : OrderedDict
A dictionary mapping parameters to positive phase gradients.
updates : OrderedDict
An empty dictionary
"""
return self._get_sampling_pos(model, X, Y), OrderedDict()
def _get_negative_phase(self, model, X, Y=None):
"""
.. todo::
WRITEME
"""
layer_to_chains = model.make_layer_to_state(self.num_chains)
def recurse_check(l):
if isinstance(l, (list, tuple, collections.ValuesView)):
for elem in l:
recurse_check(elem)
else:
assert l.get_value().shape[0] == self.num_chains
recurse_check(layer_to_chains.values())
model.layer_to_chains = layer_to_chains
# Note that we replace layer_to_chains with a dict mapping to the new
# state of the chains
updates, layer_to_chains = model.get_sampling_updates(
layer_to_chains, self.theano_rng, num_steps=self.num_gibbs_steps,
return_layer_to_updated=True)
if self.toronto_neg:
neg_phase_grads = self._get_toronto_neg(model, layer_to_chains)
else:
neg_phase_grads = self._get_standard_neg(model, layer_to_chains)
return neg_phase_grads, updates
class VariationalPCD(DefaultDataSpecsMixin, BaseCD):
"""
An intractable cost representing the variational upper bound
on the negative log likelihood of a DBM.
The gradient of this bound is computed using a persistent
markov chain.
TODO add citation to Tieleman paper, Younes paper
Parameters
----------
Same as BaseCD.
See Also
--------
BaseCD : The base class of this class (where the constructor
parameters are documented)
"""
def expr(self, model, data):
"""
The partition function makes this intractable.
Parameters
----------
model : Model
data : Minibatch in get_data_specs format
Returns
-------
None : (Always returns None)
"""
self.get_data_specs(model)[0].validate(data)
return None
def _get_positive_phase(self, model, X, Y=None):
"""
.. todo::
WRITEME
"""
return self._get_variational_pos(model, X, Y), OrderedDict()
def _get_negative_phase(self, model, X, Y=None):
"""
.. todo::
WRITEME
d/d theta log Z = (d/d theta Z) / Z
= (d/d theta sum_h sum_v exp(-E(v,h)) ) / Z
= (sum_h sum_v - exp(-E(v,h)) d/d theta E(v,h) ) / Z
= - sum_h sum_v P(v,h) d/d theta E(v,h)
"""
layer_to_chains = model.make_layer_to_state(self.num_chains)
def recurse_check(l):
if isinstance(l, (list, tuple)):
for elem in l:
recurse_check(elem)
else:
assert l.get_value().shape[0] == self.num_chains
recurse_check(layer_to_chains.values())
model.layer_to_chains = layer_to_chains
# Note that we replace layer_to_chains with a dict mapping to the new
# state of the chains
updates, layer_to_chains = model.get_sampling_updates(
layer_to_chains,
self.theano_rng, num_steps=self.num_gibbs_steps,
return_layer_to_updated=True)
if self.toronto_neg:
neg_phase_grads = self._get_toronto_neg(model, layer_to_chains)
else:
neg_phase_grads = self._get_standard_neg(model, layer_to_chains)
return neg_phase_grads, updates
class VariationalPCD_VarianceReduction(DefaultDataSpecsMixin, Cost):
"""
Like pylearn2.costs.dbm.VariationalPCD, indeed a copy-paste of it,
but with a variance reduction rule hard-coded for 2 binary
hidden layers and a softmax label layer
The variance reduction rule used here is to average together the expected
energy you get by integrating out the odd numbered layers and the
expected energy you get by integrating out the even numbered layers.
This is the most "textbook correct" implementation of the negative
phase, though not the one works the best in practice ("toronto_neg").
Parameters
----------
num_chains : int
Number of negative chains to use
num_gibbs_steps : int
Number of Gibbs steps to use for each gradient calculation
supervised : bool
If True, calculates gradient of log P(X, Y), otherwise just
log P(X)
"""
def __init__(self, num_chains, num_gibbs_steps, supervised=False):
"""
"""
self.__dict__.update(locals())
del self.self
self.theano_rng = MRG_RandomStreams(2012 + 10 + 14)
assert supervised in [True, False]
def expr(self, model, data):
"""
The partition function makes this intractable.
Parameters
----------
model : Model
data : Batch in get_data_specs format
Returns
-------
None : (always returns None because it's intractable)
"""
if self.supervised:
X, Y = data
assert Y is not None
return None
@wraps(Cost.get_monitoring_channels)
def get_monitoring_channels(self, model, data):
rval = OrderedDict()
if self.supervised:
X, Y = data
else:
X = data
Y = None
history = model.mf(X, return_history=True)
q = history[-1]
if self.supervised:
assert Y is not None
Y_hat = q[-1]
true = T.argmax(Y, axis=1)
pred = T.argmax(Y_hat, axis=1)
# true = Print('true')(true)
# pred = Print('pred')(pred)
wrong = T.neq(true, pred)
err = T.cast(wrong.mean(), X.dtype)
rval['misclass'] = err
if len(model.hidden_layers) > 1:
q = model.mf(X, Y=Y)
pen = model.hidden_layers[-2].upward_state(q[-2])
Y_recons = model.hidden_layers[-1].mf_update(state_below=pen)
pred = T.argmax(Y_recons, axis=1)
wrong = T.neq(true, pred)
rval['recons_misclass'] = T.cast(wrong.mean(), X.dtype)
return rval
def get_gradients(self, model, data):
"""
PCD approximation to the gradient of the bound.
Keep in mind this is a cost, so we are upper bounding
the negative log likelihood.
Parameters
----------
model : DBM
data : Batch in get_data_specs_format
Returns
-------
grads : OrderedDict
Dictionary mapping from parameters to (approximate) gradients
updates : OrderedDict
Dictionary containing the Gibbs sampling updates used to
maintain the Markov chain used for PCD
"""
if self.supervised:
X, Y = data
assert Y is not None
# note: if the Y layer changes to something without linear energy,
# we'll need to make the expected energy clamp Y in the positive
# phase
assert isinstance(model.hidden_layers[-1], dbm.Softmax)
else:
X = data
Y = None
q = model.mf(X, Y)
"""
Use the non-negativity of the KL divergence to construct a lower bound
on the log likelihood. We can drop all terms that are constant with
respect to the model parameters:
log P(v) = L(v, q) + KL(q || P(h|v))
L(v, q) = log P(v) - KL(q || P(h|v))
L(v, q) = log P(v) - sum_h q(h) log q(h) + q(h) log P(h | v)
L(v, q) = log P(v) + sum_h q(h) log P(h | v) + const
L(v, q) = log P(v) + sum_h q(h) log P(h, v) - sum_h q(h) log P(v) + C
L(v, q) = sum_h q(h) log P(h, v) + C
L(v, q) = sum_h q(h) - E(h, v) - log Z + C
so the cost we want to minimize is
expected_energy + log Z + C
Note: for the RBM, this bound is exact, since the KL divergence
goes to 0.
"""
variational_params = flatten(q)
# The gradients of the expected energy under q are easy, we can just
# do that in theano
expected_energy_q = model.expected_energy(X, q).mean()
params = list(model.get_params())
grads = T.grad(expected_energy_q, params,
consider_constant=variational_params,
disconnected_inputs='ignore')
gradients = OrderedDict(safe_zip(params, grads))
"""
d/d theta log Z = (d/d theta Z) / Z
= (d/d theta sum_h sum_v exp(-E(v,h)) ) / Z
= (sum_h sum_v - exp(-E(v,h)) d/d theta E(v,h) ) / Z
= - sum_h sum_v P(v,h) d/d theta E(v,h)
"""
layer_to_chains = model.make_layer_to_state(self.num_chains)
def recurse_check(l):
if isinstance(l, (list, tuple)):
for elem in l:
recurse_check(elem)
else:
assert l.get_value().shape[0] == self.num_chains
recurse_check(layer_to_chains.values())
model.layer_to_chains = layer_to_chains
# Note that we replace layer_to_chains with a dict mapping to the new
# state of the chains
gsu = model.get_sampling_updates
updates, layer_to_chains = gsu(layer_to_chains, self.theano_rng,
num_steps=self.num_gibbs_steps,
return_layer_to_updated=True)
# Variance reduction is hardcoded for this exact model
assert isinstance(model.visible_layer, dbm.BinaryVector)
assert isinstance(model.hidden_layers[0], dbm.BinaryVectorMaxPool)
assert model.hidden_layers[0].pool_size == 1
assert isinstance(model.hidden_layers[1], dbm.BinaryVectorMaxPool)
assert model.hidden_layers[1].pool_size == 1
assert isinstance(model.hidden_layers[2], dbm.Softmax)
assert len(model.hidden_layers) == 3
V_samples = layer_to_chains[model.visible_layer]
H1_samples, H2_samples, Y_samples = [layer_to_chains[layer] for layer
in model.hidden_layers]
sa = model.hidden_layers[0].downward_state(H1_samples)
V_mf = model.visible_layer.inpaint_update(layer_above=
model.hidden_layers[0],
state_above=sa)
f = model.hidden_layers[0].mf_update
sb = model.visible_layer.upward_state(V_samples)
sa = model.hidden_layers[1].downward_state(H2_samples)
H1_mf = f(state_below=sb, state_above=sa,
layer_above=model.hidden_layers[1])
f = model.hidden_layers[1].mf_update
sb = model.hidden_layers[0].upward_state(H1_samples)
sa = model.hidden_layers[2].downward_state(Y_samples)
H2_mf = f(state_below=sb,
state_above=sa,
layer_above=model.hidden_layers[2])
sb = model.hidden_layers[1].upward_state(H2_samples)
Y_mf = model.hidden_layers[2].mf_update(state_below=sb)
e1 = model.energy(V_samples, [H1_mf, H2_samples, Y_mf]).mean()
e2 = model.energy(V_mf, [H1_samples, H2_mf, Y_samples]).mean()
expected_energy_p = 0.5 * (e1 + e2)
constants = flatten([V_samples, V_mf, H1_samples, H1_mf, H2_samples,
H2_mf, Y_mf, Y_samples])
neg_phase_grads = OrderedDict(safe_zip(params, T.grad(
-expected_energy_p, params, consider_constant=constants)))
for param in list(gradients.keys()):
gradients[param] = neg_phase_grads[param] + gradients[param]
return gradients, updates
class VariationalCD(DefaultDataSpecsMixin, BaseCD):
"""
An intractable cost representing the negative log likelihood of a DBM.
The gradient of this bound is computed using a markov chain initialized
with the training example.
Source: Hinton, G. Training Products of Experts by Minimizing
Contrastive Divergence
Parameters
----------
num_chains: int
Ignored, I guess?
num_gibbs_steps : int
The number of Gibbs steps to use in the negative phase. (i.e., if
you want to use CD-k or PCD-k, this is "k").
supervised : bool
If True, requests class labels and models the joint distrbution over
features and labels.
toronto_neg : bool
If True, use a bit of mean field in the negative phase.
Ruslan Salakhutdinov's matlab code does this.
theano_rng : MRG_RandomStreams, optional
If specified, uses this object to generate all random numbers.
Otherwise, makes its own random number generator.
"""
def _get_positive_phase(self, model, X, Y=None):
"""
.. todo::
WRITEME
"""
return self._get_variational_pos(model, X, Y), OrderedDict()
def _get_negative_phase(self, model, X, Y=None):
"""
.. todo::
WRITEME
d/d theta log Z = (d/d theta Z) / Z
= (d/d theta sum_h sum_v exp(-E(v,h)) ) / Z
= (sum_h sum_v - exp(-E(v,h)) d/d theta E(v,h) ) / Z
= - sum_h sum_v P(v,h) d/d theta E(v,h)
"""
layer_to_clamp = OrderedDict([(model.visible_layer, True)])
layer_to_chains = model.make_layer_to_symbolic_state(self.num_chains,
self.theano_rng)
# The examples are used to initialize the visible layer's chains
layer_to_chains[model.visible_layer] = X
# If we use supervised training, we need to make sure the targets are
# also clamped.
if self.supervised:
assert Y is not None
# note: if the Y layer changes to something without linear energy,
# we'll need to make the expected energy clamp Y in the positive
# phase
assert isinstance(model.hidden_layers[-1], Softmax)
layer_to_clamp[model.hidden_layers[-1]] = True
layer_to_chains[model.hidden_layers[-1]] = Y
model.layer_to_chains = layer_to_chains
# Note that we replace layer_to_chains with a dict mapping to the new
# state of the chains
# We first initialize the chain by clamping the visible layer and the
# target layer (if it exists)
layer_to_chains = model.sampling_procedure.sample(
layer_to_chains,
self.theano_rng,
layer_to_clamp=layer_to_clamp,
num_steps=1
)
# We then do the required mcmc steps
layer_to_chains = model.sampling_procedure.sample(
layer_to_chains,
self.theano_rng,
num_steps=self.num_gibbs_steps
)
if self.toronto_neg:
neg_phase_grads = self._get_toronto_neg(model, layer_to_chains)
else:
neg_phase_grads = self._get_standard_neg(model, layer_to_chains)
return neg_phase_grads, OrderedDict()
class MF_L1_ActCost(DefaultDataSpecsMixin, Cost):
"""
L1 activation cost on the mean field parameters.
Adds a cost of:
coeff * max( abs(mean_activation - target) - eps, 0)
averaged over units
for each layer.
Parameters
----------
targets : list
A list, one element per layer, specifying the activation each
layer should be encouraged to have.
Each element may also be a list depending on the structure of
the layer.
See each layer's get_l1_act_cost for a specification of what
the state should be.
coeffs: list
A list, one element per layer, specifying the coefficient
to put on the L1 activation cost for each layer.
supervised: bool
If true, runs mean field on both X and Y, penalizing
the layers in between only
"""
def __init__(self, targets, coeffs, eps, supervised):
self.__dict__.update(locals())
del self.self
@wraps(Cost.expr)
def expr(self, model, data, ** kwargs):
if self.supervised:
X, Y = data
H_hat = model.mf(X, Y=Y)
else:
X = data
H_hat = model.mf(X)
hidden_layers = model.hidden_layers
if self.supervised:
hidden_layers = hidden_layers[:-1]
H_hat = H_hat[:-1]
layer_costs = []
for layer, mf_state, targets, coeffs, eps in \
safe_zip(hidden_layers, H_hat, self.targets, self.coeffs,
self.eps):
cost = None
try:
cost = layer.get_l1_act_cost(mf_state, targets, coeffs, eps)
except NotImplementedError:
assert isinstance(coeffs, float) and coeffs == 0.
assert cost is None # if this gets triggered, there might
# have been a bug, where costs from lower layers got
# applied to higher layers that don't implement the cost
cost = None
if cost is not None:
layer_costs.append(cost)
assert T.scalar() != 0. # make sure theano semantics do what I want
layer_costs = [cost_ for cost_ in layer_costs if cost_ != 0.]
if len(layer_costs) == 0:
return T.as_tensor_variable(0.)
else:
total_cost = reduce(operator.add, layer_costs)
total_cost.name = 'MF_L1_ActCost'
assert total_cost.ndim == 0
return total_cost
class MF_L2_ActCost(DefaultDataSpecsMixin, Cost):
"""
An L2 penalty on the amount that the hidden unit mean field parameters
deviate from desired target values.
Parameters
----------
targets : list
A list, one element per layer, specifying the activation each
layer should be encouraged to have.
Each element may also be a list depending on the structure of
the layer.
See each layer's get_l2_act_cost for a specification of what
the state should be.
coeffs: list
A list, one element per layer, specifying the coefficient
to put on the L2 activation cost for each layer.
supervised: bool
If true, runs mean field on both X and Y, penalizing
the layers in between only
"""
def __init__(self, targets, coeffs, supervised=False):
targets = fix(targets)
coeffs = fix(coeffs)
self.__dict__.update(locals())
del self.self
def expr(self, model, data, return_locals=False, **kwargs):
"""
Returns the expression for the Cost.
Parameters
----------
model : Model
data : Batch in get_data_specs format
return_locals : bool
If returns locals is True, returns (objective, locals())
Note that this means adding / removing / changing the value of
local variables is an interface change.
In particular, TorontoSparsity depends on "terms" and "H_hat"
kwargs : optional keyword arguments for FixedVarDescr
"""
self.get_data_specs(model)[0].validate(data)
if self.supervised:
(X, Y) = data
else:
X = data
Y = None
H_hat = model.mf(X, Y=Y)
terms = []
hidden_layers = model.hidden_layers
# if self.supervised:
# hidden_layers = hidden_layers[:-1]
for layer, mf_state, targets, coeffs in \
safe_zip(hidden_layers, H_hat, self.targets, self.coeffs):
try:
cost = layer.get_l2_act_cost(mf_state, targets, coeffs)
except NotImplementedError:
if isinstance(coeffs, float) and coeffs == 0.:
cost = 0.
else:
raise
terms.append(cost)
objective = sum(terms)
if return_locals:
return objective, locals()
return objective
def fix(l):
"""
Turns (lists of) strings into (lists of) floats.
Parameters
----------
l : object
Returns
-------
l : object
If `l` is anything but a string, the return is the
same as the input, but it may have been modified in place.
If `l` is a string, the return value is `l` converted to a float.
If `l` is a list, this function explores all nested lists inside
`l` and turns all string members into floats.
"""
if isinstance(l, list):
return [fix(elem) for elem in l]
if isinstance(l, str):
return float(l)
return l
class TorontoSparsity(Cost):
"""
A somewhat strange sparsity penalty borrowed from Ruslan
Salakhutdinov's MATLAB MNIST DBM demo.
It's an activation penalty using mean squared error on
the activations, except to backprop from the activations
to the parameters we pretend the model was partially linear.
TODO: add link to Ruslan Salakhutdinov's paper that this is based on
Parameters
----------
targets : list