-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathcrbm.py
1899 lines (1458 loc) · 62.1 KB
/
crbm.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 cPickle as pkl
import pdb
import datetime
import time
import numpy as np
import pylab as pl
import scipy.stats
import scipy.special
from scipy.special import gamma
from scipy.misc import factorial
import gnumpy as gp
import data_helper
class RBM(object):
'''
Restricted Boltzmann Machine (RBM) using numpy
'''
def __init__(self, params={}):
'''
RBM constructor. Defines the parameters of the model along with
basic operations for inferring hidden from visible (and vice-versa),
as well as for performing CD updates.
input:
-----------------
Nv: number of visible units
Nh: number of hidden units
vis_unit: type of visible unit {'binary','linear'}
('linear' = rectified linear unit)
vis_scale: maximum output value for linear visible units
(average std_dev is ~= 1 at this scale,
so pre-scale training data with this in mind)
bv: visible bias
other params:
-----------------
W: weight between current hidden and visible units (undirected)
[Nv x Nh]
bh: hidden bias
'''
dtype = 'float32'
Nv = params['Nv']
Nh = params['Nh']
vis_unit = params.get('vis_unit','binary')
vis_scale = params.get('vis_scale')
bv = params.get('bv')
Th = params.get('Th',0)
if vis_unit not in ['binary','linear']:
raise ValueError, 'Unknown visible unit type %s' % vis_unit
if vis_unit == 'linear':
if vis_scale is None:
raise ValueError, 'Must set vis_scale for linear visible units'
elif vis_unit == 'binary':
vis_scale = 1.
# W is initialized with `initial_W` which is uniformly sampled
# from -4.*sqrt(6./(Nv+Nh)) and 4.*sqrt(6./(Nh+Nv))
# the output of uniform if converted using asarray to dtype
W = np.asarray( np.random.uniform(
low = -4*np.sqrt(6./(Nv+Nh)),
high = 4*np.sqrt(6./(Nv+Nh)),
size = (Nv, Nh)),
dtype = dtype)
W = gp.garray(W)
bh = gp.zeros(Nh)
if bv is None :
bv = gp.zeros(Nv)
else:
bv = gp.garray(bv)
# params -------------------------------------------
self.dtype = 'float32'
self.Nv = Nv # num visible units
self.Nh = Nh # num hidden units
self.Th = Th # used for framing input
self.vis_unit = vis_unit # type of visible output unit
self.vis_scale = vis_scale # scale of linear output units
self.W = W # vis<->hid weights
self.bv = bv # vis bias
self.bh = bh # hid bias
self.W_update = gp.zeros((Nv,Nh))
self.bh_update = gp.zeros((Nh,))
self.bv_update = gp.zeros((Nv,))
self.params = [ 'dtype',
'vis_unit','vis_scale',
'Nv','Nh',
'W','bh','bv']
def save_params(self,filename=None):
'''
save parameters to file
'''
if filename is None:
fileid = np.random.randint(100000)
filename = 'RBM_%u.pkl' % fileid
params_out = {}
for p in self.params:
val = vars(self)[p]
if type(val) is gp.garray:
params_out[p] = val.as_numpy_array()
else:
params_out[p] = val
fp = open(filename,'wb')
pkl.dump(params_out,fp,protocol=-1)
fp.close()
print 'saved %s' % filename
def load_params(self,filename):
'''
load parameters from file
'''
fp = open(filename,'rb')
params_in = pkl.load(fp)
fp.close()
for key,value in params_in.iteritems():
vars(self)[key] = value
Nv,Nh = self.Nv,self.Nh
dtype = self.dtype
self.W_update = gp.zeros((Nv,Nh))
self.bh_update = gp.zeros((Nh,))
self.bv_update = gp.zeros((Nv,))
self.W = gp.garray(self.W)
self.bh = gp.garray(self.bh)
self.bv = gp.garray(self.bv)
def return_params(self):
'''
return a formatted string containing scalar parameters
'''
output = 'Nv=%u, Nh=%u, vis_unit=%s, vis_scale=%0.2f' \
% (self.Nv,self.Nh,self.vis_unit,self.vis_scale)
return output
def mean_field_h_given_v(self,v):
'''
compute mean-field reconstruction of P(h=1|v)
'''
prob = sigmoid(self.bh + gp.dot(v, self.W))
return prob
def mean_field_v_given_h(self,h):
'''
compute mean-field reconstruction of P(v|h)
'''
x = self.bv + gp.dot(h, self.W.T)
if self.vis_unit == 'binary':
return sigmoid(x)
elif self.vis_unit == 'linear':
return log_1_plus_exp(x) - log_1_plus_exp(x-self.vis_scale)
return prob
def sample_h_given_v(self,v):
'''
compute samples from P(h|v)
'''
prob = self.mean_field_h_given_v(v)
samples = prob.rand() < prob
return samples, prob
def sample_v_given_h(self,h):
'''
compute samples from P(v|h)
'''
if self.vis_unit == 'binary':
mean = self.mean_field_v_given_h(h)
samples = mean.rand() < mean
return samples, mean
elif self.vis_unit == 'linear':
x = self.bv + gp.dot(h, self.W.T)
# variance of noise is sigmoid(x) - sigmoid(x - vis_scale)
stddev = gp.sqrt(sigmoid(x) - sigmoid(x - self.vis_scale))
mean = log_1_plus_exp(x) - log_1_plus_exp(x-self.vis_scale)
noise = stddev * gp.randn(x.shape)
samples = mean + noise
samples[samples < 0] = 0
samples[samples > self.vis_scale] = self.vis_scale
return samples, mean
def cdk(self,K,v0_data,rate=0.001,momentum=0.0,weight_decay=0.001,noisy=0):
'''
compute K-step contrastive divergence update
input:
K - number of gibbs iterations (for cd-K)
v0_data - training data [N x (Nv+Nl)]
rate - learning rate
momentum - learning momentum
weight_decay - L2 regularizer
noisy - 0 = use h0_mean, use visible means everywhere
1 = use h0_samp, use visible means everywhere
2 = use samples everywhere
'''
# collect gradient statistics
h0_samp,h0_mean = self.sample_h_given_v(v0_data)
hk_samp = h0_samp
if noisy == 0:
for k in xrange(K): # vk_mean <--> hk_samp
vk_mean = self.mean_field_v_given_h(hk_samp)
hk_samp, hk_mean = self.sample_h_given_v(vk_mean)
h0 = h0_mean
vk = vk_mean
hk = hk_mean
elif noisy == 1:
for k in xrange(K): # vk_mean <--> hk_samp
vk_mean = self.mean_field_v_given_h(hk_samp)
hk_samp, hk_mean = self.sample_h_given_v(vk_mean)
h0 = h0_samp # <--
vk = vk_mean
hk = hk_mean
elif noisy == 2:
for k in xrange(K): # vk_samp <--> hk_samp
vk_samp, vk_mean = self.sample_v_given_h(hk_samp)
hk_samp, hk_mean = self.sample_h_given_v(vk_samp)
h0 = h0_samp
vk = vk_samp # <--
hk = hk_samp # <--
W_grad,bv_grad,bh_grad = self.compute_gradients(v0_data,h0,vk,hk)
if weight_decay > 0.0:
W_grad += weight_decay * self.W
rate = float(rate)
if momentum > 0.0:
momentum = float(momentum)
self.W_update = momentum * self.W_update - rate*W_grad
self.bh_update = momentum * self.bh_update - rate*bh_grad
self.bv_update = momentum * self.bv_update - rate*bv_grad
else:
self.W_update = -rate*W_grad
self.bh_update = -rate*bh_grad
self.bv_update = -rate*bv_grad
self.W = self.W + self.W_update
self.bh = self.bh + self.bh_update
self.bv = self.bv + self.bv_update
def compute_gradients(self,v0,h0,vk,hk):
N = v0.shape[0]
N_inv = 1./N
W_grad = N_inv * (gp.dot(vk.T, hk) - gp.dot(v0.T, h0))
bv_grad = gp.mean(vk - v0,axis=0)
bh_grad = gp.mean(hk - h0,axis=0)
return W_grad,bv_grad,bh_grad
def gibbs_samples(self,K,v0_data,noisy=0):
'''
compute a visible unit sample using Gibbs sampling
input:
K - number of complete Gibbs iterations
v_input - seed value of visible units
noisy - 0 = always use visible means and use hidden means to drive final sample
1 = drive final sample with final hidden sample
2 = use visible means for updates but use visible and hidden samples for final update
3 = always use samples for both visible and hidden updates
note: hidden samples are always used to drive visible reconstructions unless noted otherwise
'''
Nv = self.Nv
h0_samp,h0_mean = self.sample_h_given_v(v0_data)
hk_samp = h0_samp
hk_mean = h0_mean
if noisy < 3:
for k in xrange(K-1): # hk_samp <--> vk_mean
vk_mean = self.mean_field_v_given_h(hk_samp)
hk_samp, hk_mean = self.sample_h_given_v(vk_mean)
else:
for k in xrange(K-1): # hk_samp <--> vk_samp
vk_samp, vk_mean = self.sample_v_given_h(hk_samp)
hk_samp, hk_mean = self.sample_h_given_v(vk_samp)
if noisy == 0: # hk_mean --> v_mean
v_mean = self.mean_field_v_given_h(hk_mean)
return v_mean
elif noisy == 1: # hk_samp --> v_mean
v_mean = self.mean_field_v_given_h(hk_samp)
return v_mean
elif noisy > 1: # hk_samp --> v_samp
v_samp, v_mean = self.sample_v_given_h(hk_samp)
return v_samp
def recon_error(self, v0_data,K=1,print_output=False):
'''
compute K-step reconstruction error
'''
vk_mean = self.gibbs_samples(K,v0_data,noisy=0)
recon_error = gp.mean(gp.abs(v0_data - vk_mean))
if print_output:
output = '%30s %6.5f' % ('vis error:', recon_error/self.vis_scale)
print output
return output
else:
return recon_error
def update_stats(self):
W_stats = [gp.min(self.W),gp.mean(gp.abs(self.W)),gp.max(self.W)]
bh_stats = [gp.min(self.bh),gp.mean(gp.abs(self.bh)),gp.max(self.bh)]
bv_stats = [gp.min(self.bv),gp.mean(gp.abs(self.bv)),gp.max(self.bv)]
W_update_stats = [gp.min(self.W_update), gp.mean(gp.abs(self.W_update)), gp.max(self.W_update)]
bh_update_stats = [gp.min(self.bh_update), gp.mean(gp.abs(self.bh_update)), gp.max(self.bh_update)]
bv_update_stats = [gp.min(self.bv_update), gp.mean(gp.abs(self.bv_update)), gp.max(self.bv_update)]
param_stats = dict(W=W_stats,bh=bh_stats,bv=bv_stats)
update_stats = dict(W=W_update_stats,
bh=bh_update_stats,bv=bv_update_stats)
return [param_stats, update_stats]
class LRBM(RBM):
'''
Labeled Restricted Boltzmann Machine
'''
def __init__(self, params={}):
'''
input:
-----------------
(in addition to those defined in RBM class)
Nl: number of label units (group of softmax units)
'''
dtype = 'float32'
super(LRBM,self).__init__(params)
bv = params.get('bv')
Nl = params['Nl']
Nv = self.Nv
Nh = self.Nh
# add label units to visible units
# W is initialized with uniformly sampled data
# from -4.*sqrt(6./(Nv+Nh)) and 4.*sqrt(6./(Nh+Nv))
W = np.asarray( np.random.uniform(
low = -4*np.sqrt(6./(Nv+Nl+Nh)),
high = 4*np.sqrt(6./(Nv+Nl+Nh)),
size = (Nv+Nl, Nh)),
dtype = dtype)
W = gp.garray(W)
if bv is None :
bv = gp.zeros((Nv+Nl))
else:
bv = gp.garray(bv)
# new label-unit params -------------------------------------------
self.Nl = Nl # num label units
self.W = W # (vis+lab)<->hid weights
self.bv = bv # vis bias
self.W_update = gp.zeros((Nv+Nl,Nh))
self.bv_update = gp.zeros((Nv+Nl,))
self.params += ['Nl']
def load_params(self,filename):
'''load parameters from file'''
super(LRBM,self).load_params(filename)
Nv,Nh,Nl,= self.Nv,self.Nh,self.Nl
dtype = self.dtype
self.W_update = gp.zeros((Nv+Nl,Nh))
self.bv_update = gp.zeros((Nv+Nl,))
def save_params(self,filename=None):
'''save parameters to file'''
if filename is None:
fileid = np.random.randint(100000)
filename = 'LRBM_%u.pkl' % fileid
super(LRBM,self).save_params(filename)
def return_params(self):
'''
return a formatted string containing scalar parameters
'''
output = super(LRBM,self).return_params()
output = 'Nl=%u, ' % (self.Nl) + output
return output
def separate_vis_lab(self,x,axis=1):
'''
separate visible unit data from label unit data
'''
Nl = self.Nl
if x.ndim == 1:
axis = 0
if axis == 0:
x_lab = x[-Nl:]
x_vis = x[:-Nl]
elif axis == 1:
x_lab = x[:,-Nl:]
x_vis = x[:,:-Nl]
return x_vis, x_lab
def join_vis_lab(self,x_vis,x_lab,axis=1):
'''
join visible unit data to label unit data
'''
if x_vis.ndim == 1:
axis = 0
x = gp.concatenate((x_vis,x_lab),axis=axis)
return x
def mean_field_v_given_h(self,h):
'''compute mean-field reconstruction of P(v|h)'''
x = self.bv + gp.dot(h, self.W.T)
x_vis, x_lab = self.separate_vis_lab(x)
lab_mean = softmax(x_lab)
if self.vis_unit == 'binary':
vis_mean = sigmoid(x_vis)
elif self.vis_unit == 'linear':
vis_mean = log_1_plus_exp(x_vis) - log_1_plus_exp(x_vis-self.vis_scale)
means = self.join_vis_lab(vis_mean,lab_mean)
return means
def sample_v_given_h(self,h):
'''compute samples from P(v|h)'''
if self.vis_unit == 'binary':
means = self.mean_field_v_given_h(h)
vis_mean,lab_mean = self.separate_vis_lab(means)
vis_samp = vis_mean.rand() < vis_mean
elif self.vis_unit == 'linear':
x = self.bv + gp.dot(h, self.W.T)
x_vis,x_lab = self.separate_vis_lab(x)
# variance of noise is sigmoid(x_vis) - sigmoid(x_vis - vis_scale)
vis_stddev = gp.sqrt(sigmoid(x_vis) - sigmoid(x_vis - self.vis_scale))
vis_mean = log_1_plus_exp(x_vis) - log_1_plus_exp(x_vis-self.vis_scale)
vis_noise = stddev * gp.random.standard_normal(size=x.shape)
vis_samp = vis_mean + vis_noise
vis_samp[vis_samp < 0] = 0
vis_samp[vis_samp > self.vis_scale] = self.vis_scale
lab_mean = softmax(x_lab)
means = self.join_vis_lab(vis_mean,lab_mean)
lab_samp = sample_categorical(lab_mean)
samples = self.join_vis_lab(vis_samp,lab_samp)
return samples, means
def label_probabilities(self,v_input,output_h=False):
'''
compute the activation probability of each label unit given the visible units
'''
#compute free energy for each label configuration
# F(v,c) = -sum(v*bv) - bl[c] - sum(log(1 + exp(z_c)))
# where z_c = bh + dot(v,W) + r[c] (r[c] are the weights for label c)
# also, v_input = [v,l], where l are binary "one-hot" labels
b_hid = self.bh
b_vis, b_lab = self.separate_vis_lab(self.bv)
v_vis, v_lab = self.separate_vis_lab(v_input)
W_vis,W_lab = self.separate_vis_lab(self.W,axis=0)
# the b_vis term cancels out in the softmax
#F = -np.sum(v_vis*b_vis,axis=1)
#F = F.reshape((-1,1)) - b_lab
F = - b_lab
z = b_hid + gp.dot(v_vis,W_vis)
z = z.reshape(z.shape + (1,))
z = z + W_lab.T.reshape((1,) + W_lab.T.shape)
hidden_terms = -gp.sum(log_1_plus_exp(z), axis=1)
F = F + hidden_terms
pr = softmax(-F)
# compute hidden probs for each label configuration
# this is used in the discriminative updates
if output_h:
h = sigmoid(z)
return pr, h
else:
return pr
def discriminative_train(self,v_input,rate=0.001,momentum=0.0,weight_decay=0.001):
'''
Update weights using discriminative updates.
These updates use gradient ascent of the log-likelihood of the
label probability of the correct label
input:
v_input - [v_past, v_visible, v_labels]
(v_labels contains the binary activation of the correct label)
'''
N = v_input.shape[0]
# things to compute:
# h_d - hidden unit activations for each label configuration
# p_d - label unit probabilities
p_d, h_d = self.label_probabilities(v_input,output_h=True)
v_vis,v_lab = self.separate_vis_lab(v_input)
ind, true_labs = gp.where(v_lab == 1)
#scale = float(rate / N)
N_inv = 1./N
# prob_scale = (1-p_d) for correct label and -p_d for other labels
prob_scale = -p_d
prob_scale[ind,true_labs] += 1
ps_broad = prob_scale.reshape((N,1,self.Nl)) # make broadcastable across h_d
p_h_sum = gp.sum(ps_broad * h_d, axis=2)
# compute gradients ----------------------------------------------
# W = [w,r]
w_grad = gp.dot(v_vis.T, p_h_sum) # vis<-->hid
r_grad = gp.sum( ps_broad * h_d, axis=0 ).T # lab<-->hid
W_grad = N_inv * self.join_vis_lab(w_grad,r_grad,axis=0)# [vis,lab]<-->hid
bh_grad = gp.mean(p_h_sum,axis=0) # -->hid
# bv = [bvv,bvl] # -->[vis,lab]
bvv,bvl = self.separate_vis_lab(self.bv)
bvv_grad = gp.zeros(bvv.shape) # -->vis
bvl_grad = gp.mean(prob_scale,axis=0) # -->lab
# ---------------------------------------------------------------
if weight_decay > 0.0:
W_grad += -weight_decay * self.W
#Wv_grad = self.join_vis_lab(Wvv_grad,Wvl_grad)
bv_grad = self.join_vis_lab(bvv_grad,bvl_grad)
rate = float(rate)
if momentum > 0.0:
momentum = float(momentum)
self.W_update = momentum * self.W_update + rate*W_grad
self.bh_update = momentum * self.bh_update + rate*bh_grad
self.bv_update = momentum * self.bv_update + rate*bv_grad
else:
self.W_update = rate*W_grad
self.bh_update = rate*bh_grad
self.bv_update = rate*bv_grad
self.W += self.W_update
self.bh += self.bh_update
self.bv += self.bv_update
def recon_error(self,v0_data,K=1,print_output=False):
'''compute K-step reconstruction error'''
vk_mean = self.gibbs_samples(K,v0_data,noisy=0)
v0_vis,v0_lab = self.separate_vis_lab(v0_data)
vk_vis,vk_lab = self.separate_vis_lab(vk_mean)
vis_error = gp.mean(gp.abs(v0_vis - vk_vis))
lab_error = gp.mean(gp.abs(v0_lab - vk_lab))
lab_probs = self.label_probabilities(v0_data)
#pred_labs = gargmax(lab_probs)
pred_labs = lab_probs.argmax(axis=1)
ind, true_labs = gp.where(v0_lab == 1)
percent_correct = gp.mean(pred_labs == true_labs)
cross_entropy = -gp.mean(gp.log(lab_probs[ind,true_labs]))
#prob_error = gp.mean(gp.abs(1. - lab_probs[ind,true_labs]))
if print_output:
output = '%30s %6.5f' % ('vis error:', vis_error/self.vis_scale) + '\n'
output += '%30s %6.5f' % ('lab error:', lab_error) + '\n'
#output += '%30s %6.5f' % ('prob error:', prob_error) + '\n'
output += '%30s %6.5f' % ('cross entropy:', cross_entropy) + '\n'
output += '%30s %6.5f' % ('class correct:', percent_correct)
print output
return output
else:
return percent_correct, cross_entropy, lab_error, vis_error/self.vis_scale
class CRBM(object):
'''Conditional Restricted Boltzmann Machine (CRBM) using gnumpy '''
def __init__(self, params={}):
'''
RBM constructor. Defines the parameters of the model along with
basic operations for inferring hidden from visible (and vice-versa),
as well as for performing CD updates.
input:
-----------------
Nv: number of visible units
Nh: number of hidden units
Tv: order of autoregressive weights (RBM has Tv=0)
(how far into the past do they go?)
Th: order of past visible to current hidden weights (RBM has Th=0)
(how far into the past do they go?)
period: natural repetition period of data [default=Tv]
(for initializing generative gibbs sampling)
vis_unit: type of visible unit {'binary','linear'}
('linear' = rectified linear unit)
vis_scale: maximum output value for linear visible units
(average std_dev is ~= 1 at this scale,
so pre-scale training data with this in mind)
bv: visible bias
Wv_scale - how much to rescale Wv updates
other params:
--------------------
W: weight between current hidden and visible units (undirected)
[Nv x Nh]
Wh: past visible to current hidden weights (directed)
[Tv*Nv x Nh]
Wv: past visible to current visible weights (directed)
[Tv*Nv x Nv]
bh: hidden bias
'''
dtype = 'float32'
Nv = params['Nv']
Nh = params['Nh']
Tv = params['Tv']
Th = params['Th']
T = max(Tv,Th)
period = params.get('period',T)
vis_unit = params.get('vis_unit','binary')
vis_scale = params.get('vis_scale')
bv = params.get('bv')
Wv_scale = params.get('Wv_scale',0.01)
if vis_unit not in ['binary','linear']:
raise ValueError, 'Unknown visible unit type %s' % vis_unit
if vis_unit == 'linear':
if vis_scale is None:
raise ValueError, 'Must set vis_scale for linear visible units'
elif vis_unit == 'binary':
vis_scale = 1.
if period is None:
period = T
else:
if period > T:
raise ValueError, 'period must be <= max(Tv,Th)'
# W is initialized with `initial_W` which is uniformly sampled
# from -4.*sqrt(6./(Nv+Nh)) and 4.*sqrt(6./(Nh+Nv))
# the output of uniform if converted using asarray to dtype
W = np.asarray( np.random.uniform(
low = -4*np.sqrt(6./(Nv+Nh)),
high = 4*np.sqrt(6./(Nv+Nh)),
size = (Nv, Nh)),
dtype = dtype)
W = gp.garray(W)
Wv = np.asarray( np.random.uniform(
low = -4*np.sqrt(6./(Nv*Tv+Nv)),
high = 4*np.sqrt(6./(Nv*Tv+Nv)),
size = (Nv*Tv, Nv)),
dtype = dtype)
Wv = gp.garray(Wv)
Wh = np.asarray( np.random.uniform(
low = -4*np.sqrt(6./(Nv*Th+Nh)),
high = 4*np.sqrt(6./(Nv*Th+Nh)),
size = (Nv*Th, Nh)),
dtype = dtype)
Wh = gp.garray(Wh)
bh = gp.zeros(Nh)
if bv is None :
bv = gp.zeros(Nv)
else:
bv = gp.garray(bv)
# params -------------------------------------------
self.dtype = 'float32'
self.Nv = Nv # num visible units
self.Nh = Nh # num hidden units
self.Tv = Tv # num vis->vis delay taps
self.Th = Th # num vis->hid delay taps
self.T = T # max(Tv,Th)
self.period = period # typical repetition period of sequences
self.vis_unit = vis_unit # type of visible output unit
self.vis_scale = vis_scale # scale of linear output units
self.W = W # vis<->hid weights
self.Wv = Wv # vis->vis delay weights
self.Wh = Wh # vis->hid delay weights
self.bv = bv # vis bias
self.bh = bh # hid bias
self.Wv_scale = Wv_scale # rescale Wv updates
self.W_update = gp.zeros((Nv,Nh))
self.Wv_update = gp.zeros((Nv*Tv,Nv))
self.Wh_update = gp.zeros((Nv*Th,Nh))
self.bh_update = gp.zeros((Nh,))
self.bv_update = gp.zeros((Nv,))
self.params = [ 'dtype',
'period','vis_unit','vis_scale',
'Nv','Nh','Tv','Th','T',
'W','Wv','Wh','bh','bv']
def save_params(self,filename=None):
'''save parameters to file'''
if filename is None:
id = np.random.randint(100000)
filename = 'CRBM_%u.pkl' % id
params_out = {}
for p in self.params:
val = vars(self)[p]
if type(val) is gp.garray:
params_out[p] = val.as_numpy_array()
else:
params_out[p] = val
fp = open(filename,'wb')
pkl.dump(params_out,fp,protocol=-1)
fp.close()
print 'saved %s' % filename
def load_params(self,filename):
'''load parameters from file'''
fp = open(filename,'rb')
params_in = pkl.load(fp)
fp.close()
for key,value in params_in.iteritems():
vars(self)[key] = value
Nv,Nh,Tv,Th = self.Nv,self.Nh,self.Tv,self.Th
dtype = self.dtype
self.W_update = gp.zeros((Nv,Nh))
self.Wv_update = gp.zeros((Nv*Tv,Nv))
self.Wh_update = gp.zeros((Nv*Th,Nh))
self.bh_update = gp.zeros((Nh,))
self.bv_update = gp.zeros((Nv,))
self.W = gp.garray(self.W)
self.Wv = gp.garray(self.Wv)
self.Wh = gp.garray(self.Wh)
self.bh = gp.garray(self.bh)
self.bv = gp.garray(self.bv)
def return_params(self):
'''
return a formatted string containing scalar parameters
'''
output = 'Nv=%u, Nh=%u, vis_unit=%s, vis_scale=%0.2f, Tv=%u, Th=%u, Wv_scale=%g' \
% (self.Nv,self.Nh,self.vis_unit,self.vis_scale,self.Tv,self.Th,self.Wv_scale)
return output
def extract_data(self,v_input):
Nv = self.Nv
Tv = self.Tv
Th = self.Th
if v_input.ndim == 1:
v_data = v_input[-Nv:]
vv_past = v_input[-Nv*(1+Tv):-Nv]
vh_past = v_input[-Nv*(1+Th):-Nv]
else:
v_data = v_input[:,-Nv:]
vv_past = v_input[:,-Nv*(1+Tv):-Nv]
vh_past = v_input[:,-Nv*(1+Th):-Nv]
return v_data, vv_past, vh_past
def mean_field_h_given_v(self,v,h_bias):
'''compute mean-field reconstruction of P(ht=1|vt,v<t)'''
prob = sigmoid(h_bias + gp.dot(v, self.W))
return prob
def mean_field_h_given_v_frame(self,v_input):
'''
compute mean-field reconstruction of P(ht=1|vt,v<t)
and compute h_bias from data
input:
v_frames - contains [v_past, v_curr] in a matrix
'''
v,vv_past,vh_past = self.extract_data(v_input)
h_bias = self.bh + gp.dot(vh_past,self.Wh)
return sigmoid(h_bias + gp.dot(v, self.W))
def mean_field_v_given_h(self,h,v_bias):
'''compute mean-field reconstruction of P(vt|ht,v<t)'''
x = v_bias + gp.dot(h, self.W.T)
if self.vis_unit == 'binary':
return sigmoid(x)
elif self.vis_unit == 'linear':
return log_1_plus_exp(x) - log_1_plus_exp(x-self.vis_scale)
return prob
def sample_h_given_v(self,v,h_bias):
'''compute samples from P(ht=1|vt,v<t)'''
prob = self.mean_field_h_given_v(v,h_bias)
samples = prob.rand() < prob
return samples, prob
def sample_v_given_h(self,h,v_bias):
'''compute samples from P(vt|ht,v<t)'''
if self.vis_unit == 'binary':
mean = self.mean_field_v_given_h(h,v_bias)
samples = mean.rand() < mean
return samples, mean
elif self.vis_unit == 'linear':
x = v_bias + gp.dot(h, self.W.T)
# variance of noise is sigmoid(x) - sigmoid(x - vis_scale)
stddev = gp.sqrt(sigmoid(x) - sigmoid(x - self.vis_scale))
mean = log_1_plus_exp(x) - log_1_plus_exp(x-self.vis_scale)
noise = stddev * gp.randn(x.shape)
samples = mean + noise
samples *= samples > 0
samples_over = samples - self.vis_scale
samples_over *= samples_over > 0
samples_over -= samples_over
return samples, mean
def cdk(self,K,v_input,rate=0.001,momentum=0.0,weight_decay=0.001,noisy=0):
'''
compute K-step contrastive divergence update
input:
K - number of gibbs iterations (for cd-K)
v_input - contains [v_past, v0_data] = [(N x Nv*max(Tv,Th)), (N x Nv)]
rate - learning rate
momentum - learning momentum
weight_decay - L2 regularizer
noisy - 0 = use hidden samples, but means as final values
1 = use visible and hidden samples, but means as final values
2 = use visible and hidden samples, samples for final hidden values, means for final visibles
3 = use samples everywhere.
'''
# compute gradient statistics
v0_data,vv_past,vh_past = self.extract_data(v_input)
v_bias,h_bias = self.compute_dynamic_bias(v_input)
h0_samp,h0_mean = self.sample_h_given_v(v0_data,h_bias)
hk_samp = h0_samp
if noisy == 0:
for k in xrange(K): # vk_mean <--> hk_samp
vk_mean = self.mean_field_v_given_h(hk_samp,v_bias)
hk_samp, hk_mean = self.sample_h_given_v(vk_mean,h_bias)
h0 = h0_mean
vk = vk_mean
hk = hk_mean
elif noisy == 1:
for k in xrange(K): # vk_mean <--> hk_samp
vk_samp, vk_mean = self.sample_v_given_h(hk_samp,v_bias)
hk_samp, hk_mean = self.sample_h_given_v(vk_samp,h_bias)
h0 = h0_mean # <--
vk = vk_mean
hk = hk_mean
elif noisy == 2:
for k in xrange(K): # vk_samp <--> hk_samp
vk_samp, vk_mean = self.sample_v_given_h(hk_samp,v_bias)
hk_samp, hk_mean = self.sample_h_given_v(vk_samp,h_bias)
h0 = h0_samp
vk = vk_mean # <--
hk = hk_samp # <--
elif noisy == 3:
for k in xrange(K): # vk_samp <--> hk_samp
vk_samp, vk_mean = self.sample_v_given_h(hk_samp,v_bias)
hk_samp, hk_mean = self.sample_h_given_v(vk_samp,h_bias)
h0 = h0_samp
vk = vk_samp # <--
hk = hk_samp # <--
# compute gradients
W_grad,Wv_grad,Wh_grad,bv_grad,bh_grad = self.compute_gradients(v_input,h0,vk,hk)
if weight_decay > 0.0:
W_grad += weight_decay * self.W
Wv_grad += weight_decay * self.Wv
Wh_grad += weight_decay * self.Wh
rate = float(rate)
if momentum > 0.0:
momentum = float(momentum)
self.W_update = momentum * self.W_update - rate*W_grad
self.Wv_update = momentum * self.Wv_update - self.Wv_scale*rate*Wv_grad
self.Wh_update = momentum * self.Wh_update - rate*Wh_grad
self.bh_update = momentum * self.bh_update - rate*bh_grad
self.bv_update = momentum * self.bv_update - rate*bv_grad
else:
self.W_update = -rate*W_grad
self.Wv_update = -self.Wv_scale*rate*Wv_grad
self.Wh_update = -rate*Wh_grad
self.bh_update = -rate*bh_grad
self.bv_update = -rate*bv_grad