-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathmodel.py
347 lines (299 loc) · 13 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
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
import math
import torch
import torch.nn.functional as F
from torch import nn
# Bert + FNN
class Transformer(nn.Module):
def __init__(self, base_model, num_classes, input_size):
super().__init__()
self.base_model = base_model
self.num_classes = num_classes
self.input_size = input_size
self.linear = nn.Linear(base_model.config.hidden_size, num_classes)
self.dropout = nn.Dropout(0.5)
self.softmax = nn.Softmax()
for param in base_model.parameters():
param.requires_grad = (True)
def forward(self, inputs):
raw_outputs = self.base_model(**inputs)
# The pooler_output is made of CLS --> FNN --> Tanh
# The last_hidden_state[:,0] is made of original CLS
# Method one
# cls_feats = raw_outputs.pooler_output
# Method two
cls_feats = raw_outputs.last_hidden_state[:, 0, :]
predicts = self.softmax(self.linear(self.dropout(cls_feats)))
return predicts
class Gru_Model(nn.Module):
def __init__(self, base_model, num_classes, input_size):
super().__init__()
self.base_model = base_model
self.num_classes = num_classes
self.input_size = input_size
self.Gru = nn.GRU(input_size=self.input_size,
hidden_size=320,
num_layers=1,
batch_first=True)
self.fc = nn.Sequential(nn.Dropout(0.5),
nn.Linear(320, 80),
nn.Linear(80, 20),
nn.Linear(20, self.num_classes),
nn.Softmax(dim=1))
for param in base_model.parameters():
param.requires_grad = (True)
def forward(self, inputs):
raw_outputs = self.base_model(**inputs)
tokens = raw_outputs.last_hidden_state
gru_output, _ = self.Gru(tokens)
outputs = gru_output[:, -1, :]
outputs = self.fc(outputs)
return outputs
# Try to use the softmax、relu、tanh and logistic
class Lstm_Model(nn.Module):
def __init__(self, base_model, num_classes, input_size):
super().__init__()
self.base_model = base_model
self.num_classes = num_classes
self.input_size = input_size
self.Lstm = nn.LSTM(input_size=self.input_size,
hidden_size=320,
num_layers=1,
batch_first=True)
self.fc = nn.Sequential(nn.Dropout(0.5),
nn.Linear(320, 80),
nn.Linear(80, 20),
nn.Linear(20, self.num_classes),
nn.Softmax(dim=1))
for param in base_model.parameters():
param.requires_grad = (True)
def forward(self, inputs):
raw_outputs = self.base_model(**inputs)
tokens = raw_outputs.last_hidden_state
lstm_output, _ = self.Lstm(tokens)
outputs = lstm_output[:, -1, :]
outputs = self.fc(outputs)
return outputs
class BiLstm_Model(nn.Module):
def __init__(self, base_model, num_classes, input_size):
super().__init__()
self.base_model = base_model
self.num_classes = num_classes
self.input_size = input_size
# Open the bidirectional
self.BiLstm = nn.LSTM(input_size=self.input_size,
hidden_size=320,
num_layers=1,
batch_first=True,
bidirectional=True)
self.fc = nn.Sequential(nn.Dropout(0.5),
nn.Linear(320 * 2, 80),
nn.Linear(80, 20),
nn.Linear(20, self.num_classes),
nn.Softmax(dim=1))
for param in base_model.parameters():
param.requires_grad = (True)
def forward(self, inputs):
raw_outputs = self.base_model(**inputs)
cls_feats = raw_outputs.last_hidden_state
outputs, _ = self.BiLstm(cls_feats)
outputs = outputs[:, -1, :]
outputs = self.fc(outputs)
return outputs
class Rnn_Model(nn.Module):
def __init__(self, base_model, num_classes, input_size):
super().__init__()
self.base_model = base_model
self.num_classes = num_classes
self.input_size = input_size
self.Rnn = nn.RNN(input_size=self.input_size,
hidden_size=320,
num_layers=1,
batch_first=True)
self.fc = nn.Sequential(nn.Dropout(0.5),
nn.Linear(320, 80),
nn.Linear(80, 20),
nn.Linear(20, self.num_classes),
nn.Softmax(dim=1))
for param in base_model.parameters():
param.requires_grad = (True)
def forward(self, inputs):
raw_outputs = self.base_model(**inputs)
cls_feats = raw_outputs.last_hidden_state
outputs, _ = self.Rnn(cls_feats)
outputs = outputs[:, -1, :]
outputs = self.fc(outputs)
return outputs
class TextCNN_Model(nn.Module):
def __init__(self, base_model, num_classes):
super().__init__()
self.base_model = base_model
self.num_classes = num_classes
for param in base_model.parameters():
param.requires_grad = (True)
# Define the hyperparameters
self.filter_sizes = [2, 3, 4]
self.num_filters = 2
self.encode_layer = 12
# TextCNN
self.convs = nn.ModuleList(
[nn.Conv2d(in_channels=1, out_channels=self.num_filters,
kernel_size=(K, self.base_model.config.hidden_size)) for K in self.filter_sizes]
)
self.block = nn.Sequential(
nn.Dropout(0.5),
nn.Linear(self.num_filters * len(self.filter_sizes), self.num_classes),
nn.Softmax(dim=1)
)
def conv_pool(self, tokens, conv):
tokens = conv(tokens)
tokens = F.relu(tokens)
tokens = tokens.squeeze(3)
tokens = F.max_pool1d(tokens, tokens.size(2))
out = tokens.squeeze(2)
return out
def forward(self, inputs):
raw_outputs = self.base_model(**inputs)
tokens = raw_outputs.last_hidden_state.unsqueeze(1)
out = torch.cat([self.conv_pool(tokens, conv) for conv in self.convs],
1)
predicts = self.block(out)
return predicts
class Transformer_CNN_RNN(nn.Module):
def __init__(self, base_model, num_classes):
super().__init__()
self.base_model = base_model
self.num_classes = num_classes
for param in base_model.parameters():
param.requires_grad = (True)
# Define the hyperparameters
self.filter_sizes = [3, 4, 5]
self.num_filters = 100
# TextCNN
self.convs = nn.ModuleList(
[nn.Conv2d(in_channels=1, out_channels=self.num_filters,
kernel_size=(K, self.base_model.config.hidden_size)) for K in self.filter_sizes]
)
# LSTM
self.lstm = nn.LSTM(input_size=self.base_model.config.hidden_size,
hidden_size=512,
num_layers=1,
batch_first=True)
self.block = nn.Sequential(
nn.Dropout(0.5),
nn.Linear(812, 128),
nn.Linear(128, 16),
nn.Linear(16, num_classes),
nn.Softmax(dim=1)
)
def conv_pool(self, tokens, conv):
# x -> [batch,1,text_length,768]
tokens = conv(tokens) # shape [batch_size, out_channels, x.shape[2] - conv.kernel_size[0] + 1, 1]
tokens = F.relu(tokens)
tokens = tokens.squeeze(3) # shape [batch_size, out_channels, x.shape[2] - conv.kernel_size[0] + 1]
tokens = F.max_pool1d(tokens, tokens.size(2)) # shape[batch, out_channels, 1]
out = tokens.squeeze(2) # shape[batch, out_channels]
return out
def forward(self, inputs):
raw_outputs = self.base_model(**inputs)
cnn_tokens = raw_outputs.last_hidden_state.unsqueeze(1) # shape [batch_size, 1, max_len, hidden_size]
cnn_out = torch.cat([self.conv_pool(cnn_tokens, conv) for conv in self.convs],
1) # shape [batch_size, self.num_filters * len(self.filter_sizes]
rnn_tokens = raw_outputs.last_hidden_state
rnn_outputs, _ = self.lstm(rnn_tokens)
rnn_out = rnn_outputs[:, -1, :]
# cnn_out --> [batch,300]
# rnn_out --> [batch,512]
out = torch.cat((cnn_out, rnn_out), 1)
predicts = self.block(out)
return predicts
class Transformer_Attention(nn.Module):
def __init__(self, base_model, num_classes):
super().__init__()
self.base_model = base_model
self.num_classes = num_classes
for param in base_model.parameters():
param.requires_grad = (True)
# Self-Attention
self.key_layer = nn.Linear(self.base_model.config.hidden_size, self.base_model.config.hidden_size)
self.query_layer = nn.Linear(self.base_model.config.hidden_size, self.base_model.config.hidden_size)
self.value_layer = nn.Linear(self.base_model.config.hidden_size, self.base_model.config.hidden_size)
self._norm_fact = 1 / math.sqrt(self.base_model.config.hidden_size)
self.block = nn.Sequential(
nn.Dropout(0.5),
nn.Linear(768, 128),
nn.Linear(128, 16),
nn.Linear(16, num_classes),
nn.Softmax(dim=1)
)
def forward(self, inputs):
raw_outputs = self.base_model(**inputs)
tokens = raw_outputs.last_hidden_state
K = self.key_layer(tokens)
Q = self.query_layer(tokens)
V = self.value_layer(tokens)
attention = nn.Softmax(dim=-1)((torch.bmm(Q, K.permute(0, 2, 1))) * self._norm_fact)
attention_output = torch.bmm(attention, V)
attention_output = torch.mean(attention_output, dim=1)
predicts = self.block(attention_output)
return predicts
class Transformer_CNN_RNN_Attention(nn.Module):
def __init__(self, base_model, num_classes):
super().__init__()
self.base_model = base_model
self.num_classes = num_classes
for param in base_model.parameters():
param.requires_grad = (True)
# Define the hyperparameters
self.filter_sizes = [3, 4, 5]
self.num_filters = 100
# TextCNN
self.convs = nn.ModuleList(
[nn.Conv2d(in_channels=1, out_channels=self.num_filters,
kernel_size=(K, self.base_model.config.hidden_size)) for K in self.filter_sizes]
)
# LSTM
self.lstm = nn.LSTM(input_size=self.base_model.config.hidden_size,
hidden_size=512,
num_layers=1,
batch_first=True)
# Self-Attention
self.key_layer = nn.Linear(self.base_model.config.hidden_size, self.base_model.config.hidden_size)
self.query_layer = nn.Linear(self.base_model.config.hidden_size, self.base_model.config.hidden_size)
self.value_layer = nn.Linear(self.base_model.config.hidden_size, self.base_model.config.hidden_size)
self._norm_fact = 1 / math.sqrt(self.base_model.config.hidden_size)
self.block = nn.Sequential(
nn.Dropout(0.5),
nn.Linear(812, 128),
nn.Linear(128, 16),
nn.Linear(16, num_classes),
nn.Softmax(dim=1)
)
def conv_pool(self, tokens, conv):
# x -> [batch,1,text_length,768]
tokens = conv(tokens) # shape [batch_size, out_channels, x.shape[2] - conv.kernel_size[0] + 1, 1]
tokens = F.relu(tokens)
tokens = tokens.squeeze(3) # shape [batch_size, out_channels, x.shape[2] - conv.kernel_size[0] + 1]
tokens = F.max_pool1d(tokens, tokens.size(2)) # shape[batch, out_channels, 1]
out = tokens.squeeze(2) # shape[batch, out_channels]
return out
def forward(self, inputs):
raw_outputs = self.base_model(**inputs)
tokens = raw_outputs.last_hidden_state
# Self-Attention
K = self.key_layer(tokens)
Q = self.query_layer(tokens)
V = self.value_layer(tokens)
attention = nn.Softmax(dim=-1)((torch.bmm(Q, K.permute(0, 2, 1))) * self._norm_fact)
attention_output = torch.bmm(attention, V)
# TextCNN
cnn_tokens = attention_output.unsqueeze(1) # shape [batch_size, 1, max_len, hidden_size]
cnn_out = torch.cat([self.conv_pool(cnn_tokens, conv) for conv in self.convs],
1) # shape [batch_size, self.num_filters * len(self.filter_sizes]
rnn_tokens = tokens
rnn_outputs, _ = self.lstm(rnn_tokens)
rnn_out = rnn_outputs[:, -1, :]
# cnn_out --> [batch,300]
# rnn_out --> [batch,512]
out = torch.cat((cnn_out, rnn_out), 1)
predicts = self.block(out)
return predicts