-
Notifications
You must be signed in to change notification settings - Fork 6
/
csu_model.py
2005 lines (1603 loc) · 81.7 KB
/
csu_model.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
"""
Store modular components for Jupyter Notebook
"""
import json
import numpy as np
import os
import csv
import logging
import random
import math
from sklearn import metrics
from scipy import stats
from os.path import join as pjoin
from scipy.special import expit as sigmoid
from collections import defaultdict
from itertools import combinations, izip
import torch
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from torch.nn.utils.rnn import pad_packed_sequence as unpack
from torchtext import data
from util import MultiLabelField, ReversibleField, BCEWithLogitsLoss, MultiMarginHierarchyLoss
def get_ci(vals, return_range=False):
if len(set(vals)) == 1:
return (vals[0], vals[0])
loc = np.mean(vals)
scale = np.std(vals) / np.sqrt(len(vals))
range_0, range_1 = stats.t.interval(0.95, len(vals) - 1, loc=loc, scale=scale)
if return_range:
return range_0, range_1
else:
return range_1 - loc
class Config(dict):
def __init__(self, **kwargs):
super(Config, self).__init__(**kwargs)
self.__dict__.update(**kwargs)
def __setitem__(self, key, item):
self.__dict__[key] = item
def __getitem__(self, key):
return self.__dict__[key]
def __repr__(self):
return repr(self.__dict__)
def __len__(self):
return len(self.__dict__)
def __delitem__(self, key):
del self.__dict__[key]
def clear(self):
return self.__dict__.clear()
def copy(self):
return self.__dict__.copy()
def has_key(self, k):
return k in self.__dict__
def update(self, *args, **kwargs):
return self.__dict__.update(*args, **kwargs)
def keys(self):
return self.__dict__.keys()
def values(self):
return self.__dict__.values()
def items(self):
return self.__dict__.items()
def pop(self, *args):
return self.__dict__.pop(*args)
def __cmp__(self, dict_):
return self.__cmp__(self.__dict__, dict_)
def __contains__(self, item):
return item in self.__dict__
def __iter__(self):
return iter(self.__dict__)
def __unicode__(self):
return unicode(repr(self.__dict__))
# then we can make special class for different types of model
# each config is used to build a classifier and a trainer, so one for each
class LSTMBaseConfig(Config):
def __init__(self, emb_dim=100, hidden_size=512, depth=1, label_size=42, bidir=False,
c=False, m=False, co=False,
dropout=0.2, emb_update=True, clip_grad=5., seed=1234,
rand_unk=True, run_name="default", emb_corpus="gigaword", avg_run_times=1,
conv_enc=0,
**kwargs):
# run_name: the folder for the trainer
# c: cluster, m: meta, co: co-occurence constraint
super(LSTMBaseConfig, self).__init__(emb_dim=emb_dim,
hidden_size=hidden_size,
depth=depth,
label_size=label_size,
bidir=bidir,
c=c,
m=m,
co=co,
dropout=dropout,
emb_update=emb_update,
clip_grad=clip_grad,
seed=seed,
rand_unk=rand_unk,
run_name=run_name,
emb_corpus=emb_corpus,
avg_run_times=avg_run_times,
conv_enc=conv_enc,
**kwargs)
class LSTM_w_C_Config(LSTMBaseConfig):
def __init__(self, sigma_M, sigma_B, sigma_W, **kwargs):
super(LSTM_w_C_Config, self).__init__(sigma_M=sigma_M,
sigma_B=sigma_B,
sigma_W=sigma_W,
c=True,
**kwargs)
class LSTM_w_M_Config(LSTMBaseConfig):
def __init__(self, beta, **kwargs):
super(LSTM_w_M_Config, self).__init__(beta=beta, m=True, **kwargs)
class LSTM_w_Co_config(LSTMBaseConfig):
def __init__(self, x_max=100, alpha=0.75, gamma=1e-3, use_csu=True,
use_pp=False, glove=False, ppmi=False,
**kwargs):
"""
:param x_max: int (default: 100)
Words with frequency greater than this are given weight 1.0.
Words with frequency under this are given weight (c/xmax)**alpha
where c is their count in mat (see the paper, eq. (9)).
:param alpha: float (default: 0.75)
Exponent in the weighting function (see the paper, eq. (9)).
:param gamma: float(default=1e-3)
The strength of this penalty
:param use_csu: use co-occurence frequency from CSU
:param use_pp: use co-occurence frequency from PP
:param glove: use GlOVE style loss, otherwise
:param ppmi: we want this to be false because if it's negative, then we want that too
:param kwargs:
"""
super(LSTM_w_Co_config, self).__init__(co=True,
x_max=x_max,
alpha=alpha,
gamma=gamma,
use_csu=use_csu,
use_pp=use_pp,
glove=glove,
ppmi=ppmi,
**kwargs)
"""
Hierarchical ConvNet
"""
class ConvNetEncoder(nn.Module):
def __init__(self, config):
super(ConvNetEncoder, self).__init__()
self.word_emb_dim = config['word_emb_dim']
self.enc_lstm_dim = config['enc_lstm_dim']
self.convnet1 = nn.Sequential(
nn.Conv1d(self.word_emb_dim, 2 * self.enc_lstm_dim, kernel_size=3,
stride=1, padding=1),
nn.ReLU(inplace=True),
)
self.convnet2 = nn.Sequential(
nn.Conv1d(2 * self.enc_lstm_dim, 2 * self.enc_lstm_dim, kernel_size=3,
stride=1, padding=1),
nn.ReLU(inplace=True),
)
self.convnet3 = nn.Sequential(
nn.Conv1d(2 * self.enc_lstm_dim, 2 * self.enc_lstm_dim, kernel_size=3,
stride=1, padding=1),
nn.ReLU(inplace=True),
)
self.convnet4 = nn.Sequential(
nn.Conv1d(2 * self.enc_lstm_dim, 2 * self.enc_lstm_dim, kernel_size=3,
stride=1, padding=1),
nn.ReLU(inplace=True),
)
def forward(self, sent_tuple):
# sent_len: [max_len, ..., min_len] (batch)
# sent: Variable(seqlen x batch x worddim)
sent, sent_len = sent_tuple
sent = sent.transpose(0, 1).transpose(1, 2).contiguous()
# batch, nhid, seqlen)
sent = self.convnet1(sent)
u1 = torch.max(sent, 2)[0]
sent = self.convnet2(sent)
u2 = torch.max(sent, 2)[0]
sent = self.convnet3(sent)
u3 = torch.max(sent, 2)[0]
sent = self.convnet4(sent)
u4 = torch.max(sent, 2)[0]
emb = torch.cat((u1, u2, u3, u4), 1)
return emb
"""
Normal ConvNet
"""
class NormalConvNetEncoder(nn.Module):
def __init__(self, config):
super(NormalConvNetEncoder, self).__init__()
self.word_emb_dim = config['word_emb_dim']
self.enc_lstm_dim = config['enc_lstm_dim']
self.conv = nn.Conv2d(in_channels=1, out_channels=self.enc_lstm_dim, kernel_size=(3, self.word_emb_dim),
stride=(1, self.word_emb_dim))
def encode(self, inputs):
output = inputs.transpose(0, 1).unsqueeze(1) # [batch_size, in_kernel, seq_length, embed_dim]
output = F.relu(self.conv(output)) # conv -> [batch_size, out_kernel, seq_length, 1]
output = output.squeeze(3).max(2)[0] # max_pool -> [batch_size, out_kernel]
return output
def forward(self, sent_tuple):
# sent_len: [max_len, ..., min_len] (batch)
# sent: Variable(seqlen x batch x worddim)
sent, sent_len = sent_tuple
emb = self.encode(sent)
return emb
"""
https://github.com/Shawn1993/cnn-text-classification-pytorch/blob/master/model.py
352 stars
"""
class CNN_Text_Encoder(nn.Module):
def __init__(self, config):
super(CNN_Text_Encoder, self).__init__()
self.word_emb_dim = config['word_emb_dim']
# V = args.embed_num
# D = args.embed_dim
# C = args.class_num
Ci = 1
Co = config['kernel_num'] # 100
Ks = config['kernel_sizes'] # '3,4,5'
# len(Ks)*Co
# self.convs1 = [nn.Conv2d(Ci, Co, (K, D)) for K in Ks]
self.convs1 = nn.ModuleList([nn.Conv2d(Ci, Co, (K, self.word_emb_dim)) for K in Ks])
'''
self.conv13 = nn.Conv2d(Ci, Co, (3, D))
self.conv14 = nn.Conv2d(Ci, Co, (4, D))
self.conv15 = nn.Conv2d(Ci, Co, (5, D))
'''
# self.dropout = nn.Dropout(args.dropout)
# self.fc1 = nn.Linear(len(Ks) * Co, C)
def conv_and_pool(self, x, conv):
x = F.relu(conv(x)).squeeze(3) # (N, Co, W)
x = F.max_pool1d(x, x.size(2)).squeeze(2)
return x
def forward(self, x):
# x = self.embed(x) # (N, W, D)
x = x[0].transpose(0, 1).unsqueeze(1)
# x = x.unsqueeze(1) # (N, Ci, W, D)
x = [F.relu(conv(x)).squeeze(3) for conv in self.convs1] # [(N, Co, W), ...]*len(Ks)
x = [F.max_pool1d(i, i.size(2)).squeeze(2) for i in x] # [(N, Co), ...]*len(Ks)
x = torch.cat(x, 1)
'''
x1 = self.conv_and_pool(x,self.conv13) #(N,Co)
x2 = self.conv_and_pool(x,self.conv14) #(N,Co)
x3 = self.conv_and_pool(x,self.conv15) #(N,Co)
x = torch.cat((x1, x2, x3), 1) # (N,len(Ks)*Co)
'''
# x = self.dropout(x) # (N, len(Ks)*Co)
# logit = self.fc1(x) # (N, C)
return x
class Classifier(nn.Module):
def __init__(self, vocab, config):
super(Classifier, self).__init__()
self.config = config
self.drop = nn.Dropout(config.dropout) # embedding dropout
if config.conv_enc == 1:
kernel_size = config.hidden_size / 8
print(kernel_size)
self.encoder = ConvNetEncoder({
'word_emb_dim': config.emb_dim,
'enc_lstm_dim': kernel_size if not config.bidir else kernel_size * 2
})
d_out = config.hidden_size if not config.bidir else config.hidden_size * 2
elif config.conv_enc == 2:
kernel_size = config.hidden_size
print(kernel_size)
self.encoder = NormalConvNetEncoder({
'word_emb_dim': config.emb_dim,
'enc_lstm_dim': kernel_size if not config.bidir else kernel_size * 2
})
d_out = config.hidden_size if not config.bidir else config.hidden_size * 2
elif config.conv_enc == 3:
kernel_num = config.hidden_size / 3
kernel_num = kernel_num if not config.bidir else kernel_num * 2
self.encoder = CNN_Text_Encoder({
'word_emb_dim': config.emb_dim,
'kernel_sizes': [3, 4, 5],
'kernel_num': kernel_num
})
d_out = len([3, 4, 5]) * kernel_num
else:
self.encoder = nn.LSTM(
config.emb_dim,
config.hidden_size,
config.depth,
dropout=config.dropout,
bidirectional=config.bidir) # ha...not even bidirectional
d_out = config.hidden_size if not config.bidir else config.hidden_size * 2
self.out = nn.Linear(d_out, config.label_size) # include bias, to prevent bias assignment
self.embed = nn.Embedding(len(vocab), config.emb_dim)
self.embed.weight.data.copy_(vocab.vectors)
self.embed.weight.requires_grad = True if config.emb_update else False
def forward(self, input, lengths=None):
output_vecs = self.get_vectors(input, lengths)
return self.get_logits(output_vecs)
def get_vectors(self, input, lengths=None):
embed_input = self.embed(input)
if self.config.conv_enc:
output = self.encoder((embed_input, lengths.view(-1).tolist()))
return output
packed_emb = embed_input
if lengths is not None:
lengths = lengths.view(-1).tolist()
packed_emb = nn.utils.rnn.pack_padded_sequence(embed_input, lengths)
output, hidden = self.encoder(packed_emb) # embed_input
if lengths is not None:
output = unpack(output)[0]
# we ignored negative masking
return output
def get_logits(self, output_vec):
if self.config.conv_enc:
output = output_vec
else:
output = torch.max(output_vec, 0)[0].squeeze(0)
return self.out(output)
def get_softmax_weight(self):
return self.out.weight
"""
Interpretation module
"""
def propagate_three(a, b, c, activation):
a_contrib = 0.5 * (activation(a + c) - activation(c) +
activation(a + b + c) - activation(b + c))
b_contrib = 0.5 * (activation(b + c) - activation(c) +
activation(a + b + c) - activation(a + c))
return a_contrib, b_contrib, activation(c)
# propagate tanh nonlinearity
def propagate_tanh_two(a, b):
return 0.5 * (np.tanh(a) + (np.tanh(a + b) - np.tanh(b))), 0.5 * (np.tanh(b) + (np.tanh(a + b) - np.tanh(a)))
def propagate_max_two(a, b, d=0):
# need to return a, b with the same shape...
indices = np.argmax(a + b, axis=d)
a_mask = np.zeros_like(a)
a_mask[indices, np.arange(a.shape[1])] = 1
a = a * a_mask
b_mask = np.zeros_like(b)
b_mask[indices, np.arange(b.shape[1])] = 1
b = b * b_mask
return a, b
class BaseLSTM(object):
def __init__(self, model, bilstm=False):
self.model = model
weights = model.encoder.state_dict()
self.optimizer = torch.optim.SGD(self.model.parameters(), 0.1)
self.hidden_dim = model.config.hidden_size
self.W_ii, self.W_if, self.W_ig, self.W_io = np.split(
weights['weight_ih_l0'], 4, 0)
self.W_hi, self.W_hf, self.W_hg, self.W_ho = np.split(
weights['weight_hh_l0'], 4, 0)
self.b_i, self.b_f, self.b_g, self.b_o = np.split(
weights['bias_ih_l0'].numpy() + weights['bias_hh_l0'].numpy(),
4)
if bilstm:
self.rev_W_ii, self.rev_W_if, self.rev_W_ig, self.rev_W_io = np.split(
weights['weight_ih_l0_reverse'], 4, 0)
self.rev_W_hi, self.rev_W_hf, self.rev_W_hg, self.rev_W_ho = np.split(
weights['weight_hh_l0_reverse'], 4, 0)
self.rev_b_i, self.rev_b_f, self.rev_b_g, self.rev_b_o = np.split(
weights['bias_ih_l0_reverse'].numpy(
) + weights['bias_hh_l0_reverse'].numpy(),
4)
self.word_emb_dim = 100
self.classifiers = [
(self.model.out.weight.data.numpy(),
self.model.out.bias.data.numpy())
]
def zero_grad(self):
self.optimizer.zero_grad()
def classify(self, final_res):
# note that u, v could be positional!! don't mix the two
for c in self.classifiers:
w, b = c
final_res = np.dot(w, final_res) + b
return final_res
class MaxPoolingCDBiLSTM(BaseLSTM):
def cell(self, prev_h, prev_c, x_i):
# x_i = word_vecs[i]
rel_i = np.dot(self.W_hi, prev_h)
rel_g = np.dot(self.W_hg, prev_h)
rel_f = np.dot(self.W_hf, prev_h)
rel_o = np.dot(self.W_ho, prev_h)
rel_i = sigmoid(rel_i + np.dot(self.W_ii, x_i) + self.b_i)
rel_g = np.tanh(rel_g + np.dot(self.W_ig, x_i) + self.b_g)
rel_f = sigmoid(rel_f + np.dot(self.W_if, x_i) + self.b_f)
rel_o = sigmoid(rel_o + np.dot(self.W_io, x_i) + self.b_o)
c_t = rel_f * prev_c + rel_i * rel_g
h_t = rel_o * np.tanh(c_t)
return h_t, c_t
def rev_cell(self, prev_h, prev_c, x_i):
# x_i = word_vecs[i]
rel_i = np.dot(self.rev_W_hi, prev_h)
rel_g = np.dot(self.rev_W_hg, prev_h)
rel_f = np.dot(self.rev_W_hf, prev_h)
rel_o = np.dot(self.rev_W_ho, prev_h)
rel_i = sigmoid(rel_i + np.dot(self.rev_W_ii, x_i) + self.rev_b_i)
rel_g = np.tanh(rel_g + np.dot(self.rev_W_ig, x_i) + self.rev_b_g)
rel_f = sigmoid(rel_f + np.dot(self.rev_W_if, x_i) + self.rev_b_f)
rel_o = sigmoid(rel_o + np.dot(self.rev_W_io, x_i) + self.rev_b_o)
c_t = rel_f * prev_c + rel_i * rel_g
h_t = rel_o * np.tanh(c_t)
return h_t, c_t
def run_bi_lstm(self, sent):
# this is used as validation
# sent: [legnth, dim=100]
word_vecs = sent
T = word_vecs.shape[0]
hidden_states = np.zeros((T, self.hidden_dim))
rev_hidden_states = np.zeros((T, self.hidden_dim))
cell_states = np.zeros((T, self.hidden_dim))
rev_cell_states = np.zeros((T, self.hidden_dim))
for i in range(T):
if i > 0:
# this is just the prev hidden state
prev_h = hidden_states[i - 1]
prev_c = cell_states[i - 1]
else:
prev_h = np.zeros(self.hidden_dim)
prev_c = np.zeros(self.hidden_dim)
new_h, new_c = self.cell(prev_h, prev_c, word_vecs[i])
hidden_states[i] = new_h
cell_states[i] = new_c
for i in reversed(range(T)):
# 20, 19, 18, 17, ...
if i < T - 1:
# this is just the prev hidden state
prev_h = rev_hidden_states[i + 1]
prev_c = rev_cell_states[i + 1]
else:
prev_h = np.zeros(self.hidden_dim)
prev_c = np.zeros(self.hidden_dim)
new_h, new_c = self.rev_cell(prev_h, prev_c, word_vecs[i])
rev_hidden_states[i] = new_h
rev_cell_states[i] = new_c
# stack second dimension
return np.hstack([hidden_states, rev_hidden_states]), np.hstack([cell_states, rev_cell_states])
def get_word_level_scores(self, sentence, sentence_len, label_idx):
"""
:param sentence: word embeddings of [T, d]
:return:
"""
# texts = gen_tiles(text_orig, method='cd', sweep_dim=1).transpose()
# starts, stops = tiles_to_cd(texts)
# [0, 1, 2,...], [0, 1, 2,...]
self.zero_grad()
# contextual decomposition
rel_A, irrel_A = self.cd_encode(sentence) # already masked
# Gradient part!
# now we actually fire up the encoder, and get gradients w.r.t. hidden states
# run the actual model to compute gradients
sentence_emb = self.model.embed(sentence)
lengths = sentence_len.view(-1).tolist()
output, hidden = self.model.encoder(sentence_emb)
# output_vec = unpack(output)[0]
sent_output = torch.max(output, 0)[0].squeeze(0)
clf_output = self.model.out(sent_output)
# output_vec is the hidden states we want!! (T, hid_state_dim)
# TODO: fix this part
# y = clf_output[label_idx]
# label_id = torch.max(clf_output, 0)[1]
# compute A score
y = clf_output[label_idx]
grad = torch.autograd.grad(y, output, retain_graph=True)[0]
scores_A = grad.data.squeeze() * torch.from_numpy(rel_A).float()
# (sent_len, num_label)
return scores_A.sum(dim=1), clf_output
def extract_keywords(self, sentence, sentence_len, dataset, score_values, label_keyword_dict, label_size=42, threshold=0.2):
# sentence: x
# sentence_len: x_len
# text_score_tup_list: [('surgery', 4.0), ...]
self.zero_grad()
# contextual decomposition
rel_A, irrel_A = self.cd_encode(sentence) # already masked
# Gradient part!
# now we actually fire up the encoder, and get gradients w.r.t. hidden states
# run the actual model to compute gradients
sentence_emb = self.model.embed(sentence)
lengths = sentence_len.view(-1).tolist()
# packed_emb = nn.utils.rnn.pack_padded_sequence(sentence_emb, lengths)
# output, hidden = self.model.encoder(packed_emb)
output, hidden = self.model.encoder(sentence_emb)
# output_vec = unpack(output)[0]
sent_output = torch.max(output, 0)[0].squeeze(0)
clf_output = self.model.out(sent_output)
# output_vec is the hidden states we want!! (T, hid_state_dim)
# y = clf_output[label_idx]
# label_id = torch.max(clf_output, 0)[1]
text = [dataset.TEXT.vocab.itos[idx] for idx in sentence.data]
# compute A score
for label_idx in range(label_size):
self.zero_grad()
y = clf_output[label_idx]
grad = torch.autograd.grad(y, output, retain_graph=True)[0]
scores_A = grad.data.squeeze() * torch.from_numpy(rel_A).float()
scores_A = scores_A.sum(dim=1).data.squeeze().numpy().tolist()
assert len(scores_A) == len(text)
score_values.extend(scores_A)
for g, t in zip(scores_A, text):
if g > threshold:
label_keyword_dict[label_idx].append(t)
# we don't return anything :)
return
def cd_encode(self, sentences):
rel_h, irrel_h, _ = self.flat_cd_text(sentences)
rev_rel_h, rev_irrel_h, _ = self.flat_cd_text(sentences, reverse=True)
rel = np.hstack([rel_h, rev_rel_h]) # T, 2*d
irrel = np.hstack([irrel_h, rev_irrel_h]) # T, 2*d
# again, hidden-states = rel + irrel
# we mask both
rel_masked, irrel_masked = propagate_max_two(rel, irrel)
# (2*d), actual sentence representation
return rel_masked, irrel_masked
def flat_cd_text(self, sentence, reverse=False):
# collects relevance for word 0 to sent_length
# not considering interactions between words; merely collecting word contribution
# word_vecs = self.model.embed(batch.text)[:, 0].data
word_vecs = self.model.embed(sentence).squeeze().data.numpy()
T = word_vecs.shape[0]
# so prev_h is always irrelevant
# there's no rel_h because we only look at each time step individually
# relevant cell states, irrelevant cell states
relevant = np.zeros((T, self.hidden_dim))
irrelevant = np.zeros((T, self.hidden_dim))
relevant_h = np.zeros((T, self.hidden_dim))
# keep track of the entire hidden state
irrelevant_h = np.zeros((T, self.hidden_dim))
hidden_states = np.zeros((T, self.hidden_dim))
cell_states = np.zeros((T, self.hidden_dim))
if not reverse:
W_ii, W_if, W_ig, W_io = self.W_ii, self.W_if, self.W_ig, self.W_io
W_hi, W_hf, W_hg, W_ho = self.W_hi, self.W_hf, self.W_hg, self.W_ho
b_i, b_f, b_g, b_o = self.b_i, self.b_f, self.b_g, self.b_o
else:
W_ii, W_if, W_ig, W_io = self.rev_W_ii, self.rev_W_if, self.rev_W_ig, self.rev_W_io
W_hi, W_hf, W_hg, W_ho = self.rev_W_hi, self.rev_W_hf, self.rev_W_hg, self.rev_W_ho
b_i, b_f, b_g, b_o = self.rev_b_i, self.rev_b_f, self.rev_b_g, self.rev_b_o
# strategy: keep using prev_h as irrel_h
# every time, make sure h = irrel + rel, then prev_h = h
indices = range(T) if not reverse else reversed(range(T))
for i in indices:
first_cond = i > 0 if not reverse else i < T - 1
if first_cond:
ret_idx = i - 1 if not reverse else i + 1
prev_c = cell_states[ret_idx]
prev_h = hidden_states[ret_idx]
else:
prev_c = np.zeros(self.hidden_dim)
prev_h = np.zeros(self.hidden_dim)
irrel_i = np.dot(W_hi, prev_h)
irrel_g = np.dot(W_hg, prev_h)
irrel_f = np.dot(W_hf, prev_h)
irrel_o = np.dot(W_ho, prev_h)
rel_i = np.dot(W_ii, word_vecs[i])
rel_g = np.dot(W_ig, word_vecs[i])
rel_f = np.dot(W_if, word_vecs[i])
rel_o = np.dot(W_io, word_vecs[i])
# this remains unchanged
rel_contrib_i, irrel_contrib_i, bias_contrib_i = propagate_three(
rel_i, irrel_i, b_i, sigmoid)
rel_contrib_g, irrel_contrib_g, bias_contrib_g = propagate_three(
rel_g, irrel_g, b_g, np.tanh)
relevant[i] = rel_contrib_i * (rel_contrib_g + bias_contrib_g) + \
bias_contrib_i * rel_contrib_g
irrelevant[i] = irrel_contrib_i * (rel_contrib_g + irrel_contrib_g + bias_contrib_g) + \
(rel_contrib_i + bias_contrib_i) * irrel_contrib_g
relevant[i] += bias_contrib_i * bias_contrib_g
# if i >= start and i < stop:
# relevant[i] += bias_contrib_i * bias_contrib_g
# else:
# irrelevant[i] += bias_contrib_i * bias_contrib_g
cond = i > 0 if not reverse else i < T - 1
if cond:
rel_contrib_f, irrel_contrib_f, bias_contrib_f = propagate_three(
rel_f, irrel_f, b_f, sigmoid)
# not sure if this is completely correct
irrelevant[i] += (rel_contrib_f +
irrel_contrib_f + bias_contrib_f) * prev_c
# recompute o-gate
o = sigmoid(rel_o + irrel_o + b_o)
rel_contrib_o, irrel_contrib_o, bias_contrib_o = propagate_three(
rel_o, irrel_o, b_o, sigmoid)
# from current cell state
new_rel_h, new_irrel_h = propagate_tanh_two(
relevant[i], irrelevant[i])
# relevant_h[i] = new_rel_h * (rel_contrib_o + bias_contrib_o)
# irrelevant_h[i] = new_rel_h * (irrel_contrib_o) + new_irrel_h * (rel_contrib_o + irrel_contrib_o + bias_contrib_o)
relevant_h[i] = o * new_rel_h
irrelevant_h[i] = o * new_irrel_h
hidden_states[i] = relevant_h[i] + irrelevant_h[i]
cell_states[i] = relevant[i] + irrelevant[i]
return relevant_h, irrelevant_h, hidden_states
# this dataset can also take in 5-class classification
class Dataset(object):
def __init__(self, path='./data/csu/',
dataset_prefix='snomed_multi_label_no_des_',
# test_data_name='adobe_abbr_matched_snomed_multi_label_no_des_test.tsv',
test_data_name='adobe_combined_abbr_matched_snomed_multi_label_no_des_test.tsv',
# change this to 'adobe_combined_abbr_matched_snomed_multi_label_no_des_test.tsv'
label_size=42, fix_length=None):
self.TEXT = ReversibleField(sequential=True, include_lengths=True, lower=False, fix_length=fix_length)
self.LABEL = MultiLabelField(sequential=True, use_vocab=False, label_size=label_size,
tensor_type=torch.FloatTensor, fix_length=fix_length)
# it's actually this step that will take 5 minutes
self.train, self.val, self.test = data.TabularDataset.splits(
path=path, train=dataset_prefix + 'train.tsv',
validation=dataset_prefix + 'valid.tsv',
test=dataset_prefix + 'test.tsv', format='tsv',
fields=[('Text', self.TEXT), ('Description', self.LABEL)])
self.external_test = data.TabularDataset(path=path + test_data_name,
format='tsv',
fields=[('Text', self.TEXT), ('Description', self.LABEL)])
self.is_vocab_bulit = False
self.iterators = []
self.test_iterator = None
def init_emb(self, vocab, init="randn", num_special_toks=2, silent=False):
# we can try randn or glorot
# mode="unk"|"all", all means initialize everything
emb_vectors = vocab.vectors
sweep_range = len(vocab)
running_norm = 0.
num_non_zero = 0
total_words = 0
for i in range(num_special_toks, sweep_range):
if len(emb_vectors[i, :].nonzero()) == 0:
# std = 0.5 is based on the norm of average GloVE word vectors
if init == "randn":
torch.nn.init.normal(emb_vectors[i], mean=0, std=0.5)
else:
num_non_zero += 1
running_norm += torch.norm(emb_vectors[i])
total_words += 1
if not silent:
print("average GloVE norm is {}, number of known words are {}, total number of words are {}".format(
running_norm / num_non_zero, num_non_zero, total_words)) # directly printing into Jupyter Notebook
def build_vocab(self, config, silent=False):
if config.emb_corpus == 'common_crawl':
self.TEXT.build_vocab(self.train, vectors="glove.840B.300d")
config.emb_dim = 300 # change the config emb dimension
else:
self.TEXT.build_vocab(self.train, vectors="glove.6B.{}d".format(config.emb_dim))
self.is_vocab_bulit = True
self.vocab = self.TEXT.vocab
if config.rand_unk:
if not silent:
print("initializing random vocabulary")
self.init_emb(self.vocab, silent=silent)
def get_iterators(self, device, val_batch_size=128):
if not self.is_vocab_bulit:
raise Exception("Vocabulary is not built yet..needs to call build_vocab()")
if len(self.iterators) > 0:
return self.iterators # return stored iterator
# only get them after knowing the device (inside trainer or evaluator)
train_iter, val_iter, test_iter = data.Iterator.splits(
(self.train, self.val, self.test), sort_key=lambda x: len(x.Text), # no global sort, but within-batch-sort
batch_sizes=(32, val_batch_size, val_batch_size), device=device,
sort_within_batch=True, repeat=False)
return train_iter, val_iter, test_iter
def get_test_iterator(self, device):
if not self.is_vocab_bulit:
raise Exception("Vocabulary is not built yet..needs to call build_vocab()")
if self.test_iterator is not None:
return self.test_iterator
external_test_iter = data.Iterator(self.external_test, 128, sort_key=lambda x: len(x.Text),
device=device, train=False, repeat=False, sort_within_batch=True)
return external_test_iter
def get_lm_iterator(self, device):
# get language modeling data iterators
pass
# compute loss
class ClusterLoss(nn.Module):
def __init__(self, config, cluster_path='./data/csu/snomed_label_to_meta_grouping.json'):
super(ClusterLoss, self).__init__()
with open(cluster_path, 'rb') as f:
label_grouping = json.load(f)
self.meta_category_groups = label_grouping.values()
self.config = config
def forward(self, softmax_weight, batch_size):
w_bar = softmax_weight.sum(1) / self.config.label_size # w_bar
omega_mean = softmax_weight.pow(2).sum()
omega_between = 0.
omega_within = 0.
for c in xrange(len(self.meta_category_groups)):
m_c = len(self.meta_category_groups[c])
w_c_bar = softmax_weight[:, self.meta_category_groups[c]].sum(1) / m_c
omega_between += m_c * (w_c_bar - w_bar).pow(2).sum()
for i in self.meta_category_groups[c]:
# this value will be 0 for singleton group
omega_within += (softmax_weight[:, i] - w_c_bar).pow(2).sum()
aux_loss = omega_mean * self.config.sigma_M + (omega_between * self.config.sigma_B +
omega_within * self.config.sigma_W) / batch_size
return aux_loss
class MetaLoss(nn.Module):
def __init__(self, config, cluster_path='./data/csu/snomed_label_to_meta_grouping.json',
label_to_meta_map_path='./data/csu/snomed_label_to_meta_map.json'):
super(MetaLoss, self).__init__()
with open(cluster_path, 'rb') as f:
self.label_grouping = json.load(f)
with open(label_to_meta_map_path, 'rb') as f:
self.meta_label_mapping = json.load(f)
self.meta_label_size = len(self.label_grouping)
self.config = config
# your original classifier did this wrong...found a bug
self.bce_loss = nn.BCELoss() # this takes in probability (after sigmoid)
# now that this becomes somewhat independent...maybe you can examine this more closely?
def generate_meta_y(self, indices, meta_label_size, batch_size):
a = np.array([[0.] * meta_label_size for _ in range(batch_size)], dtype=np.float32)
matched = defaultdict(set)
for b, l in indices:
if b not in matched:
a[b, self.meta_label_mapping[str(l)]] = 1.
matched[b].add(self.meta_label_mapping[str(l)])
elif self.meta_label_mapping[str(l)] not in matched[b]:
a[b, self.meta_label_mapping[str(l)]] = 1.
matched[b].add(self.meta_label_mapping[str(l)])
assert np.sum(a <= 1) == a.size
return a
def forward(self, logits, true_y, device):
batch_size = logits.size(0)
y_hat = torch.sigmoid(logits)
meta_probs = []
for i in range(self.meta_label_size):
# 1 - (1 - p_1)(...)(1 - p_n)
meta_prob = (1 - y_hat[:, self.label_grouping[str(i)]]).prod(1)
meta_probs.append(meta_prob) # in this version we don't do threshold....(originally we did)
meta_probs = torch.stack(meta_probs, dim=1)
assert meta_probs.size(1) == self.meta_label_size
# generate meta-label
y_indices = true_y.nonzero()
meta_y = self.generate_meta_y(y_indices.data.cpu().numpy().tolist(), self.meta_label_size,
batch_size)
meta_y = Variable(torch.from_numpy(meta_y)) if device == -1 else Variable(torch.from_numpy(meta_y)).cuda(device)
meta_loss = self.bce_loss(meta_probs, meta_y) * self.config.beta
return meta_loss
def log_of_array_ignoring_zeros(M):
"""Returns an array containing the logs of the nonzero
elements of M. Zeros are left alone since log(0) isn't
defined.
"""
log_M = M.copy()
mask = log_M > 0
log_M[mask] = np.log(log_M[mask])
return log_M
def observed_over_expected(df):
col_totals = df.sum(axis=0)
total = col_totals.sum()
row_totals = df.sum(axis=1)
expected = np.outer(row_totals, col_totals) / total
oe = df / expected
return oe
def pmi(df, positive=True):
df = observed_over_expected(df)
# Silence distracting warnings about log(0):
with np.errstate(divide='ignore'):
df = np.log(df)
df[np.isnan(df)] = 0.0 # log(0) = 0
if positive:
df[df < 0] = 0.0
return df
class CoOccurenceLoss(nn.Module):
def __init__(self, config,
csu_path='./data/csu/label_co_matrix.npy',
pp_path='./data/csu/pp_combined_label_co_matrix.npy',
device=-1):
super(CoOccurenceLoss, self).__init__()
self.co_mat_path = csu_path if config.use_csu else pp_path
self.co_mat = np.load(self.co_mat_path)
self.X = self.co_mat
self.glove = self.config.glove
logging.info("using co_matrix {}".format(self.co_mat_path))
self.n = config.hidden_size # N-dim rep
self.m = config.label_size
self.gamma = self.config.gamma
if self.glove:
self.C = torch.empty(self.m, self.n)
self.C = Variable(self.C.uniform_(-0.5, 0.5)).cuda(device)
self.B = torch.empty(2, self.m)
self.B = Variable(self.B.uniform_(-0.5, 0.5)).cuda(device)
self.indices = list(range(self.m)) # label_size
# Precomputable GloVe values:
self.X_log = log_of_array_ignoring_zeros(self.X)
self.X_weights = (np.minimum(self.X, config.xmax) / config.xmax) ** config.alpha # eq. (9)
# iterate on the upper triangular matrix, off-diagonal
self.iu1 = np.triu_indices(41, 1) # 820 iterations
else:
self.X = Variable(pmi(self.X, positive=self.config.ppmi), requires_grad=False).cuda(device)
self.mse = nn.MSELoss()
def forward(self, softmax_weight):
# this computes a straight-through pass of the GloVE objective
# similar to "Auxiliary" training
# return the loss
# softmax_weight: [d, |Y|]
if self.glove: