forked from SonjayaJetBrain/Super-Brocoli
-
Notifications
You must be signed in to change notification settings - Fork 1
/
cost_layers.py
1367 lines (1222 loc) · 54.7 KB
/
cost_layers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Cost layers.
TODO: write more documentation
"""
__docformat__ = 'restructedtext en'
__authors__ = ("Razvan Pascanu "
"KyungHyun Cho "
"Caglar Gulcehre ")
__contact__ = "Razvan Pascanu <r.pascanu@gmail>"
import numpy
import copy
import logging
import theano
import theano.tensor as TT
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
from groundhog import utils
from groundhog.utils import sample_weights, sample_weights_classic,\
init_bias, constant_shape, sample_zeros
from groundhog.layers.basic import Layer
logger = logging.getLogger(__name__)
class CostLayer(Layer):
"""
Base class for all cost layers
"""
def __init__(self, rng,
n_in,
n_out,
scale,
sparsity,
rank_n_approx=0,
rank_n_activ='lambda x: x',
weight_noise=False,
init_fn='sample_weights_classic',
bias_fn='init_bias',
bias_scale=0.,
sum_over_time=True,
additional_inputs=None,
grad_scale=1.,
use_nce=False,
name=None):
"""
:type rng: numpy random generator
:param rng: numpy random generator used to sample weights
:type n_in: int
:param n_in: number of input units
:type n_out: int
:param n_out: number of output units
:type scale: float or list of
:param scale: depending on the initialization function, it can be
the standard deviation of the Gaussian from which the weights
are sampled or the largest singular value. If a single value it
will be used for each layer, otherwise it has to have one value
for each layer
:type sparsity: int or list of
:param sparsity: if a single value, it will be used for each layer,
otherwise it has to be a list with as many values as layers. If
negative, it means the weight matrix is dense. Otherwise it
means this many randomly selected input units are connected to
an output unit
:type rank_n_approx: int
:param rank_n_approx: It applies to the first layer only. If
positive and larger than 0, the first weight matrix is
factorized into two matrices. The first one goes from input to
`rank_n_approx` hidden units, the second from `rank_n_approx` to
the number of units on the second layer
:type rank_n_activ: string or function
:param rank_n_activ: Function that is applied on on the intermediary
layer formed from factorizing the first weight matrix (Q: do we
need this?)
:type weight_noise: bool
:param weight_noise: If true, the model is used with weight noise
(and the right shared variable are constructed, to keep track
of the noise)
:type init_fn: string or function
:param init_fn: function used to initialize the weights of the
layer. We recommend using either `sample_weights_classic` or
`sample_weights` defined in the utils
:type bias_fn: string or function
:param bias_fn: function used to initialize the biases. We recommend
using `init_bias` defined in the utils
:type bias_scale: float
:param bias_scale: argument passed to `bias_fn`, depicting the scale
of the initial bias
:type sum_over_time: bool
:param sum_over_time: flag, stating if, when computing the cost, we
should take the sum over time, or the mean. If you have variable
length sequences, please take the sum over time
:type additional_inputs: None or list of ints
:param additional_inputs: dimensionality of each additional input
:type grad_scale: float or theano scalar
:param grad_scale: factor with which the gradients with respect to
the parameters of this layer are scaled. It is used for
differentiating between the different parameters of a model.
:type use_nce: bool
:param use_nce: flag, if true, do not use MLE, but NCE-like cost
:type name: string
:param name: name of the layer (used to name parameters). NB: in
this library names are very important because certain parts of the
code relies on name to disambiguate between variables, therefore
each layer should have a unique name.
"""
self.grad_scale = grad_scale
assert rank_n_approx >= 0, "Please enter a valid rank_n_approx"
self.rank_n_approx = rank_n_approx
if type(rank_n_activ) is str:
rank_n_activ = eval(rank_n_activ)
self.rank_n_activ = rank_n_activ
super(CostLayer, self).__init__(n_in, n_out, rng, name)
self.trng = RandomStreams(self.rng.randint(int(1e6)))
self.scale = scale
if isinstance(bias_fn, str):
self.bias_fn = eval(bias_fn)
else:
self.bias_fn = bias_fn
self.bias_scale = bias_scale
self.sum_over_time = sum_over_time
self.weight_noise = weight_noise
self.sparsity = sparsity
if self.sparsity < 0:
self.sparsity = n_out
if type(init_fn) is str:
init_fn = eval(init_fn)
self.init_fn = init_fn
self.additional_inputs = additional_inputs
self.use_nce = use_nce
self._init_params()
def _init_params(self):
"""
Initialize the parameters of the layer, either by using sparse
initialization or small isotropic noise.
"""
if self.rank_n_approx:
W_em1 = self.init_fn(self.n_in,
self.rank_n_approx,
self.sparsity,
self.scale,
self.rng)
W_em2 = self.init_fn(self.rank_n_approx,
self.n_out,
self.sparsity,
self.scale,
self.rng)
self.W_em1 = theano.shared(W_em1,
name='W1_%s' % self.name)
self.W_em2 = theano.shared(W_em2,
name='W2_%s' % self.name)
self.b_em = theano.shared(
self.bias_fn(self.n_out, self.bias_scale, self.rng),
name='b_%s' % self.name)
self.params += [self.W_em1, self.W_em2, self.b_em]
if self.weight_noise:
self.nW_em1 = theano.shared(W_em1*0.,
name='noise_W1_%s' % self.name)
self.nW_em2 = theano.shared(W_em*0.,
name='noise_W2_%s' % self.name)
self.nb_em = theano.shared(b_em*0.,
name='noise_b_%s' % self.name)
self.noise_params = [self.nW_em1, self.nW_em2, self.nb_em]
self.noise_params_shape_fn = [
constant_shape(x.get_value().shape)
for x in self.noise_params]
else:
W_em = self.init_fn(self.n_in,
self.n_out,
self.sparsity,
self.scale,
self.rng)
self.W_em = theano.shared(W_em,
name='W_%s' % self.name)
self.b_em = theano.shared(
self.bias_fn(self.n_out, self.bias_scale, self.rng),
name='b_%s' % self.name)
self.params += [self.W_em, self.b_em]
if self.weight_noise:
self.nW_em = theano.shared(W_em*0.,
name='noise_W_%s' % self.name)
self.nb_em = theano.shared(
numpy.zeros((self.n_out,), dtype=theano.config.floatX),
name='noise_b_%s' % self.name)
self.noise_params = [self.nW_em, self.nb_em]
self.noise_params_shape_fn = [
constant_shape(x.get_value().shape)
for x in self.noise_params]
self.additional_weights = []
self.noise_additional_weights = []
if self.additional_inputs:
for pos, size in enumerate(self.additional_inputs):
W_add = self.init_fn(size,
self.n_out,
self.sparsity,
self.scale,
self.rng)
self.additional_weights += [theano.shared(W_add,
name='W_add%d_%s'%(pos, self.name))]
if self.weight_noise:
self.noise_additional_weights += [
theano.shared(W_add*0.,
name='noise_W_add%d_%s'%(pos, self.name))]
self.params = self.params + self.additional_weights
self.noise_params += self.noise_additional_weights
self.noise_params_shape_fn += [
constant_shape(x.get_value().shape)
for x in self.noise_additional_weights]
self.params_grad_scale = [self.grad_scale for x in self.params]
def compute_sample(self, state_below, temp=1, use_noise=False):
"""
Constructs the theano expression that samples from the output layer.
:type state_below: tensor or layer
:param state_below: The theano expression (or groundhog layer)
representing the input of the cost layer
:type temp: float or tensor scalar
:param temp: scalar representing the temperature that should be used
when sampling from the output distribution
:type use_noise: bool
:param use_noise: flag. If true, noise is used when computing the
output of the model
"""
raise NotImplemented
def get_cost(self,
state_below,
target=None,
mask=None,
temp=1,
reg=None,
scale=None,
sum_over_time=None,
use_noise=True,
additional_inputs=None,
no_noise_bias=False):
"""
Computes the expression of the cost of the model (given the type of
layer used).
:type state_below: tensor or layer
:param state_below: The theano expression (or groundhog layer)
representing the input of the cost layer
:type target: tensor or layer
:param target: The theano expression (or groundhog layer)
representing the target (used to evaluate the prediction of the
output layer)
:type mask: None or mask or layer
:param mask: Mask, depicting which of the predictions should be
ignored (e.g. due to them resulting from padding a sequence
with 0s)
:type temp: float or tensor scalar
:param temp: scalar representing the temperature that should be used
when sampling from the output distribution
:type reg: None or layer or theano scalar expression
:param reg: additional regularization term that should be added to
the cost
:type scale: float or None or theano scalar
:param scale: scaling factor with which the cost is multiplied
:type sum_over_time: bool or None
:param sum_over_time: this flag overwrites the value given to this
property in the constructor of the class
:type use_noise: bool
:param use_noise: flag. If true, noise is used when computing the
output of the model
:type additional_inputs: list theano variable or layers
:param additional_inputs: list of theano variables or layers
representing the additional inputs
:type no_noise_bias: bool
:param no_noise_bias: flag, stating if weight noise should be added
to the bias as well, or only to the weights
"""
raise NotImplemented
def get_grads(self,
state_below,
target=None,
mask=None,
temp=1,
reg=None,
scale=None,
additional_gradients=None,
sum_over_time=None,
use_noise=True,
additional_inputs=None,
no_noise_bias=False):
"""
Computes the expression of the gradients of the cost with respect to
all parameters of the model.
:type state_below: tensor or layer
:param state_below: The theano expression (or groundhog layer)
representing the input of the cost layer
:type target: tensor or layer
:param target: The theano expression (or groundhog layer)
representing the target (used to evaluate the prediction of the
output layer)
:type mask: None or mask or layer
:param mask: Mask, depicting which of the predictions should be
ignored (e.g. due to them resulting from padding a sequence
with 0s)
:type temp: float or tensor scalar
:param temp: scalar representing the temperature that should be used
when sampling from the output distribution
:type reg: None or layer or theano scalar expression
:param reg: additional regularization term that should be added to
the cost
:type scale: float or None or theano scalar
:param scale: scaling factor with which the cost is multiplied
:type additional_gradients: list of tuples of the form
(param, gradient)
:param additional_gradiens: A list of tuples. Each tuple has as its
first element the parameter, and as second element a gradient
expression that should be added to the gradient resulting from the
cost. Not all parameters need to have an additional gradient.
:type sum_over_time: bool or None
:param sum_over_time: this flag overwrites the value given to this
property in the constructor of the class
:type use_noise: bool
:param use_noise: flag. If true, noise is used when computing the
output of the model
:type no_noise_bias: bool
:param no_noise_bias: flag, stating if weight noise should be added
to the bias as well, or only to the weights
"""
cost = self.get_cost(state_below,
target,
mask=mask,
reg=reg,
scale=scale,
sum_over_time=sum_over_time,
use_noise=use_noise,
additional_inputs=additional_inputs,
no_noise_bias=no_noise_bias)
logger.debug("Get grads")
grads = TT.grad(cost.mean(), self.params)
logger.debug("Got grads")
if additional_gradients:
for p, gp in additional_gradients:
if p in self.params:
grads[self.params.index(p)] += gp
if self.additional_gradients:
for new_grads, to_replace, properties in self.additional_gradients:
gparams, params = new_grads
prop_expr = [x[1] for x in properties]
replace = [(x[0], TT.grad(cost, x[1])) for x in to_replace]
rval = theano.clone(gparams + prop_expr,
replace=replace)
gparams = rval[:len(gparams)]
prop_expr = rval[len(gparams):]
self.properties += [(x[0], y)
for x, y in zip(properties, prop_expr)]
for gp, p in zip(gparams, params):
grads[self.params.index(p)] += gp
self.cost = cost
self.grads = grads
return cost, grads
def _get_samples(self, model, length=30, temp=1, *inps):
"""
Sample a sequence from the model `model` whose output layer is given
by `self`.
:type model: groundhog model class
:param model: model that has `self` as its output layer
:type length: int
:param length: length of the sequence to sample
:type temp: float
:param temp: temperature to use during sampling
"""
raise NotImplemented
class LinearLayer(CostLayer):
"""
Linear output layer.
"""
def _init_params(self):
"""
Initialize the parameters of the layer, either by using sparse initialization or small
isotropic noise.
"""
if self.rank_n_approx:
W_em1 = self.init_fn(self.nin,
self.rank_n_approx,
self.sparsity,
self.scale,
self.rng)
W_em2 = self.init_fn(self.rank_n_approx,
self.nout,
self.sparsity,
self.scale,
self.rng)
self.W_em1 = theano.shared(W_em1,
name='W1_%s'%self.name)
self.W_em2 = theano.shared(W_em2,
name='W2_%s'%self.name)
self.b_em = theano.shared(
numpy.zeros((self.nout,), dtype=theano.config.floatX),
name='b_%s'%self.name)
self.params += [self.W_em1, self.W_em2, self.b_em]
self.myparams = []#[self.W_em1, self.W_em2, self.b_em]
if self.weight_noise:
self.nW_em1 = theano.shared(W_em1*0.,
name='noise_W1_%s'%self.name)
self.nW_em2 = theano.shared(W_em*0.,
name='noise_W2_%s'%self.name)
self.nb_em = theano.shared(b_em*0.,
name='noise_b_%s'%self.name)
self.noise_params = [self.nW_em1, self.nW_em2, self.nb_em]
self.noise_params_shape_fn = [
constant_shape(x.get_value().shape)
for x in self.noise_params]
else:
W_em = self.init_fn(self.nin,
self.nout,
self.sparsity,
self.scale,
self.rng)
self.W_em = theano.shared(W_em,
name='W_%s'%self.name)
self.b_em = theano.shared(
numpy.zeros((self.nout,), dtype=theano.config.floatX),
name='b_%s'%self.name)
self.add_wghs = []
self.n_add_wghs = []
if self.additional_inputs:
for pos, sz in enumerate(self.additional_inputs):
W_add = self.init_fn(sz,
self.nout,
self.sparsity,
self.scale,
self.rng)
self.add_wghs += [theano.shared(W_add,
name='W_add%d_%s'%(pos, self.name))]
if self.weight_noise:
self.n_add_wghs += [theano.shared(W_add*0.,
name='noise_W_add%d_%s'%(pos,
self.name))]
self.params += [self.W_em, self.b_em] + self.add_wghs
self.myparams = []#[self.W_em, self.b_em] + self.add_wghs
if self.weight_noise:
self.nW_em = theano.shared(W_em*0.,
name='noise_W_%s'%self.name)
self.nb_em = theano.shared(numpy.zeros((self.nout,),
dtype=theano.config.floatX),
name='noise_b_%s'%self.name)
self.noise_params = [self.nW_em, self.nb_em] + self.n_add_wghs
self.noise_params_shape_fn = [
constant_shape(x.get_value().shape)
for x in self.noise_params]
def _check_dtype(self, matrix, inp):
if 'int' in inp.dtype and inp.ndim==2:
return matrix[inp.flatten()]
elif 'int' in inp.dtype:
return matrix[inp]
elif 'float' in inp.dtype and inp.ndim == 3:
shape0 = inp.shape[0]
shape1 = inp.shape[1]
shape2 = inp.shape[2]
return TT.dot(inp.reshape((shape0*shape1, shape2)), matrix)
else:
return TT.dot(inp, matrix)
def fprop(self, state_below, temp = numpy.float32(1), use_noise=True,
additional_inputs = None):
"""
Constructs the computational graph of this layer.
"""
if self.rank_n_approx:
if use_noise and self.noise_params:
emb_val = self._check_dtype(self.W_em1+self.nW_em1,
state_below)
emb_val = TT.dot(self.W_em2 + self.nW_em2, emb_val)
else:
emb_val = self._check_dtype(self.W_em1, state_below)
emb_val = TT.dot(self.W_em2, emb_val)
else:
if use_noise and self.noise_params:
emb_val = self._check_dtype(self.W_em + self.nW_em, state_below)
else:
emb_val = self._check_dtype(self.W_em, state_below)
if additional_inputs:
for st, wgs in zip(additional_inputs, self.add_wghs):
emb_val += self._check_dtype(wgs, st)
if use_noise and self.noise_params:
emb_val = (emb_val + self.b_em+ self.nb_em)
else:
emb_val = (emb_val + self.b_em)
self.out = emb_val
self.state_below = state_below
self.model_output = emb_val
return emb_val
def get_cost(self, state_below, target=None, mask = None, temp=1,
reg = None, scale=None, sum_over_time=True, use_noise=True,
additional_inputs=None):
"""
This function computes the cost of this layer.
:param state_below: theano variable representing the input to the
softmax layer
:param target: theano variable representing the target for this
layer
:return: mean cross entropy
"""
class_probs = self.fprop(state_below, temp = temp,
use_noise=use_noise,
additional_inputs=additional_inputs)
pvals = class_probs
assert target, 'Computing the cost requires a target'
if target.ndim == 3:
target = target.reshape((target.shape[0]*target.shape[1],
target.shape[2]))
assert 'float' in target.dtype
cost = (class_probs - target)**2
if mask:
mask = mask.flatten()
cost = cost * TT.cast(mask, theano.config.floatX)
if sum_over_time is None:
sum_over_time = self.sum_over_time
if sum_over_time:
if state_below.ndim ==3:
sh0 = TT.cast(state_below.shape[0],
theano.config.floatX)
sh1 = TT.cast(state_below.shape[1],
theano.config.floatX)
self.cost = cost.sum()/sh1
else:
self.cost =cost.sum()
else:
self.cost = cost.mean()
if scale:
self.cost = self.cost*scale
if reg:
self.cost = self.cost + reg
self.out = self.cost
self.mask = mask
self.cost_scale = scale
return self.cost
def get_grads(self, state_below, target, mask = None, reg = None,
scale=None, sum_over_time=True, use_noise=True,
additional_inputs=None):
"""
This function implements both the forward and backwards pass of this
layer. The reason we do this in a single function is because for the
factorized softmax layer is hard to rely on grad and get an
optimized graph. For uniformity I've implemented this method for
this layer as well (though one doesn't need to use it)
:param state_below: theano variable representing the input to the
softmax layer
:param target: theano variable representing the target for this
layer
:return: cost, dC_dstate_below, param_grads, new_properties
dC_dstate_below is a computational graph representing the
gradient of the cost wrt to state_below
param_grads is a list containing the gradients wrt to the
different parameters of the layer
new_properties is a dictionary containing additional properties
of the model; properties are theano expression that are
evaluated and reported by the model
"""
cost = self.get_cost(state_below,
target,
mask = mask,
reg = reg,
scale=scale,
sum_over_time=sum_over_time,
use_noise=use_noise,
additional_inputs=additional_inputs)
grads = TT.grad(cost, self.params)
if self.additional_gradients:
for new_grads, to_replace, properties in self.additional_gradients:
gparams, params = new_grads
prop_expr = [x[1] for x in properties]
replace = [(x[0], TT.grad(cost, x[1])) for x in to_replace]
rval = theano.clone(gparams + prop_expr,
replace=replace)
gparams = rval[:len(gparams)]
prop_expr = rval[len(gparams):]
self.properties += [(x[0], y) for x,y in zip(properties,
prop_expr)]
for gp, p in zip(gparams, params):
grads[self.params.index(p)] += gp
self.cost = cost
self.grads = grads
def Gvs_fn(*args):
w = (1 - self.model_output) * self.model_output * state_below.shape[1]
Gvs = TT.Lop(self.model_output, self.params,
TT.Rop(self.model_output, self.params, args)/w)
return Gvs
self.Gvs = Gvs_fn
return cost, grads
class SigmoidLayer(CostLayer):
"""
Sigmoid output layer.
"""
def _get_samples(self, model, length=30, temp=1, *inps):
"""
See parent class.
"""
if not hasattr(model, 'word_indxs_src'):
model.word_indxs_src = model.word_indxs
character_level = False
if hasattr(model, 'character_level'):
character_level = model.character_level
if model.del_noise:
model.del_noise()
[values, probs] = model.sample_fn(length, temp, *inps)
# Assumes values matrix
#print 'Generated sample is:'
#print
if values.ndim > 1:
for d in xrange(2):
print '%d-th sentence' % d
print 'Input: ',
if character_level:
sen = []
for k in xrange(inps[0].shape[0]):
if model.word_indxs_src[inps[0][k][d]] == '<eol>':
break
sen.append(model.word_indxs_src[inps[0][k][d]])
print "".join(sen),
else:
for k in xrange(inps[0].shape[0]):
print model.word_indxs_src[inps[0][k][d]],
if model.word_indxs_src[inps[0][k][d]] == '<eol>':
break
print ''
print 'Output: ',
if character_level:
sen = []
for k in xrange(values.shape[0]):
if model.word_indxs[values[k][d]] == '<eol>':
break
sen.append(model.word_indxs[values[k][d]])
print "".join(sen),
else:
for k in xrange(values.shape[0]):
print model.word_indxs[values[k][d]],
if model.word_indxs[values[k][d]] == '<eol>':
break
print
print
else:
print 'Input: ',
if character_level:
sen = []
for k in xrange(inps[0].shape[0]):
if model.word_indxs_src[inps[0][k]] == '<eol>':
break
sen.append(model.word_indxs_src[inps[0][k]])
print "".join(sen),
else:
for k in xrange(inps[0].shape[0]):
print model.word_indxs_src[inps[0][k]],
if model.word_indxs_src[inps[0][k]] == '<eol>':
break
print ''
print 'Output: ',
if character_level:
sen = []
for k in xrange(values.shape[0]):
if model.word_indxs[values[k]] == '<eol>':
break
sen.append(model.word_indxs[values[k]])
print "".join(sen),
else:
for k in xrange(values.shape[0]):
print model.word_indxs[values[k]],
if model.word_indxs[values[k]] == '<eol>':
break
print
print
def fprop(self,
state_below,
temp=numpy.float32(1),
use_noise=True,
additional_inputs=None,
no_noise_bias=False):
"""
Forward pass through the cost layer.
:type state_below: tensor or layer
:param state_below: The theano expression (or groundhog layer)
representing the input of the cost layer
:type temp: float or tensor scalar
:param temp: scalar representing the temperature that should be used
when sampling from the output distribution
:type use_noise: bool
:param use_noise: flag. If true, noise is used when computing the
output of the model
:type no_noise_bias: bool
:param no_noise_bias: flag, stating if weight noise should be added
to the bias as well, or only to the weights
"""
if self.rank_n_approx:
if use_noise and self.noise_params:
emb_val = self.rank_n_activ(utils.dot(state_below,
self.W_em1+self.nW_em1))
emb_val = TT.dot(self.W_em2 + self.nW_em2, emb_val)
else:
emb_val = self.rank_n_activ(utils.dot(state_below, self.W_em1))
emb_val = TT.dot(self.W_em2, emb_val)
else:
if use_noise and self.noise_params:
emb_val = utils.dot(state_below, self.W_em + self.nW_em)
else:
emb_val = utils.dot(state_below, self.W_em)
if additional_inputs:
if use_noise and self.noise_params:
for inp, weight, noise_weight in zip(
additional_inputs, self.additional_weights,
self.noise_additional_weights):
emb_val += utils.dot(inp, (noise_weight + weight))
else:
for inp, weight in zip(additional_inputs, self.additional_weights):
emb_val += utils.dot(inp, weight)
self.preactiv = emb_val
if use_noise and self.noise_params and not no_noise_bias:
emb_val = TT.nnet.sigmoid(temp *
(emb_val + self.b_em + self.nb_em))
else:
emb_val = TT.nnet.sigmoid(temp * (emb_val + self.b_em))
self.out = emb_val
self.state_below = state_below
self.model_output = emb_val
return emb_val
def compute_sample(self,
state_below,
temp=1,
additional_inputs=None,
use_noise=False):
"""
See parent class.
"""
class_probs = self.fprop(state_below,
temp=temp,
additional_inputs=additional_inputs,
use_noise=use_noise)
pvals = class_probs
if pvals.ndim == 1:
pvals = pvals.dimshuffle('x', 0)
sample = self.trng.binomial(pvals.shape, p=pvals,
dtype='int64')
if class_probs.ndim == 1:
sample = sample[0]
self.sample = sample
return sample
def get_cost(self,
state_below,
target=None,
mask=None,
temp=1,
reg=None,
scale=None,
sum_over_time=None,
use_noise=True,
additional_inputs=None,
no_noise_bias=False):
"""
See parent class
"""
class_probs = self.fprop(state_below,
temp=temp,
use_noise=use_noise,
additional_inputs=additional_inputs,
no_noise_bias=no_noise_bias)
pvals = class_probs
assert target, 'Computing the cost requires a target'
if target.ndim == 3:
target = target.reshape((target.shape[0]*target.shape[1],
target.shape[2]))
assert 'float' in target.dtype
# Do we need the safety net of 1e-12 ?
cost = -TT.log(TT.maximum(1e-12, class_probs)) * target -\
TT.log(TT.maximum(1e-12, 1 - class_probs)) * (1 - target)
if cost.ndim > 1:
cost = cost.sum(1)
if mask:
mask = mask.flatten()
cost = cost * TT.cast(mask, theano.config.floatX)
if sum_over_time is None:
sum_over_time = self.sum_over_time
if sum_over_time:
if state_below.ndim == 3:
sh0 = TT.cast(state_below.shape[0],
theano.config.floatX)
sh1 = TT.cast(state_below.shape[1],
theano.config.floatX)
self.cost = cost.sum()/sh1
else:
self.cost = cost.sum()
else:
self.cost = cost.mean()
if scale:
self.cost = self.cost*scale
if reg:
self.cost = self.cost + reg
self.out = self.cost
self.mask = mask
self.cost_scale = scale
return self.cost
class SoftmaxLayer(CostLayer):
"""
Softmax output layer.
"""
def _get_samples(self, model, length=30, temp=1, *inps):
"""
See parent class
"""
if not hasattr(model, 'word_indxs_src'):
model.word_indxs_src = model.word_indxs
character_level = False
if hasattr(model, 'character_level'):
character_level = model.character_level
if model.del_noise:
model.del_noise()
[values, probs] = model.sample_fn(length, temp, *inps)
#print 'Generated sample is:'
#print
if values.ndim > 1:
for d in xrange(2):
print '%d-th sentence' % d
print 'Input: ',
if character_level:
sen = []
for k in xrange(inps[0].shape[0]):
if model.word_indxs_src[inps[0][k][d]] == '<eol>':
break
sen.append(model.word_indxs_src[inps[0][k][d]])
print "".join(sen),
else:
for k in xrange(inps[0].shape[0]):
print model.word_indxs_src[inps[0][k][d]],
if model.word_indxs_src[inps[0][k][d]] == '<eol>':
break
print ''
print 'Output: ',
if character_level:
sen = []
for k in xrange(values.shape[0]):
if model.word_indxs[values[k][d]] == '<eol>':
break
sen.append(model.word_indxs[values[k][d]])
print "".join(sen),
else:
for k in xrange(values.shape[0]):
print model.word_indxs[values[k][d]],
if model.word_indxs[values[k][d]] == '<eol>':
break
print
print
else:
print 'Input: ',
if character_level:
sen = []
for k in xrange(inps[0].shape[0]):
if model.word_indxs_src[inps[0][k]] == '<eol>':
break
sen.append(model.word_indxs_src[inps[0][k]])
print "".join(sen),
else:
for k in xrange(inps[0].shape[0]):
print model.word_indxs_src[inps[0][k]],
if model.word_indxs_src[inps[0][k]] == '<eol>':
break
print ''
print 'Output: ',
if character_level:
sen = []
for k in xrange(values.shape[0]):
if model.word_indxs[values[k]] == '<eol>':
break
sen.append(model.word_indxs[values[k]])
print "".join(sen),
else:
for k in xrange(values.shape[0]):
print model.word_indxs[values[k]],
if model.word_indxs[values[k]] == '<eol>':
break
print
print
def fprop(self,
state_below,
temp=numpy.float32(1),
use_noise=True,
additional_inputs=None,
no_noise_bias=False,
target=None,
full_softmax=True):
"""
Forward pass through the cost layer.
:type state_below: tensor or layer
:param state_below: The theano expression (or groundhog layer)
representing the input of the cost layer
:type temp: float or tensor scalar
:param temp: scalar representing the temperature that should be used
when sampling from the output distribution
:type use_noise: bool
:param use_noise: flag. If true, noise is used when computing the
output of the model
:type no_noise_bias: bool
:param no_noise_bias: flag, stating if weight noise should be added
to the bias as well, or only to the weights
"""
if not full_softmax:
assert target != None, 'target must be given'
if self.rank_n_approx:
if self.weight_noise and use_noise and self.noise_params:
emb_val = self.rank_n_activ(utils.dot(state_below,
self.W_em1+self.nW_em1))
nW_em = self.nW_em2
else:
emb_val = self.rank_n_activ(utils.dot(state_below, self.W_em1))
W_em = self.W_em2
else:
W_em = self.W_em
if self.weight_noise: