-
Notifications
You must be signed in to change notification settings - Fork 2
/
common_functions.py
2744 lines (2259 loc) · 152 KB
/
common_functions.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 numpy
import theano
import random
import theano.tensor as T
#import theano.tensor.nlinalg
from theano.tensor.nnet import conv
from cis.deep.utils.theano import debug_print
from logistic_sgd import LogisticRegression
import numpy as np
from scipy.spatial.distance import cosine
from mlp import HiddenLayer
import cPickle
from nltk import ne_chunk, pos_tag, word_tokenize
from nltk.tree import Tree
import nltk
# nltk.download('maxent_ne_chunker')
# nltk.download('words')
# nltk.download('punkt')
# nltk.download('averaged_perceptron_tagger')
def load_word2vec():
word2vec = {}
print "==> loading 300d word2vec"
# with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), "data/glove/glove.6B." + str(dim) + "d.txt")) as f:
f=open('/save/wenpeng/datasets/word2vec_words_300d.txt', 'r')#glove.6B.300d.txt, word2vec_words_300d.txt, glove.840B.300d.txt
for line in f:
l = line.split()
word2vec[l[0]] = map(float, l[1:])
print "==> word2vec is loaded"
return word2vec
def load_word2vec_to_init(rand_values, ivocab, word2vec):
fail=0
for id, word in ivocab.iteritems():
emb=word2vec.get(word)
if emb is not None:
rand_values[id]=np.array(emb)
else:
# print word
fail+=1
print '==> use word2vec initialization over...fail ', fail
return rand_values
def get_continuous_chunks(text):
wordlist = word_tokenize(text)
poslist = pos_tag(wordlist)
chunked = ne_chunk(poslist)
prev = None
continuous_chunk = []
current_chunk = []
for i in chunked:
if type(i) == Tree:
current_chunk.append(" ".join([token for token, pos in i.leaves()]))
elif current_chunk:
named_entity = " ".join(current_chunk)
if named_entity not in continuous_chunk:
continuous_chunk.append(named_entity)
current_chunk = []
else:
continue
return continuous_chunk, wordlist
def F1_two_strset(set1, set2):
size1 = len(set1)
size2 = len(set2)
if size1 == 0 or size2 == 0:
return 0.0
else:
overlap_size = len(set1& set2)
if overlap_size == 0:
return 0.0
recall = overlap_size*1.0/size1
prec = overlap_size*1.0/size2
return 2.0*recall*prec/(recall+prec)
def recall_first_set(set1, set2):
overlap_size = len(set1& set2)
if overlap_size == 0:
return 0.0
return overlap_size*1.0/(1e-8+len(set1))
def create_AttentionMatrix_para(rng, n_in, n_out):
W1_values = numpy.asarray(rng.uniform(
low=-numpy.sqrt(6. / (n_in + n_out)),
high=numpy.sqrt(6. / (n_in + n_out)),
size=(n_in, n_out)), dtype=theano.config.floatX) # @UndefinedVariable
W1 = theano.shared(value=W1_values, name='W1', borrow=True)
W2_values = numpy.asarray(rng.uniform(
low=-numpy.sqrt(6. / (n_in + n_out)),
high=numpy.sqrt(6. / (n_in + n_out)),
size=(n_in, n_out)), dtype=theano.config.floatX) # @UndefinedVariable
W2 = theano.shared(value=W2_values, name='W2', borrow=True)
# b_values = numpy.zeros((n_out,), dtype=theano.config.floatX) # @UndefinedVariable
w_values = numpy.asarray(rng.uniform(
low=-numpy.sqrt(6. / (n_out+1)),
high=numpy.sqrt(6. / (n_out+1)),
size=(n_out,)), dtype=theano.config.floatX) # @UndefinedVariable
w = theano.shared(value=w_values, name='w', borrow=True)
return W1,W2, w
def create_HiddenLayer_para(rng, n_in, n_out):
W_values = numpy.asarray(rng.uniform(
low=-numpy.sqrt(6. / (n_in + n_out)),
high=numpy.sqrt(6. / (n_in + n_out)),
size=(n_in, n_out)), dtype=theano.config.floatX) # @UndefinedVariable
W = theano.shared(value=W_values, name='W', borrow=True)
b_values = numpy.zeros((n_out,), dtype=theano.config.floatX) # @UndefinedVariable
b = theano.shared(value=b_values, name='b', borrow=True)
return W,b
def create_Bi_GRU_para(rng, word_dim, hidden_dim):
# Initialize the network parameters
U = numpy.random.uniform(-numpy.sqrt(1./hidden_dim), numpy.sqrt(1./hidden_dim), (3, hidden_dim, word_dim))
W = numpy.random.uniform(-numpy.sqrt(1./hidden_dim), numpy.sqrt(1./hidden_dim), (3, hidden_dim, hidden_dim))
b = numpy.zeros((3, hidden_dim))
# Theano: Created shared variables
U = debug_print(theano.shared(name='U', value=U.astype(theano.config.floatX), borrow=True), 'U')
W = debug_print(theano.shared(name='W', value=W.astype(theano.config.floatX), borrow=True), 'W')
b = debug_print(theano.shared(name='b', value=b.astype(theano.config.floatX), borrow=True), 'b')
Ub = numpy.random.uniform(-numpy.sqrt(1./hidden_dim), numpy.sqrt(1./hidden_dim), (3, hidden_dim, word_dim))
Wb = numpy.random.uniform(-numpy.sqrt(1./hidden_dim), numpy.sqrt(1./hidden_dim), (3, hidden_dim, hidden_dim))
bb = numpy.zeros((3, hidden_dim))
# Theano: Created shared variables
Ub = debug_print(theano.shared(name='Ub', value=Ub.astype(theano.config.floatX), borrow=True), 'Ub')
Wb = debug_print(theano.shared(name='Wb', value=Wb.astype(theano.config.floatX), borrow=True), 'Wb')
bb = debug_print(theano.shared(name='bb', value=bb.astype(theano.config.floatX), borrow=True), 'bb')
return U, W, b, Ub, Wb, bb
def create_GRU_para(rng, word_dim, hidden_dim):
# Initialize the network parameters
# U = numpy.random.uniform(-0.01, 0.01, (3, hidden_dim, word_dim))
U=rng.normal(0.0, 0.01, (3, hidden_dim, word_dim))
# W = numpy.random.uniform(-0.01, 0.01, (3, hidden_dim, hidden_dim))
W=rng.normal(0.0, 0.01, (3, hidden_dim, hidden_dim))
b = numpy.zeros((3, hidden_dim))
# Theano: Created shared variables
U = theano.shared(name='U', value=U.astype(theano.config.floatX), borrow=True)
W =theano.shared(name='W', value=W.astype(theano.config.floatX), borrow=True)
b = theano.shared(name='b', value=b.astype(theano.config.floatX), borrow=True)
return U, W, b
def create_LSTM_para(rng, word_dim, hidden_dim):
params={}
#W play with input dimension
W = rng.normal(0.0, 0.01, (word_dim, 4*hidden_dim))
params['W'] = theano.shared(name='W', value=W.astype(theano.config.floatX), borrow=True)
#U play with hidden states
U = rng.normal(0.0, 0.01, (hidden_dim, 4*hidden_dim))
params['U'] = theano.shared(name='U', value=U.astype(theano.config.floatX), borrow=True)
b = numpy.zeros((4 * hidden_dim,))
params['b'] = theano.shared(name='b', value=b.astype(theano.config.floatX), borrow=True)
return params
def create_ensemble_para(rng, fan_in, fan_out):
# W=rng.normal(0.0, 0.01, (fan_out,fan_in))
#
# W =theano.shared(name='W', value=W.astype(theano.config.floatX), borrow=True)
# initialize weights with random weights
W_bound = numpy.sqrt(6. /(fan_in + fan_out))
W = theano.shared(numpy.asarray(
rng.uniform(low=-0.01, high=0.01, size=(fan_out,fan_in)),
dtype=theano.config.floatX),
borrow=True)
return W
def create_ensemble_para_with_bounds(rng, fan_in, fan_out, lowerbound, upperbound):
W = theano.shared(numpy.asarray(
rng.uniform(low=lowerbound, high=upperbound, size=(fan_out,fan_in)),
dtype=theano.config.floatX),
borrow=True)
return W
def create_highw_para(rng, fan_in, fan_out):
# initialize weights with random weights
W_bound = numpy.sqrt(6. / (fan_in + fan_out))
W = theano.shared(numpy.asarray(
rng.uniform(low=-W_bound, high=W_bound, size=(fan_out,fan_in)),
dtype=theano.config.floatX),
borrow=True)
# the bias is a 1D tensor -- one bias per output feature map
b_values = numpy.zeros((fan_out,), dtype=theano.config.floatX)
b = theano.shared(value=b_values, borrow=True)
return W, b
def create_conv_para(rng, filter_shape):
fan_in = numpy.prod(filter_shape[1:])
fan_out = filter_shape[0] * numpy.prod(filter_shape[2:])
# initialize weights with random weights
W_bound = numpy.sqrt(6. / (fan_in + fan_out))
W = theano.shared(numpy.asarray(
rng.uniform(low=-0.01, high=0.01, size=filter_shape),
dtype=theano.config.floatX),
borrow=True)
# the bias is a 1D tensor -- one bias per output feature map
b_values = numpy.zeros((filter_shape[0],), dtype=theano.config.floatX)
b = theano.shared(value=b_values, borrow=True)
return W, b
def create_conv_bias(rng, hidden_size):
# the bias is a 1D tensor -- one bias per output feature map
b_values = numpy.zeros((hidden_size,), dtype=theano.config.floatX)
b = theano.shared(value=b_values, borrow=True)
return b
def create_rnn_para(rng, dim):
# initialize weights with random weights
W_bound = numpy.sqrt(6. / (2*dim + dim))
# Whh = theano.shared(numpy.asarray(
# rng.uniform(low=-W_bound, high=W_bound, size=(dim, dim)),
# dtype=theano.config.floatX),
# borrow=True)
# Wxh = theano.shared(numpy.asarray(
# rng.uniform(low=-W_bound, high=W_bound, size=(dim, dim)),
# dtype=theano.config.floatX),
# borrow=True)
W = theano.shared(numpy.asarray(
rng.uniform(low=-W_bound, high=W_bound, size=(2*dim, dim)),
dtype=theano.config.floatX),
borrow=True)
# the bias is a 1D tensor -- one bias per output feature map
b_values = numpy.zeros((dim,), dtype=theano.config.floatX)
b = theano.shared(value=b_values, borrow=True)
return W, b
def ABCNN(left_T, right_T):
dot_tensor3 = T.batched_dot(left_T.dimshuffle(0,2,1),right_T) #(batch, l_len, r_len)
dot_matrix_for_right = T.nnet.softmax(T.max(dot_tensor3, axis=1)) #(batch, r_len)
weighted_sum_r = T.batched_dot(dot_matrix_for_right.dimshuffle(0,'x',1), right_T.dimshuffle(0,2,1)).reshape((right_T.shape[0], right_T.shape[1])) #(batch,hidden, l_len)
dot_matrix_for_left = T.nnet.softmax(T.max(dot_tensor3, axis=2))
weighted_sum_l = T.batched_dot(dot_matrix_for_left.dimshuffle(0,'x',1), left_T.dimshuffle(0,2,1)).reshape((left_T.shape[0], left_T.shape[1])) #(batch,hidden, r_len)
return weighted_sum_l,weighted_sum_r
def Conv_for_Self_Attend(input_tensor3, mask_matrix):
#construct interaction matrix
input_tensor3 = input_tensor3*mask_matrix.dimshuffle(0,'x',1)
input_tensor3_r = input_tensor3
mask_matrix_r = mask_matrix
input_tensor3_r = input_tensor3_r*mask_matrix_r.dimshuffle(0,'x',1) #(batch, hidden, r_len)
dot_tensor3 = T.batched_dot(input_tensor3.dimshuffle(0,2,1),input_tensor3_r) #(batch, l_len, r_len)
dot_matrix_for_right = T.nnet.softmax(dot_tensor3.reshape((dot_tensor3.shape[0]*dot_tensor3.shape[1], dot_tensor3.shape[2])))
dot_tensor3_for_right = dot_matrix_for_right.reshape((dot_tensor3.shape[0], dot_tensor3.shape[1], dot_tensor3.shape[2]))#(batch, l_len, r_len)
weighted_sum_r = T.batched_dot(dot_tensor3_for_right, input_tensor3_r.dimshuffle(0,2,1)).dimshuffle(0,2,1)*mask_matrix.dimshuffle(0,'x',1) #(batch,hidden, l_len)
# self.concat_output_tensor3 = T.concatenate([input_tensor3, weighted_sum_r], axis=1) #(batch, 2*hidden, len)
sum_output_tensor3 = input_tensor3+weighted_sum_r
return sum_output_tensor3
def tensor3_group_maxpool(tensor3, valid_left_vec, group_size):
#tensor3 (batch, hidden, len)
#valid_left_vec #batch
#group_size 3
def each_slice(matrix, left):
#matrix (hidden , len)
group_width = (matrix.shape[1]-left)/group_size
if T.lt(group_width, 1):
pool_vec_1 = (T.max(matrix[:,left:], axis=1)).dimshuffle(0,'x') #(hidden, 1)
pool_vec_2 = pool_vec_1
pool_vec_3 = pool_vec_1
else:
pool_vec_1 = (T.max(matrix[:,left:left+group_width], axis=1)).dimshuffle(0,'x') #(hidden, 1)
pool_vec_2 = (T.max(matrix[:,left+group_width:left+2*group_width], axis=1)).dimshuffle(0,'x')
pool_vec_3 = (T.max(matrix[:,left+2*group_width:], axis=1)).dimshuffle(0,'x')
return T.concatenate([pool_vec_1,pool_vec_2,pool_vec_3], axis=1) #(hidden, 3)
batch_return, _ = theano.scan(
each_slice,
sequences=[tensor3,valid_left_vec]) #(batch,hidden, 3)
return batch_return
def fine_grained_softmax_tensor3(tensor3, left_vec):
def process_matrix(matrix, left):
submatrix = matrix[:,left:]
sub_distr = T.nnet.softmax(submatrix)
return T.concatenate([matrix[:,:left], sub_distr], axis=1)
batch_return, _ = theano.scan(
process_matrix,
sequences=[tensor3,left_vec]) #(batch,hidden, len)
return batch_return
class Attentive_Conv_for_Pair(object):
def __init__(self, rng, origin_input_tensor3,origin_input_tensor3_r,input_tensor3, input_tensor3_r, mask_matrix, mask_matrix_r,
filter_shape, filter_shape_context,image_shape, image_shape_r,W, b, W_context, b_context):
'''
Input:
origin_input_tensor3: (batch_size, hidden_size, sen_length). tensor3 representation for sentence 1
origin_input_tensor3_r: (batch_size, hidden_size, sen_length). tensor3 representation for sentence 2
input_tensor3: (batch_size, hidden_size, sen_length). tensor3 representation for sentence 1. It can be the same with 'origin_input_tensor3' or be the output of gated convolution layer
input_tensor3_r: (batch_size, hidden_size, sen_length). tensor3 representation for sentence 2. It can be the same with 'origin_input_tensor3_r' or be the output of gated convolution layer
mask_matrix, mask_matrix_r: mask for the two sentences respectively. Each with (batch_size, sent_length), each row corresponding to one sentence
filter_shape: standard filter shape for theano convolution function, in shape (hidden_size, 1, emb_size, filter_width)
filter_shape_context: the filter shape to deal with the 'fake sentence' which contains attentive context. In shape (hidden_size, 1, emb_size, 1)
image_shape, image_shape_r: standard tensor4 theano image_shape. (batch_size, 1, emb_size, sent_length)
W, b: parameters to deal with each sentence
W_context, b_context: parameters to deal with 'fake attentive-context sentence' for each sentence
Output:
attentive_maxpool_vec_l: a vector to represent the sentence 1
attentive_maxpool_vec_r: a vector to represent the sentence 2
'''
batch_size = origin_input_tensor3.shape[0]
hidden_size = origin_input_tensor3.shape[1]
l_len = origin_input_tensor3.shape[2]
r_len = origin_input_tensor3_r.shape[2]
#construct interaction matrix
input_tensor3 = input_tensor3*mask_matrix.dimshuffle(0,'x',1)
input_tensor3_r = input_tensor3_r*mask_matrix_r.dimshuffle(0,'x',1) #(batch, hidden, r_len)
dot_tensor3 = T.batched_dot(input_tensor3.dimshuffle(0,2,1),input_tensor3_r) #(batch, l_len, r_len)
l_max_cos = 1.0/(1.0+T.max(T.nnet.relu(dot_tensor3), axis=2))#1.0/T.exp(T.max(T.nnet.sigmoid(dot_tensor3), axis=2)) #(batch, l_len)
r_max_cos = 1.0/(1.0+T.max(T.nnet.relu(dot_tensor3), axis=1))#1.0/T.exp(T.max(T.nnet.sigmoid(dot_tensor3), axis=1)) #(batch, r_len)
dot_matrix_for_right = T.nnet.softmax(dot_tensor3.reshape((batch_size*l_len, r_len))) #(batch*l_len, r_len)
dot_tensor3_for_right = dot_matrix_for_right.reshape((batch_size, l_len, r_len))#(batch, l_len, r_len)
weighted_sum_r = T.batched_dot(dot_tensor3_for_right, input_tensor3_r.dimshuffle(0,2,1)).dimshuffle(0,2,1)*mask_matrix.dimshuffle(0,'x',1) #(batch,hidden, l_len)
dot_matrix_for_left = T.nnet.softmax(dot_tensor3.dimshuffle(0,2,1).reshape((batch_size*r_len, l_len))) #(batch*r_len, l_len)
dot_tensor3_for_left = dot_matrix_for_left.reshape((batch_size, r_len, l_len))#(batch, r_len, l_len)
weighted_sum_l = T.batched_dot(dot_tensor3_for_left, input_tensor3.dimshuffle(0,2,1)).dimshuffle(0,2,1)*mask_matrix_r.dimshuffle(0,'x',1) #(batch,hidden, r_len)
#convolve left, weighted sum r
biased_conv_model_l = Conv_with_Mask(rng, input_tensor3=origin_input_tensor3*l_max_cos.dimshuffle(0,'x',1),
mask_matrix = mask_matrix,
image_shape=image_shape,
filter_shape=filter_shape, W=W, b=b)
biased_temp_conv_output_l = biased_conv_model_l.naked_conv_out
self.conv_out_l = biased_conv_model_l.masked_conv_out
self.maxpool_vec_l = biased_conv_model_l.maxpool_vec
conv_model_l = Conv_with_Mask(rng, input_tensor3=origin_input_tensor3,
mask_matrix = mask_matrix,
image_shape=image_shape,
filter_shape=filter_shape, W=W, b=b)
temp_conv_output_l = conv_model_l.naked_conv_out
conv_model_weighted_r = Conv_with_Mask(rng, input_tensor3=weighted_sum_r,
mask_matrix = mask_matrix,
image_shape=image_shape,
filter_shape=filter_shape_context, W=W_context, b=b_context) # note that b_context is not used
temp_conv_output_weighted_r = conv_model_weighted_r.naked_conv_out
'''
combine
'''
mask_for_conv_output_l=T.repeat(mask_matrix.dimshuffle(0,'x',1), filter_shape[0], axis=1) #(batch_size, emb_size, maxSentLen-filter_size+1)
mask_for_conv_output_l=(1.0-mask_for_conv_output_l)*(mask_for_conv_output_l-10)
self.biased_conv_attend_out_l = T.tanh(biased_temp_conv_output_l+ temp_conv_output_weighted_r+ b.dimshuffle('x', 0, 'x'))*mask_matrix.dimshuffle(0,'x',1)
self.biased_attentive_sumpool_vec_l=T.sum(self.biased_conv_attend_out_l, axis=2)
self.biased_attentive_meanpool_vec_l=self.biased_attentive_sumpool_vec_l/T.sum(mask_matrix,axis=1).dimshuffle(0,'x')
masked_biased_conv_output_l=self.biased_conv_attend_out_l+mask_for_conv_output_l #mutiple mask with the conv_out to set the features by UNK to zero
self.biased_attentive_maxpool_vec_l=T.max(masked_biased_conv_output_l, axis=2) #(batch_size, hidden_size) # each sentence then have an embedding of length hidden_size
self.conv_attend_out_l = T.tanh(temp_conv_output_l+ temp_conv_output_weighted_r+ b.dimshuffle('x', 0, 'x'))*mask_matrix.dimshuffle(0,'x',1)
masked_conv_output_l=self.conv_attend_out_l+mask_for_conv_output_l #mutiple mask with the conv_out to set the features by UNK to zero
self.attentive_maxpool_vec_l=T.max(masked_conv_output_l, axis=2) #(batch_size, hidden_size) # each sentence then have an embedding of length hidden_size
"convolve right, weighted sum l"
biased_conv_model_r = Conv_with_Mask(rng, input_tensor3=origin_input_tensor3_r*r_max_cos.dimshuffle(0,'x',1),
mask_matrix = mask_matrix_r,
image_shape=image_shape_r,
filter_shape=filter_shape, W=W, b=b)
biased_temp_conv_output_r = biased_conv_model_r.naked_conv_out
self.conv_out_r = biased_conv_model_r.masked_conv_out
self.maxpool_vec_r = biased_conv_model_r.maxpool_vec
conv_model_r = Conv_with_Mask(rng, input_tensor3=origin_input_tensor3_r,
mask_matrix = mask_matrix_r,
image_shape=image_shape_r,
filter_shape=filter_shape, W=W, b=b)
temp_conv_output_r = conv_model_r.naked_conv_out
conv_model_weighted_l = Conv_with_Mask(rng, input_tensor3=weighted_sum_l,
mask_matrix = mask_matrix_r,
image_shape=image_shape_r,
filter_shape=filter_shape_context, W=W_context, b=b_context) # note that b_context is not used
temp_conv_output_weighted_l = conv_model_weighted_l.naked_conv_out
'''
combine
'''
mask_for_conv_output_r=T.repeat(mask_matrix_r.dimshuffle(0,'x',1), filter_shape[0], axis=1) #(batch_size, emb_size, maxSentLen-filter_size+1)
mask_for_conv_output_r=(1.0-mask_for_conv_output_r)*(mask_for_conv_output_r-10)
self.biased_conv_attend_out_r = T.tanh(biased_temp_conv_output_r+ temp_conv_output_weighted_l+ b.dimshuffle('x', 0, 'x'))*mask_matrix_r.dimshuffle(0,'x',1)
self.biased_attentive_sumpool_vec_r=T.sum(self.biased_conv_attend_out_r, axis=2)
self.biased_attentive_meanpool_vec_r=self.biased_attentive_sumpool_vec_r/T.sum(mask_matrix_r,axis=1).dimshuffle(0,'x')
self.conv_attend_out_r = T.tanh(temp_conv_output_r+ temp_conv_output_weighted_l+ b.dimshuffle('x', 0, 'x'))*mask_matrix_r.dimshuffle(0,'x',1)
# self.attentive_sumpool_vec_r=T.sum(self.conv_attend_out_r, axis=2)
masked_biased_conv_output_r=self.biased_conv_attend_out_r+mask_for_conv_output_r #mutiple mask with the conv_out to set the features by UNK to zero
self.biased_attentive_maxpool_vec_r=T.max(masked_biased_conv_output_r, axis=2) #(batch_size, hidden_size) # each sentence then have an embedding of length hidden_size
masked_conv_output_r=self.conv_attend_out_r+mask_for_conv_output_r #mutiple mask with the conv_out to set the features by UNK to zero
self.attentive_maxpool_vec_r=T.max(masked_conv_output_r, axis=2) #(batch_size, hidden_size) # each sentence then have an embedding of length hidden_size
class Attentive_Conv_for_Pair_easy_version(object):
def __init__(self, rng, input_tensor3, input_tensor3_r, mask_matrix, mask_matrix_r,
filter_shape, filter_shape_context,image_shape, image_shape_r,W, b, W_context, b_context):
'''
Input:
input_tensor3: (batch_size, hidden_size, sen_length). tensor3 representation for sentence 1
input_tensor3_r: (batch_size, hidden_size, sen_length). tensor3 representation for sentence 2
mask_matrix, mask_matrix_r: mask for the two sentences respectively. Each with (batch_size, sent_length), each row corresponding to one sentence
filter_shape: standard filter shape for theano convolution function, in shape (hidden_size, 1, emb_size, filter_width)
filter_shape_context: the filter shape to deal with the 'fake sentence' which contains attentive context. In shape (hidden_size, 1, emb_size, 1)
image_shape, image_shape_r: standard tensor4 theano image_shape. (batch_size, 1, emb_size, sent_length)
W, b: parameters to deal with each sentence
W_context, b_context: parameters to deal with 'fake attentive-context sentence' for each sentence
Output:
attentive_maxpool_vec_l: a vector to represent the sentence 1
attentive_maxpool_vec_r: a vector to represent the sentence 2
'''
origin_input_tensor3=input_tensor3
origin_input_tensor3_r=input_tensor3_r
batch_size = origin_input_tensor3.shape[0]
hidden_size = origin_input_tensor3.shape[1]
l_len = origin_input_tensor3.shape[2]
r_len = origin_input_tensor3_r.shape[2]
#construct interaction matrix
input_tensor3 = input_tensor3*mask_matrix.dimshuffle(0,'x',1)
input_tensor3_r = input_tensor3_r*mask_matrix_r.dimshuffle(0,'x',1) #(batch, hidden, r_len)
dot_tensor3 = T.batched_dot(input_tensor3.dimshuffle(0,2,1),input_tensor3_r) #(batch, l_len, r_len)
l_max_cos = 1.0/(1.0+T.max(T.nnet.relu(dot_tensor3), axis=2))#1.0/T.exp(T.max(T.nnet.sigmoid(dot_tensor3), axis=2)) #(batch, l_len)
r_max_cos = 1.0/(1.0+T.max(T.nnet.relu(dot_tensor3), axis=1))#1.0/T.exp(T.max(T.nnet.sigmoid(dot_tensor3), axis=1)) #(batch, r_len)
dot_matrix_for_right = T.nnet.softmax(dot_tensor3.reshape((batch_size*l_len, r_len))) #(batch*l_len, r_len)
dot_tensor3_for_right = dot_matrix_for_right.reshape((batch_size, l_len, r_len))#(batch, l_len, r_len)
weighted_sum_r = T.batched_dot(dot_tensor3_for_right, input_tensor3_r.dimshuffle(0,2,1)).dimshuffle(0,2,1)*mask_matrix.dimshuffle(0,'x',1) #(batch,hidden, l_len)
dot_matrix_for_left = T.nnet.softmax(dot_tensor3.dimshuffle(0,2,1).reshape((batch_size*r_len, l_len))) #(batch*r_len, l_len)
dot_tensor3_for_left = dot_matrix_for_left.reshape((batch_size, r_len, l_len))#(batch, r_len, l_len)
weighted_sum_l = T.batched_dot(dot_tensor3_for_left, input_tensor3.dimshuffle(0,2,1)).dimshuffle(0,2,1)*mask_matrix_r.dimshuffle(0,'x',1) #(batch,hidden, r_len)
#convolve left, weighted sum r
biased_conv_model_l = Conv_with_Mask(rng, input_tensor3=origin_input_tensor3*l_max_cos.dimshuffle(0,'x',1),
mask_matrix = mask_matrix,
image_shape=image_shape,
filter_shape=filter_shape, W=W, b=b)
biased_temp_conv_output_l = biased_conv_model_l.naked_conv_out
self.conv_out_l = biased_conv_model_l.masked_conv_out
self.maxpool_vec_l = biased_conv_model_l.maxpool_vec
conv_model_l = Conv_with_Mask(rng, input_tensor3=origin_input_tensor3,
mask_matrix = mask_matrix,
image_shape=image_shape,
filter_shape=filter_shape, W=W, b=b)
temp_conv_output_l = conv_model_l.naked_conv_out
conv_model_weighted_r = Conv_with_Mask(rng, input_tensor3=weighted_sum_r,
mask_matrix = mask_matrix,
image_shape=image_shape,
filter_shape=filter_shape_context, W=W_context, b=b_context) # note that b_context is not used
temp_conv_output_weighted_r = conv_model_weighted_r.naked_conv_out
'''
combine
'''
mask_for_conv_output_l=T.repeat(mask_matrix.dimshuffle(0,'x',1), filter_shape[0], axis=1) #(batch_size, emb_size, maxSentLen-filter_size+1)
mask_for_conv_output_l=(1.0-mask_for_conv_output_l)*(mask_for_conv_output_l-10)
self.biased_conv_attend_out_l = T.tanh(biased_temp_conv_output_l+ temp_conv_output_weighted_r+ b.dimshuffle('x', 0, 'x'))*mask_matrix.dimshuffle(0,'x',1)
self.biased_attentive_sumpool_vec_l=T.sum(self.biased_conv_attend_out_l, axis=2)
self.biased_attentive_meanpool_vec_l=self.biased_attentive_sumpool_vec_l/T.sum(mask_matrix,axis=1).dimshuffle(0,'x')
masked_biased_conv_output_l=self.biased_conv_attend_out_l+mask_for_conv_output_l #mutiple mask with the conv_out to set the features by UNK to zero
self.biased_attentive_maxpool_vec_l=T.max(masked_biased_conv_output_l, axis=2) #(batch_size, hidden_size) # each sentence then have an embedding of length hidden_size
self.conv_attend_out_l = T.tanh(temp_conv_output_l+ temp_conv_output_weighted_r+ b.dimshuffle('x', 0, 'x'))*mask_matrix.dimshuffle(0,'x',1)
masked_conv_output_l=self.conv_attend_out_l+mask_for_conv_output_l #mutiple mask with the conv_out to set the features by UNK to zero
self.attentive_maxpool_vec_l=T.max(masked_conv_output_l, axis=2) #(batch_size, hidden_size) # each sentence then have an embedding of length hidden_size
"convolve right, weighted sum l"
biased_conv_model_r = Conv_with_Mask(rng, input_tensor3=origin_input_tensor3_r*r_max_cos.dimshuffle(0,'x',1),
mask_matrix = mask_matrix_r,
image_shape=image_shape_r,
filter_shape=filter_shape, W=W, b=b)
biased_temp_conv_output_r = biased_conv_model_r.naked_conv_out
self.conv_out_r = biased_conv_model_r.masked_conv_out
self.maxpool_vec_r = biased_conv_model_r.maxpool_vec
conv_model_r = Conv_with_Mask(rng, input_tensor3=origin_input_tensor3_r,
mask_matrix = mask_matrix_r,
image_shape=image_shape_r,
filter_shape=filter_shape, W=W, b=b)
temp_conv_output_r = conv_model_r.naked_conv_out
conv_model_weighted_l = Conv_with_Mask(rng, input_tensor3=weighted_sum_l,
mask_matrix = mask_matrix_r,
image_shape=image_shape_r,
filter_shape=filter_shape_context, W=W_context, b=b_context) # note that b_context is not used
temp_conv_output_weighted_l = conv_model_weighted_l.naked_conv_out
'''
combine
'''
mask_for_conv_output_r=T.repeat(mask_matrix_r.dimshuffle(0,'x',1), filter_shape[0], axis=1) #(batch_size, emb_size, maxSentLen-filter_size+1)
mask_for_conv_output_r=(1.0-mask_for_conv_output_r)*(mask_for_conv_output_r-10)
self.biased_conv_attend_out_r = T.tanh(biased_temp_conv_output_r+ temp_conv_output_weighted_l+ b.dimshuffle('x', 0, 'x'))*mask_matrix_r.dimshuffle(0,'x',1)
self.biased_attentive_sumpool_vec_r=T.sum(self.biased_conv_attend_out_r, axis=2)
self.biased_attentive_meanpool_vec_r=self.biased_attentive_sumpool_vec_r/T.sum(mask_matrix_r,axis=1).dimshuffle(0,'x')
self.conv_attend_out_r = T.tanh(temp_conv_output_r+ temp_conv_output_weighted_l+ b.dimshuffle('x', 0, 'x'))*mask_matrix_r.dimshuffle(0,'x',1)
# self.attentive_sumpool_vec_r=T.sum(self.conv_attend_out_r, axis=2)
masked_biased_conv_output_r=self.biased_conv_attend_out_r+mask_for_conv_output_r #mutiple mask with the conv_out to set the features by UNK to zero
self.biased_attentive_maxpool_vec_r=T.max(masked_biased_conv_output_r, axis=2) #(batch_size, hidden_size) # each sentence then have an embedding of length hidden_size
masked_conv_output_r=self.conv_attend_out_r+mask_for_conv_output_r #mutiple mask with the conv_out to set the features by UNK to zero
self.attentive_maxpool_vec_r=T.max(masked_conv_output_r, axis=2) #(batch_size, hidden_size) # each sentence then have an embedding of length hidden_size
class Conv_for_Pair_Multi_Perspective(object):
"""we define CNN by input tensor3 and output tensor3, like RNN, filter width must by 3,5,7..."""
def __init__(self, rng, origin_input_tensor3, origin_input_tensor3_r, input_tensor3, input_tensor3_r, mask_matrix, mask_matrix_r,
filter_shape, filter_shape_context,image_shape, image_shape_r,W, b, W_context, b_context,
MP_W, psp_size):
#MP_W: (emb_size, l), l meams perspectives
MP_W=T.nnet.relu(MP_W) # first make sure each dim has weight 0-1
#construct interaction matrix
batch_size = input_tensor3.shape[0]
hidden_size = filter_shape[0]
l_len = input_tensor3.shape[2]
r_len = input_tensor3_r.shape[2]
input_tensor3 = input_tensor3*mask_matrix.dimshuffle(0,'x',1)
input_tensor3_r = input_tensor3_r*mask_matrix_r.dimshuffle(0,'x',1)
inter_tensor3 = T.extra_ops.repeat(input_tensor3, r_len, axis=2)*T.tile(input_tensor3_r, (1,1,l_len)) #(batch, hidden, l_len*r_len)
inter_tensor3_psp = (inter_tensor3.dimshuffle(0,2,1).dot(MP_W)).dimshuffle(0,2,1) #(batch, kerns,l_len*r_len )
inter_tensor4_psp = inter_tensor3_psp.reshape((batch_size, psp_size, l_len, r_len)) #(batch, kerns, l_lrn, r_len)
dot_tensor3 = inter_tensor4_psp.reshape((batch_size*psp_size,l_len,r_len)) #(batch*kerns, l_len, r_len)
l_max_cos = 1.0/(1.0+T.max(T.nnet.relu(dot_tensor3), axis=2))##(batch*kerns, l_len)
r_max_cos = 1.0/(1.0+T.max(T.nnet.relu(dot_tensor3), axis=1))##(batch*kerns, r_len)
exp_inter_tensor4_psp = T.exp(inter_tensor4_psp)
softmax_for_right = exp_inter_tensor4_psp/T.sum(exp_inter_tensor4_psp, axis=3).dimshuffle(0,1,2,'x') #(batch, kerns, l_lrn, r_len)
softmax_for_left = exp_inter_tensor4_psp/T.sum(exp_inter_tensor4_psp, axis=2).dimshuffle(0,1,'x',2) #(batch, kerns, l_lrn, r_len)
softmax_for_right_tensor3 = softmax_for_right.reshape((batch_size*psp_size,l_len,r_len))#(batch*kerns, l_lrn, r_len)
softmax_for_left_tensor3 = softmax_for_left.reshape((batch_size*psp_size,l_len,r_len)).dimshuffle(0,2,1)#(batch*kerns, r_lrn, l_len)
repeat_input_tensor3 = T.repeat(input_tensor3,psp_size, axis=0 ) #(batch*kerns, hidden, l_len)
repeat_mask_matrix = T.repeat(mask_matrix,psp_size, axis=0 ) #(batch*kerns, l_len)
repeat_input_tensor3_r = T.repeat(input_tensor3_r,psp_size, axis=0 ) #(batch*kerns, hidden, r_len)
repeat_mask_matrix_r = T.repeat(mask_matrix_r,psp_size, axis=0 ) #(batch*kerns, r_len)
weighted_sum_r = T.batched_dot(softmax_for_right_tensor3, repeat_input_tensor3_r.dimshuffle(0,2,1)).dimshuffle(0,2,1)*repeat_mask_matrix.dimshuffle(0,'x',1) #(batch*kerns,hidden, l_len)
weighted_sum_l = T.batched_dot(softmax_for_left_tensor3, repeat_input_tensor3.dimshuffle(0,2,1)).dimshuffle(0,2,1)*repeat_mask_matrix_r.dimshuffle(0,'x',1) #(batch*kerns,hidden, r_len)
repeat_origin_input_tensor3 = T.repeat(origin_input_tensor3, psp_size, axis=0 ) #(batch*kerns, hidden, l_len)
biased_conv_model_l = Conv_with_Mask(rng, input_tensor3=repeat_origin_input_tensor3*l_max_cos.dimshuffle(0,'x',1),
mask_matrix = repeat_mask_matrix,
image_shape=(image_shape[0]*psp_size, image_shape[1],image_shape[2],image_shape[3]),
filter_shape=filter_shape, W=W, b=b)
biased_temp_conv_output_l = biased_conv_model_l.naked_conv_out #(batch*kerns, hidden, l_len)
# self.conv_out_l = biased_conv_model_l.masked_conv_out
# self.maxpool_vec_l = biased_conv_model_l.maxpool_vec
# conv_model_l = Conv_with_Mask(rng, input_tensor3=origin_input_tensor3,
# mask_matrix = mask_matrix,
# image_shape=image_shape,
# filter_shape=filter_shape, W=W, b=b)
# temp_conv_output_l = conv_model_l.naked_conv_out
conv_model_weighted_r = Conv_with_Mask(rng, input_tensor3=weighted_sum_r,
mask_matrix = repeat_mask_matrix,
image_shape=(image_shape[0]*psp_size, image_shape[1],image_shape[2],image_shape[3]),
filter_shape=filter_shape_context, W=W_context, b=b_context) # note that b_context is not used
temp_conv_output_weighted_r = conv_model_weighted_r.naked_conv_out #(batch*kerns, hidden, l_len)
'''
combine
'''
mask_for_conv_output_l=T.repeat(repeat_mask_matrix.dimshuffle(0,'x',1), filter_shape[0], axis=1) #(batch_size*kerns, emb_size, maxSentLen)
mask_for_conv_output_l=(1.0-mask_for_conv_output_l)*(mask_for_conv_output_l-10)
self.biased_conv_attend_out_l = T.tanh(biased_temp_conv_output_l+ temp_conv_output_weighted_r+ b.dimshuffle('x', 0, 'x'))*repeat_mask_matrix.dimshuffle(0,'x',1)
# self.attentive_sumpool_vec_l=T.sum(self.conv_attend_out_l, axis=2)
masked_biased_conv_output_l=self.biased_conv_attend_out_l+mask_for_conv_output_l ##(batch_size*kerns, emb_size, l_len)
self.biased_attentive_maxpool_vec_l_psp=T.max(masked_biased_conv_output_l, axis=2) #(batch_size*kerns, hidden_size) # each sentence then have an embedding of length hidden_size
# self.biased_attentive_maxpool_vec_l_psp=T.max(masked_biased_conv_output_l, axis=2).reshape((batch_size, psp_size*hidden_size)) #(batch_size*kerns, hidden_size) # each sentence then have an embedding of length hidden_size
# self.conv_attend_out_l = T.tanh(temp_conv_output_l+ temp_conv_output_weighted_r+ b.dimshuffle('x', 0, 'x'))*mask_matrix.dimshuffle(0,'x',1)
# masked_conv_output_l=self.conv_attend_out_l+mask_for_conv_output_l #mutiple mask with the conv_out to set the features by UNK to zero
# self.attentive_maxpool_vec_l=T.max(masked_conv_output_l, axis=2) #(batch_size, hidden_size) # each sentence then have an embedding of length hidden_size
# self.group_max_pools_l = T.signal.pool.pool_2d(input=self.conv_out_l, ds=(1,10), ignore_border=True) #(batch, hidden, 5)
# self.all_att_maxpool_vecs_l = T.concatenate([self.attentive_maxpool_vec_l.dimshuffle(0,1,'x'), self.group_max_pools_l], axis=2) #(batch, hidden, 6)
repeat_origin_input_tensor3_r = T.repeat(origin_input_tensor3_r, psp_size, axis=0 ) #(batch*kerns, hidden, r_len)
biased_conv_model_r = Conv_with_Mask(rng, input_tensor3=repeat_origin_input_tensor3_r*r_max_cos.dimshuffle(0,'x',1),
mask_matrix = repeat_mask_matrix_r,
image_shape=[image_shape_r[0]*psp_size,image_shape_r[1],image_shape_r[2],image_shape_r[3]],
filter_shape=filter_shape, W=W, b=b)
biased_temp_conv_output_r = biased_conv_model_r.naked_conv_out
# self.conv_out_r = biased_conv_model_r.masked_conv_out
# self.maxpool_vec_r = biased_conv_model_r.maxpool_vec
# conv_model_r = Conv_with_Mask(rng, input_tensor3=origin_input_tensor3_r,
# mask_matrix = mask_matrix_r,
# image_shape=image_shape_r,
# filter_shape=filter_shape, W=W, b=b)
# temp_conv_output_r = conv_model_r.naked_conv_out
conv_model_weighted_l = Conv_with_Mask(rng, input_tensor3=weighted_sum_l,
mask_matrix = repeat_mask_matrix_r,
image_shape=[image_shape_r[0]*psp_size,image_shape_r[1],image_shape_r[2],image_shape_r[3]],
filter_shape=filter_shape_context, W=W_context, b=b_context) # note that b_context is not used
temp_conv_output_weighted_l = conv_model_weighted_l.naked_conv_out
'''
combine
'''
mask_for_conv_output_r=T.repeat(repeat_mask_matrix_r.dimshuffle(0,'x',1), filter_shape[0], axis=1) #(batch_size, emb_size, maxSentLen-filter_size+1)
mask_for_conv_output_r=(1.0-mask_for_conv_output_r)*(mask_for_conv_output_r-10)
self.biased_conv_attend_out_r = T.tanh(biased_temp_conv_output_r+ temp_conv_output_weighted_l+ b.dimshuffle('x', 0, 'x'))*repeat_mask_matrix_r.dimshuffle(0,'x',1)
# self.conv_attend_out_r = T.tanh(temp_conv_output_r+ temp_conv_output_weighted_l+ b.dimshuffle('x', 0, 'x'))*mask_matrix_r.dimshuffle(0,'x',1)
# self.attentive_sumpool_vec_r=T.sum(self.conv_attend_out_r, axis=2)
masked_biased_conv_output_r=self.biased_conv_attend_out_r+mask_for_conv_output_r #mutiple mask with the conv_out to set the features by UNK to zero
self.biased_attentive_maxpool_vec_r_psp=T.max(masked_biased_conv_output_r, axis=2) #(batch_size*kerns, hidden_size) # each sentence then have an embedding of length hidden_size
# self.biased_attentive_maxpool_vec_r_psp=T.max(masked_biased_conv_output_r, axis=2).reshape((batch_size, psp_size*hidden_size))
# masked_conv_output_r=self.conv_attend_out_r+mask_for_conv_output_r #mutiple mask with the conv_out to set the features by UNK to zero
# self.attentive_maxpool_vec_r=T.max(masked_conv_output_r, axis=2) #(batch_size, hidden_size) # each sentence then have an embedding of length hidden_size
# self.group_max_pools_r = T.signal.pool.pool_2d(input=self.conv_out_r, ds=(1,10), ignore_border=True) #(batch, hidden, 5)
# self.all_att_maxpool_vecs_r = T.concatenate([self.attentive_maxpool_vec_r.dimshuffle(0,1,'x'), self.group_max_pools_r], axis=2) #(batch, hidden, 6)
def kmaxpooling_tensor3(tensor3, k):
batch_size = tensor3.shape[0]
hidden_size = tensor3.shape[1]
length=tensor3.shape[2]
matrix = tensor3.reshape((batch_size*hidden_size, length))
idsort_matrix = T.argsort(matrix, axis=1)
idsort_topk = idsort_matrix[:,-k:]
restore_id_order_matrix = T.sort(idsort_topk, axis=1) # make y indices in acending lie
ii = T.repeat(T.arange(batch_size*hidden_size), k)
jj = restore_id_order_matrix.flatten()
feature_vec = matrix[ii, jj] # batch_size*hidden_size*k
return feature_vec.reshape((batch_size, k*hidden_size))
class Conv_for_Pair_SoftAttend(object):
"""we define CNN by input tensor3 and output tensor3, like RNN, filter width must by 3,5,7..."""
def __init__(self, rng, origin_input_tensor3, origin_input_tensor3_r, input_tensor3, input_tensor3_r, mask_matrix, mask_matrix_r,
filter_shape, filter_shape_context,image_shape, image_shape_r,W, b, W_context, b_context,
soft_att_W_big, soft_att_b_big,soft_att_W_small):
#construct interaction matrix
input_tensor3 = input_tensor3*mask_matrix.dimshuffle(0,'x',1)
input_tensor3_r = input_tensor3_r*mask_matrix_r.dimshuffle(0,'x',1) #(batch, hidden, r_len)
# dot_mask = T.batched_dot(mask_matrix.dimshuffle(0,1,'x'), mask_matrix_r.dimshuffle(0,'x',1)) #(batch, l_len, r_len)
# dot_tensor3 = T.batched_dot(input_tensor3.dimshuffle(0,2,1),input_tensor3_r) #(batch, l_len, r_len)
#
# self.cosine_tensor3 = dot_tensor3
# self.cosine_tensor3 = dot_tensor3/(1e-8+T.batched_dot(T.sqrt(1e-8+T.sum(input_tensor3**2, axis=1)).dimshuffle(0,1,'x'), T.sqrt(1e-8+T.sum(input_tensor3_r**2, axis=1)).dimshuffle(0,'x', 1)))
# sort_l= T.argsort(self.l_max_cos, axis=1)
# self.l_topK_min_max_cos = self.l_max_cos[T.repeat(T.arange(input_tensor3.shape[0]), 10, axis=0), sort_l[:,:10].flatten()].reshape((input_tensor3.shape[0],10))
# sort_r= T.argsort(self.r_max_cos, axis=1)
# self.r_topK_min_max_cos = self.r_max_cos[T.repeat(T.arange(input_tensor3.shape[0]), 10, axis=0), sort_r[:,:10].flatten()].reshape((input_tensor3.shape[0],10))
'''
soft interaction matrix
'''
Conc_T = T.concatenate([T.extra_ops.repeat(input_tensor3, input_tensor3_r.shape[2], axis=2), T.tile(input_tensor3_r, (1,1,input_tensor3.shape[2]))], axis=1) #(batch, 2hidden, l_len*r_len)
dot_tensor3 = T.tanh(Conc_T.dimshuffle(0,2,1).dot(soft_att_W_big)+soft_att_b_big.dimshuffle('x','x',0)).dot(soft_att_W_small).reshape((input_tensor3.shape[0], input_tensor3.shape[2], input_tensor3_r.shape[2]))#(batch, l_len, r_len)
l_max_cos = T.max(dot_tensor3, axis=2) #(batch, l_len)
r_max_cos = T.max(dot_tensor3, axis=1) #(batch, r_len)
# l_max_cos = 1.0/(1.0+T.max(T.nnet.relu(dot_tensor3), axis=2))##(batch*kerns, l_len)
# r_max_cos = 1.0/(1.0+T.max(T.nnet.relu(dot_tensor3), axis=1))##(batch*kerns, r_len)
# dot_mask=T.cast((1.0-dot_mask)*(dot_mask-100000), 'float32')#(batch, l_len, r_len)
# dot_tensor3 = dot_tensor3 + dot_mask
dot_matrix_for_right = T.nnet.softmax(dot_tensor3.reshape((dot_tensor3.shape[0]*dot_tensor3.shape[1], dot_tensor3.shape[2])))
dot_tensor3_for_right = dot_matrix_for_right.reshape((dot_tensor3.shape[0], dot_tensor3.shape[1], dot_tensor3.shape[2]))#(batch, l_len, r_len)
weighted_sum_r = T.batched_dot(dot_tensor3_for_right, input_tensor3_r.dimshuffle(0,2,1)).dimshuffle(0,2,1)*mask_matrix.dimshuffle(0,'x',1) #(batch,hidden, l_len)
dot_matrix_for_left = T.nnet.softmax(dot_tensor3.dimshuffle(0,2,1).reshape((dot_tensor3.shape[0]*dot_tensor3.shape[2], dot_tensor3.shape[1])))
dot_tensor3_for_left = dot_matrix_for_left.reshape((dot_tensor3.shape[0], dot_tensor3.shape[2], dot_tensor3.shape[1]))#(batch, r_len, l_len)
weighted_sum_l = T.batched_dot(dot_tensor3_for_left, input_tensor3.dimshuffle(0,2,1)).dimshuffle(0,2,1)*mask_matrix_r.dimshuffle(0,'x',1) #(batch,hidden, r_len)
#convolve left, weighted sum r
biased_conv_model_l = Conv_with_Mask(rng, input_tensor3=origin_input_tensor3*l_max_cos.dimshuffle(0,'x',1),
mask_matrix = mask_matrix,
image_shape=image_shape,
filter_shape=filter_shape, W=W, b=b)
biased_temp_conv_output_l = biased_conv_model_l.naked_conv_out
conv_model_l = Conv_with_Mask(rng, input_tensor3=origin_input_tensor3,
mask_matrix = mask_matrix,
image_shape=image_shape,
filter_shape=filter_shape, W=W, b=b)
temp_conv_output_l = conv_model_l.naked_conv_out
self.conv_out_l = conv_model_l.masked_conv_out
self.maxpool_vec_l = conv_model_l.maxpool_vec
self.kmaxpool_vec_l = kmaxpooling_tensor3(self.conv_out_l, 3)
conv_model_weighted_r = Conv_with_Mask(rng, input_tensor3=weighted_sum_r,
mask_matrix = mask_matrix,
image_shape=image_shape,
filter_shape=filter_shape_context, W=W_context, b=b_context) # note that b_context is not used
temp_conv_output_weighted_r = conv_model_weighted_r.naked_conv_out
'''
combine
'''
mask_for_conv_output_l=T.repeat(mask_matrix.dimshuffle(0,'x',1), filter_shape[0], axis=1) #(batch_size, emb_size, maxSentLen-filter_size+1)
mask_for_conv_output_l=(1.0-mask_for_conv_output_l)*(mask_for_conv_output_l-10)
self.biased_conv_attend_out_l = T.tanh(biased_temp_conv_output_l+ temp_conv_output_weighted_r+ b.dimshuffle('x', 0, 'x'))*mask_matrix.dimshuffle(0,'x',1)
masked_biased_conv_output_l=self.biased_conv_attend_out_l+mask_for_conv_output_l #mutiple mask with the conv_out to set the features by UNK to zero
self.biased_attentive_maxpool_vec_l=T.max(masked_biased_conv_output_l, axis=2) #(batch_size, hidden_size) # each sentence then have an embedding of length hidden_size
self.conv_attend_out_l = T.tanh(temp_conv_output_l+ temp_conv_output_weighted_r+ b.dimshuffle('x', 0, 'x'))*mask_matrix.dimshuffle(0,'x',1)
self.attentive_sumpool_vec_l=T.sum(self.conv_attend_out_l, axis=2)
masked_conv_output_l=self.conv_attend_out_l+mask_for_conv_output_l #mutiple mask with the conv_out to set the features by UNK to zero
self.attentive_maxpool_vec_l=T.max(masked_conv_output_l, axis=2) #(batch_size, hidden_size) # each sentence then have an embedding of length hidden_size
self.attentive_kmaxpool_vec_l = kmaxpooling_tensor3(masked_conv_output_l, 3)
#convolve right, weighted sum l
biased_conv_model_r = Conv_with_Mask(rng, input_tensor3=origin_input_tensor3_r*r_max_cos.dimshuffle(0,'x',1),
mask_matrix = mask_matrix_r,
image_shape=image_shape_r,
filter_shape=filter_shape, W=W, b=b)
biased_temp_conv_output_r = biased_conv_model_r.naked_conv_out
conv_model_r = Conv_with_Mask(rng, input_tensor3=origin_input_tensor3_r,
mask_matrix = mask_matrix_r,
image_shape=image_shape_r,
filter_shape=filter_shape, W=W, b=b)
temp_conv_output_r = conv_model_r.naked_conv_out
self.conv_out_r = conv_model_r.masked_conv_out
self.maxpool_vec_r = conv_model_r.maxpool_vec
self.kmaxpool_vec_r = kmaxpooling_tensor3(self.conv_out_r, 3)
conv_model_weighted_l = Conv_with_Mask(rng, input_tensor3=weighted_sum_l,
mask_matrix = mask_matrix_r,
image_shape=image_shape_r,
filter_shape=filter_shape_context, W=W_context, b=b_context) # note that b_context is not used
temp_conv_output_weighted_l = conv_model_weighted_l.naked_conv_out
'''
combine
'''
mask_for_conv_output_r=T.repeat(mask_matrix_r.dimshuffle(0,'x',1), filter_shape[0], axis=1) #(batch_size, emb_size, maxSentLen-filter_size+1)
mask_for_conv_output_r=(1.0-mask_for_conv_output_r)*(mask_for_conv_output_r-10)
self.biased_conv_attend_out_r = T.tanh(biased_temp_conv_output_r+ temp_conv_output_weighted_l+ b.dimshuffle('x', 0, 'x'))*mask_matrix_r.dimshuffle(0,'x',1)
masked_biased_conv_output_r=self.biased_conv_attend_out_r+mask_for_conv_output_r #mutiple mask with the conv_out to set the features by UNK to zero
self.biased_attentive_maxpool_vec_r=T.max(masked_biased_conv_output_r, axis=2) #(batch_size, hidden_size) # each sentence then have an embedding of length hidden_size
self.conv_attend_out_r = T.tanh(temp_conv_output_r+ temp_conv_output_weighted_l+ b.dimshuffle('x', 0, 'x'))*mask_matrix_r.dimshuffle(0,'x',1)
self.attentive_sumpool_vec_r=T.sum(self.conv_attend_out_r, axis=2)
masked_conv_output_r=self.conv_attend_out_r+mask_for_conv_output_r #mutiple mask with the conv_out to set the features by UNK to zero
self.attentive_maxpool_vec_r=T.max(masked_conv_output_r, axis=2) #(batch_size, hidden_size) # each sentence then have an embedding of length hidden_size
self.attentive_kmaxpool_vec_r = kmaxpooling_tensor3(masked_conv_output_r, 3)
class Conv_with_Mask_with_Gate(object):
"""we define CNN by input tensor3 and output tensor3, like RNN, filter width must by 3,5,7..."""
def __init__(self, rng, input_tensor3, mask_matrix, filter_shape, image_shape, W, b, W_gate, b_gate):
conv_layer = Conv_with_Mask(rng, input_tensor3=input_tensor3,
mask_matrix = mask_matrix,
image_shape=image_shape,
filter_shape=filter_shape, W=W, b=b)
gate_layer = Conv_with_Mask(rng, input_tensor3=input_tensor3,
mask_matrix = mask_matrix,
image_shape=image_shape,
filter_shape=filter_shape, W=W_gate, b=b_gate)
self.output_tensor3 = gate_layer.masked_conv_out_sigmoid*input_tensor3+(1.0-gate_layer.masked_conv_out_sigmoid)*conv_layer.masked_conv_out
mask_for_conv_output=T.repeat(mask_matrix.dimshuffle(0,'x',1), filter_shape[0], axis=1) #(batch_size, emb_size, maxSentLen-filter_size+1)
mask_for_conv_output=(1.0-mask_for_conv_output)*(mask_for_conv_output-10)
masked_conv_output=self.output_tensor3+mask_for_conv_output #mutiple mask with the conv_out to set the features by UNK to zero
self.maxpool_vec=T.max(masked_conv_output, axis=2) #(batch_size, hidden_size) # each sentence then have an embedding of length hidden_size
class Conv_with_Mask(object):
"""we define CNN by input tensor3 and output tensor3, like RNN, filter width must by 3,5,7..."""
def __init__(self, rng, input_tensor3, mask_matrix, filter_shape, image_shape, W, b):
assert image_shape[1] == filter_shape[1]
pad_size = filter_shape[3]/2
remain_size = filter_shape[3]%2
zero_pad_tensor4_1 = T.zeros((input_tensor3.shape[0], 1, input_tensor3.shape[1], pad_size), dtype=theano.config.floatX)+1e-8 # to get rid of nan in CNN gradient
input = T.concatenate([zero_pad_tensor4_1,input_tensor3.dimshuffle(0,'x',1,2),
zero_pad_tensor4_1], axis=3) #(batch_size, 1, emb_size, maxsenlen+width-1)
self.input = input
self.W = W
self.b = b
pad_images_shape=(image_shape[0], image_shape[1], image_shape[2], image_shape[3]+2*pad_size)
# convolve input feature maps with filters
conv_out = conv.conv2d(input=input, filters=self.W,
filter_shape=filter_shape, image_shape=pad_images_shape, border_mode='valid') #here, we should pad enough zero padding for input
#no tanh and bias
# conv_with_bias = T.tanh(conv_out + self.b.dimshuffle('x', 0, 'x', 'x'))
# conv_output_tensor3=conv_out.reshape((image_shape[0], filter_shape[0], image_shape[3])) #(batch, 1, kernerl, ishape[1]-filter_size1[1]+1)
if remain_size==0:
conv_out = conv_out[:,:,:,:-1]+conv_out[:,:,:,1:] #(batch, kerns, hidden, len)
self.naked_conv_out=conv_out.reshape((image_shape[0], filter_shape[0], image_shape[3]))*mask_matrix.dimshuffle(0,'x',1) #(batch, hidden_size, len)
#with tank and bias
conv_with_bias = T.tanh(conv_out + self.b.dimshuffle('x', 0, 'x', 'x'))
conv_output_tensor3=conv_with_bias.reshape((image_shape[0], filter_shape[0], image_shape[3])) #(batch, 1, kernerl, ishape[1]-filter_size1[1]+1)
self.masked_conv_out=conv_output_tensor3*mask_matrix.dimshuffle(0,'x',1) #(batch, hidden_size, len)
self.sumpool_vec = T.sum(self.masked_conv_out, axis=2) #(batch, hidden)
conv_with_bias_sigmoid = T.nnet.sigmoid(conv_out + self.b.dimshuffle('x', 0, 'x', 'x'))
conv_output_tensor3_sigmoid=conv_with_bias_sigmoid.reshape((image_shape[0], filter_shape[0], image_shape[3])) #(batch, 1, kernerl, ishape[1]-filter_size1[1]+1)
self.masked_conv_out_sigmoid=conv_output_tensor3_sigmoid*mask_matrix.dimshuffle(0,'x',1) #(batch, hidden_size, len)
mask_for_conv_output=T.repeat(mask_matrix.dimshuffle(0,'x',1), filter_shape[0], axis=1) #(batch_size, emb_size, maxSentLen-filter_size+1)
mask_for_conv_output=(1.0-mask_for_conv_output)*(mask_for_conv_output-10)
masked_conv_output=self.masked_conv_out+mask_for_conv_output #mutiple mask with the conv_out to set the features by UNK to zero
self.masked_conv_out_plus_mask = masked_conv_output
self.maxpool_vec=T.max(self.masked_conv_out_plus_mask, axis=2) #(batch_size, hidden_size) # each sentence then have an embedding of length hidden_size
self.params = [self.W, self.b]
class Conv_with_input_para(object):
"""Pool Layer of a convolutional network """
def __init__(self, rng, input, filter_shape, image_shape, W, b, filter_type='valid'):
assert image_shape[1] == filter_shape[1]
self.input = input
self.W = W
self.b = b
# convolve input feature maps with filters
conv_out = conv.conv2d(input=input, filters=self.W,
filter_shape=filter_shape, image_shape=image_shape, border_mode=filter_type) #here, we should pad enough zero padding for input
# add the bias term. Since the bias is a vector (1D array), we first
# reshape it to a tensor of shape (1,n_filters,1,1). Each bias will
# thus be broadcasted across mini-batches and feature map
# width & height
conv_with_bias = T.tanh(conv_out + self.b.dimshuffle('x', 0, 'x', 'x'))
wide_conv_out=conv_with_bias[:,:,filter_shape[2]-1,:].reshape((image_shape[0], 1, filter_shape[0], image_shape[3]+filter_shape[3]-1))
narrow_conv_out=conv_with_bias.reshape((image_shape[0], 1, filter_shape[0], image_shape[3]-filter_shape[3]+1)) #(batch, 1, kernerl, ishape[1]-filter_size1[1]+1)
self.narrow_conv_out=narrow_conv_out
self.wide_conv_out=wide_conv_out
#pad filter_size-1 zero embeddings at both sides
left_padding = T.zeros((image_shape[0], 1, filter_shape[0], filter_shape[3]-1), dtype=theano.config.floatX)
right_padding = T.zeros((image_shape[0], 1, filter_shape[0], filter_shape[3]-1), dtype=theano.config.floatX)
self.output = T.concatenate([left_padding, narrow_conv_out, right_padding], axis=3)
self.output_max_pooling_vec=T.max(narrow_conv_out.reshape((narrow_conv_out.shape[2], narrow_conv_out.shape[3])), axis=1)
# store parameters of this layer
self.params = [self.W, self.b]
class RNN_with_input_para(object):
"""Pool Layer of a convolutional network """
def __init__(self, rng, input, rnn_Whh, rnn_Wxh, rnn_b, dim):
self.input = input.transpose(1,0) #iterate over first dim
self.Whh = rnn_Whh
self.Wxh=rnn_Wxh
self.b = rnn_b
self.h0 = theano.shared(name='h0',
value=numpy.zeros(dim,
dtype=theano.config.floatX))
def recurrence(x_t, h_tm1):
w_t = T.nnet.sigmoid(T.dot(x_t, self.Wxh)
+ T.dot(h_tm1, self.Whh) + self.b)
h_t=h_tm1*w_t+x_t*(1-w_t)
# s_t = T.nnet.softmax(T.dot(h_t, self.w) + self.b)
return h_t
h, _ = theano.scan(fn=recurrence,
sequences=self.input,
outputs_info=self.h0,#[self.h0, None],
n_steps=self.input.shape[0])
self.output=h.reshape((self.input.shape[0], self.input.shape[1])).transpose(1,0)
# store parameters of this layer
self.params = [self.Whh, self.Wxh, self.b]
def Matrix_Bit_Shift(input_matrix): # shit each column
input_matrix=debug_print(input_matrix, 'input_matrix')
def shift_at_t(t):
shifted_matrix=debug_print(T.concatenate([input_matrix[:,t:], input_matrix[:,:t]], axis=1), 'shifted_matrix')
return shifted_matrix
tensor,_ = theano.scan(fn=shift_at_t,
sequences=T.arange(input_matrix.shape[1]),
n_steps=input_matrix.shape[1])
return tensor
class Bi_GRU_Matrix_Input(object):
def __init__(self, X, word_dim, hidden_dim, U, W, b, U_b, W_b, b_b, bptt_truncate):
self.hidden_dim = hidden_dim
self.bptt_truncate = bptt_truncate
def forward_prop_step(x_t, s_t1_prev):
# GRU Layer 1
z_t1 =T.nnet.sigmoid(U[0].dot(x_t) + W[0].dot(s_t1_prev) + b[0])
r_t1 = T.nnet.sigmoid(U[1].dot(x_t) + W[1].dot(s_t1_prev) + b[1])
c_t1 = T.tanh(U[2].dot(x_t) + W[2].dot(s_t1_prev * r_t1) + b[2])
s_t1 = (T.ones_like(z_t1) - z_t1) * c_t1 + z_t1 * s_t1_prev
return s_t1
s, updates = theano.scan(
forward_prop_step,
sequences=X.transpose(1,0),
truncate_gradient=self.bptt_truncate,
outputs_info=dict(initial=T.zeros(self.hidden_dim)))
# self.output_matrix=debug_print(s.transpose(), 'GRU_Matrix_Input.output_matrix')
# self.output_vector_mean=T.mean(self.output_matrix, axis=1)
# self.output_vector_max=T.max(self.output_matrix, axis=1)
# self.output_vector_last=self.output_matrix[:,-1]
#backward
X_b=X[:,::-1]
def backward_prop_step(x_t_b, s_t1_prev_b):
# GRU Layer 1
z_t1_b =T.nnet.sigmoid(U_b[0].dot(x_t_b) + W_b[0].dot(s_t1_prev_b) + b_b[0])
r_t1_b = T.nnet.sigmoid(U_b[1].dot(x_t_b) + W_b[1].dot(s_t1_prev_b) + b_b[1])
c_t1_b = T.tanh(U_b[2].dot(x_t_b) + W_b[2].dot(s_t1_prev_b * r_t1_b) + b_b[2])
s_t1_b = (T.ones_like(z_t1_b) - z_t1_b) * c_t1_b + z_t1_b * s_t1_prev_b
return s_t1_b
s_b, updates_b = theano.scan(
backward_prop_step,
sequences=X_b.transpose(1,0),
truncate_gradient=self.bptt_truncate,
outputs_info=dict(initial=T.zeros(self.hidden_dim)))
#dim: hidden_dim*2
# output_matrix=T.concatenate([s.transpose(), s_b.transpose()[:,::-1]], axis=0)
output_matrix=s.transpose()+s_b.transpose()[:,::-1]
self.output_matrix=output_matrix+X # add input feature maps
self.output_vector_mean=T.mean(self.output_matrix, axis=1)
self.output_vector_max=T.max(self.output_matrix, axis=1)
#dim: hidden_dim*4
self.output_vector_last=T.concatenate([self.output_matrix[:,-1], self.output_matrix[:,0]], axis=0)
class Bi_GRU_Tensor3_Input(object):
def __init__(self, T, lefts, rights, hidden_dim, U, W, b, Ub,Wb,bb):
T=debug_print(T,'T')
lefts=debug_print(lefts, 'lefts')
rights=debug_print(rights, 'rights')
def recurrence(matrix, left, right):
sub_matrix=debug_print(matrix[:,left:-right], 'sub_matrix')
GRU_layer=Bi_GRU_Matrix_Input(sub_matrix, sub_matrix.shape[0], hidden_dim,U,W,b, Ub,Wb,bb, -1)
return GRU_layer.output_vector_mean
new_M, updates = theano.scan(recurrence,
sequences=[T, lefts, rights],
outputs_info=None)
self.output=debug_print(new_M.transpose(), 'Bi_GRU_Tensor3_Input.output')
class GRU_Matrix_Input(object):
def __init__(self, X, word_dim, hidden_dim, U, W, b, bptt_truncate):
self.hidden_dim = hidden_dim
self.bptt_truncate = bptt_truncate
def forward_prop_step(x_t, s_t1_prev):
# GRU Layer 1
z_t1 =debug_print( T.nnet.sigmoid(U[0].dot(x_t) + W[0].dot(s_t1_prev) + b[0]), 'z_t1')
r_t1 = debug_print(T.nnet.sigmoid(U[1].dot(x_t) + W[1].dot(s_t1_prev) + b[1]), 'r_t1')
c_t1 = debug_print(T.tanh(U[2].dot(x_t) + W[2].dot(s_t1_prev * r_t1) + b[2]), 'c_t1')
s_t1 = debug_print((T.ones_like(z_t1) - z_t1) * c_t1 + z_t1 * s_t1_prev, 's_t1')
return s_t1
s, updates = theano.scan(
forward_prop_step,