-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.py
160 lines (124 loc) · 6.17 KB
/
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
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
# ## Functions to accomplish attention
def batch_matmul_bias(seq, weight, bias, nonlinearity=''):
s = None
bias_dim = bias.size()
for i in range(seq.size(0)):
_s = torch.mm(seq[i], weight)
_s_bias = _s + bias.expand(bias_dim[0], _s.size()[0]).transpose(0,1)
if(nonlinearity=='tanh'):
_s_bias = torch.tanh(_s_bias)
_s_bias = _s_bias.unsqueeze(0)
if(s is None):
s = _s_bias
else:
s = torch.cat((s,_s_bias),0)
return s.squeeze()
def batch_matmul(seq, weight, nonlinearity=''):
s = None
for i in range(seq.size(0)):
_s = torch.mm(seq[i], weight)
if(nonlinearity=='tanh'):
_s = torch.tanh(_s)
_s = _s.unsqueeze(0)
if(s is None):
s = _s
else:
s = torch.cat((s,_s),0)
return s.squeeze()
def attention_mul(rnn_outputs, att_weights):
attn_vectors = None
for i in range(rnn_outputs.size(0)):
h_i = rnn_outputs[i]
a_i = att_weights[i].unsqueeze(1).expand_as(h_i)
h_i = a_i * h_i
h_i = h_i.unsqueeze(0)
if(attn_vectors is None):
attn_vectors = h_i
else:
attn_vectors = torch.cat((attn_vectors,h_i),0)
return torch.sum(attn_vectors, 0)
# ## Word attention model with bias
class AttentionWordRNN(nn.Module):
def __init__(self, batch_size, num_tokens, embed_size, word_gru_hidden, bidirectional= True):
super(AttentionWordRNN, self).__init__()
self.batch_size = batch_size
self.num_tokens = num_tokens
self.embed_size = embed_size
self.word_gru_hidden = word_gru_hidden
self.bidirectional = bidirectional
self.lookup = nn.Embedding(num_tokens, embed_size)
if bidirectional == True:
self.word_gru = nn.GRU(embed_size, word_gru_hidden, bidirectional= True)
self.weight_W_word = nn.Parameter(torch.Tensor(2* word_gru_hidden,2*word_gru_hidden))
self.bias_word = nn.Parameter(torch.Tensor(2* word_gru_hidden,1))
self.weight_proj_word = nn.Parameter(torch.Tensor(2*word_gru_hidden, 1))
else:
self.word_gru = nn.GRU(embed_size, word_gru_hidden, bidirectional= False)
self.weight_W_word = nn.Parameter(torch.Tensor(word_gru_hidden, word_gru_hidden))
self.bias_word = nn.Parameter(torch.Tensor(word_gru_hidden,1))
self.weight_proj_word = nn.Parameter(torch.Tensor(word_gru_hidden, 1))
self.softmax_word = nn.Softmax()
self.weight_W_word.data.uniform_(-0.1, 0.1)
self.weight_proj_word.data.uniform_(-0.1,0.1)
def forward(self, embed, state_word):
# embeddings
embedded = self.lookup(embed)
# word level gru
output_word, state_word = self.word_gru(embedded, state_word)
# print output_word.size()
word_squish = batch_matmul_bias(output_word, self.weight_W_word,self.bias_word, nonlinearity='tanh')
word_attn = batch_matmul(word_squish, self.weight_proj_word)
word_attn_norm = self.softmax_word(word_attn.transpose(1,0))
word_attn_vectors = attention_mul(output_word, word_attn_norm.transpose(1,0))
return word_attn_vectors, state_word, word_attn_norm
def init_hidden(self):
if self.bidirectional == True:
return Variable(torch.zeros(2, self.batch_size, self.word_gru_hidden))
else:
return Variable(torch.zeros(1, self.batch_size, self.word_gru_hidden))
# ## Sentence Attention model with bias
class AttentionSentRNN(nn.Module):
def __init__(self, batch_size, sent_gru_hidden, word_gru_hidden, n_classes, bidirectional= True):
super(AttentionSentRNN, self).__init__()
self.batch_size = batch_size
self.sent_gru_hidden = sent_gru_hidden
self.n_classes = n_classes
self.word_gru_hidden = word_gru_hidden
self.bidirectional = bidirectional
if bidirectional == True:
self.sent_gru = nn.GRU(2 * word_gru_hidden, sent_gru_hidden, bidirectional= True)
self.weight_W_sent = nn.Parameter(torch.Tensor(2* sent_gru_hidden ,2* sent_gru_hidden))
self.bias_sent = nn.Parameter(torch.Tensor(2* sent_gru_hidden,1))
self.weight_proj_sent = nn.Parameter(torch.Tensor(2* sent_gru_hidden, 1))
self.final_linear = nn.Linear(2* sent_gru_hidden, n_classes)
else:
self.sent_gru = nn.GRU(word_gru_hidden, sent_gru_hidden, bidirectional= False)
self.weight_W_sent = nn.Parameter(torch.Tensor(sent_gru_hidden ,sent_gru_hidden))
self.bias_sent = nn.Parameter(torch.Tensor(sent_gru_hidden,1))
self.weight_proj_sent = nn.Parameter(torch.Tensor(sent_gru_hidden, 1))
self.final_linear = nn.Linear(sent_gru_hidden, n_classes)
self.softmax_sent = nn.Softmax()
self.final_softmax = nn.Softmax()
self.weight_W_sent.data.uniform_(-0.1, 0.1)
self.weight_proj_sent.data.uniform_(-0.1,0.1)
def forward(self, word_attention_vectors, state_sent):
output_sent, state_sent = self.sent_gru(word_attention_vectors, state_sent)
sent_squish = batch_matmul_bias(output_sent, self.weight_W_sent,self.bias_sent, nonlinearity='tanh')
sent_attn = batch_matmul(sent_squish, self.weight_proj_sent)
sent_attn_norm = self.softmax_sent(sent_attn.transpose(1,0))
sent_attn_vectors = attention_mul(output_sent, sent_attn_norm.transpose(1,0))
# final classifier
final_map = self.final_linear(sent_attn_vectors.squeeze(0))
return F.log_softmax(final_map), state_sent, sent_attn_norm
def init_hidden(self):
if self.bidirectional == True:
return Variable(torch.zeros(2, self.batch_size, self.sent_gru_hidden))
else:
return Variable(torch.zeros(1, self.batch_size, self.sent_gru_hidden))