/
train_mlp_text.py
278 lines (199 loc) · 8.12 KB
/
train_mlp_text.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
from torch import nn
from torch.utils.data import DataLoader, Dataset, sampler, WeightedRandomSampler
import torch
from torch.autograd import Variable
import json
import os, random, copy
import numpy as np
import torch.optim as optim
import time
from sklearn import metrics, preprocessing
import pandas as pd
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.metrics import confusion_matrix
import pandas as pd
import seaborn as sn
import matplotlib.pyplot as plt
from sklearn.utils.class_weight import compute_class_weight
import argparse
parser = argparse.ArgumentParser(description='Train MLP Models for FakeNews Detection')
parser.add_argument('--bs', type=int, default=32,
help='16,32,64,128')
parser.add_argument('--optim', type=str, default='adam',
help='sgd, adam')
parser.add_argument('--epochs', type=int, default=100,
help='15,20,30')
parser.add_argument('--lr', type=str, default='2e-5',
help='1e-5, 5e-5')
parser.add_argument('--gamma', type=float, default=0.75)
parser.add_argument('--step', type=int, default=1,
help='any number>1')
parser.add_argument('--ltype', type=int, default=0,
help='0-3')
parser.add_argument('--norm', type=int, default=1,
help='0 | 1')
parser.add_argument('--split', type=int, default=1,
help='1-10')
parser.add_argument('--gpu', type=int, default=0,
help='0,1,2,3')
args = parser.parse_args()
seed = 42
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
class SELayer(nn.Module):
def __init__(self, channel, reduction=16):
super(SELayer, self).__init__()
self.fc = nn.Sequential(
nn.Linear(channel, channel // reduction, bias=False),
nn.ReLU(inplace=True),
nn.Linear(channel // reduction, channel, bias=False),
nn.Sigmoid()
)
def forward(self, x):
y = self.fc(x)
return x * y, y
class UniMLP_SeNet(nn.Module):
def __init__(self, inp_dim, ncls):
super(UniMLP_SeNet, self).__init__()
self.se = SELayer(inp_dim)
self.bn1 = nn.BatchNorm1d(inp_dim)
self.fc2 = nn.Linear(inp_dim, 128, bias=False)
self.bn2 = nn.BatchNorm1d(128)
self.cf = nn.Linear(128, ncls)
self.dp1 = nn.Dropout(0.2)
self.dp2 = nn.Dropout(0.5)
self.relu = nn.ReLU()
def forward(self, x):
x, y = self.se(x)
x = self.dp1(self.bn1(x))
x = self.dp2(self.relu(self.bn2(self.fc2(x))))
return self.cf(x), y
class UniDataset(Dataset):
def __init__(self, feats, labels, normalize=1):
self.feats = feats
self.labels = np.array(labels).astype(np.int)
self.normalize = normalize
def __len__(self):
return len(self.labels)
def __getitem__(self, idx):
feat = self.feats[idx]
label = self.labels[idx]
if self.normalize:
feat = preprocessing.normalize(feat.reshape(1,-1), axis=1).flatten()
return torch.FloatTensor(feat), torch.tensor(label)
def train(model, optimizer, lr_scheduler, num_epochs):
since = time.time()
best_model = model
best_acc = 0.0
best_val_loss = 100
best_epoch = 0
for epoch in range(1, num_epochs+1):
print('Epoch {}/{}'.format(epoch, num_epochs))
print('-' * 10)
since2 = time.time()
model.train() # Set model to training mode
running_loss = 0.0
running_corrects = 0
tot = 0.0
cnt = 0
# Iterate over data.
for inputs, labels in tr_loader:
inputs, labels = inputs.to(device), labels.to(device)
# zero the parameter gradients
optimizer.zero_grad()
# forward
outputs, _ = model(inputs)
_, preds = torch.max(outputs.data, 1)
loss = criterion(outputs, labels)
# backward + optimize
loss.backward()
optimizer.step()
# statistics
running_loss += loss.item()
running_corrects += torch.sum(preds == labels.data).item()
tot += len(labels)
if cnt % 50 == 0:
print('[%d, %5d] loss: %.5f, Acc: %.2f' %
(epoch, cnt + 1, loss.item(), (100.0 * running_corrects) / tot))
cnt = cnt + 1
if lr_scheduler:
lr_scheduler.step()
train_loss = running_loss / len(tr_loader)
train_acc = running_corrects * 1.0 / (len(tr_loader.dataset))
print('Training Loss: {:.6f} Acc: {:.2f}'.format(train_loss, 100.0 * train_acc))
val_loss, val_acc, val_mcc = evaluate(model, vl_loader)
print('Epoch: {:d}, Val Loss: {:.4f}, Val Acc: {:.4f}, Val MCC: {:.4f}'.format(epoch,
val_loss, val_acc, val_mcc))
# deep copy the model
if val_loss <= best_val_loss:
best_acc = val_acc
best_val_loss = val_loss
best_epoch = epoch
best_model = copy.deepcopy(model)
time_elapsed2 = time.time() - since2
print('Epoch complete in {:.0f}m {:.0f}s'.format(
time_elapsed2 // 60, time_elapsed2 % 60))
time_elapsed = time.time() - since
print('Training complete in {:.0f}m {:.0f}s'.format(
time_elapsed // 60, time_elapsed % 60))
return best_model, best_epoch
def evaluate(model, loader):
model.eval()
test_loss = 0
all_preds = []
all_labels = []
with torch.no_grad():
for inputs, labels in loader:
inputs, labels = inputs.to(device), labels.to(device)
outputs, _ = model(inputs)
preds = torch.argmax(outputs.data, 1)
test_loss += criterion(outputs, labels).item()
all_preds.extend(preds.cpu().numpy().flatten())
all_labels.extend(labels.cpu().numpy().flatten())
acc = metrics.accuracy_score(all_labels, all_preds)
mcc = metrics.matthews_corrcoef(all_labels, all_preds)
return test_loss/len(loader), acc, mcc
batch_size = args.bs
normalize = args.norm
init_lr = float(args.lr)
epochs = args.epochs
optz = args.optim
step = args.step
ltype = args.ltype
split = args.split
dev_loc = 'dataset/dev/data/'
tr_ids = pd.read_csv(dev_loc+'splits/train%d.txt'%(split), header=None).to_numpy().flatten()
vl_ids = pd.read_csv(dev_loc+'splits/val%d.txt'%(split), header=None).to_numpy().flatten()
layers = ['sent_word_sumavg', 'sent_emb_2_last', 'sent_emb_last', 'sent_word_catavg']
layer = layers[ltype]
feat_text = json.load(open('features/dev_covidbert.json','r'))
lab_df = pd.read_csv(dev_loc+'all_ids.csv', header=None)[1].to_numpy().flatten()
fname_df = pd.read_csv(dev_loc+'all_ids.csv', header=None)[0].to_numpy().flatten()
dim = 4096 if 'catavg' in layer else 1024
lab_train = lab_df[tr_ids]
lab_val = lab_df[vl_ids]
ft_train = np.array(feat_text[layer])[tr_ids]
ft_val = np.array(feat_text[layer])[vl_ids]
tr_data = UniDataset(ft_train, lab_train, normalize)
vl_data = UniDataset(ft_val, lab_val, normalize)
tr_loader = DataLoader(dataset=tr_data, batch_size=batch_size, num_workers=2,
shuffle=True)
vl_loader = DataLoader(dataset=vl_data, batch_size=16, num_workers=2)
criterion = nn.CrossEntropyLoss().to(device)
model_ft = UniMLP_SeNet(dim, len(np.unique(lab_train)))
print(model_ft)
model_ft.to(device)
if optz == 'sgd':
optimizer_ft = optim.SGD(model_ft.parameters(), init_lr, momentum=0.9, weight_decay=1e-5)
scheduler = optim.lr_scheduler.StepLR(optimizer_ft, step, gamma=args.gamma)
else:
optimizer_ft = optim.Adam(model_ft.parameters(), init_lr, weight_decay=1e-5)
scheduler = None
model_ft, best_epoch = train(model_ft, optimizer_ft, scheduler,num_epochs=epochs)
torch.save(model_ft.state_dict(), 'models/mlp_%s_%d.pt'%(layer, split))
vl_loss, vl_acc, vl_mcc = evaluate(model_ft, vl_loader)
print('Best Epoch: %d, Val Acc: %.4f, %.4f, %.4f'%(best_epoch, np.round(vl_loss,4),
np.round(vl_acc,4), np.round(vl_mcc,4)))