-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
253 lines (218 loc) · 10.4 KB
/
main.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
from pprint import pprint
import os
import logging
import json
import shutil
from sklearn.metrics import accuracy_score, f1_score, classification_report
import torch
import torch.nn as nn
import numpy as np
import pickle
from torch.utils.data import DataLoader, RandomSampler
from transformers import BertTokenizer
import config
import preprocess_no_log
import dataset
import models
import utils
logger = logging.getLogger(__name__)
from transformers import logging
logging.set_verbosity_warning()
logging.set_verbosity_error()
class Trainer:
def __init__(self, args, train_loader, dev_loader, test_loader):
self.args = args
gpu_ids = args.gpu_ids.split(',')
self.device = torch.device("cpu" if gpu_ids[0] == '-1' else "cuda:" + gpu_ids[0])
self.model = models.BertForRelationExtraction(args)
self.optimizer = torch.optim.Adam(params=self.model.parameters(), lr=self.args.lr)
self.criterion = nn.CrossEntropyLoss()
self.train_loader = train_loader
self.dev_loader = dev_loader
self.test_loader = test_loader
self.model.to(self.device)
def load_ckp(self, model, optimizer, checkpoint_path):
# checkpoint = torch.load(checkpoint_path)
checkpoint = torch.load(checkpoint_path, map_location=self.device)
model.load_state_dict(checkpoint['state_dict'])
optimizer.load_state_dict(checkpoint['optimizer'])
epoch = checkpoint['epoch']
loss = checkpoint['loss']
return model, optimizer, epoch, loss
def save_ckp(self, state, checkpoint_path):
torch.save(state, checkpoint_path)
"""
def save_ckp(self, state, is_best, checkpoint_path, best_model_path):
tmp_checkpoint_path = checkpoint_path
torch.save(state, tmp_checkpoint_path)
if is_best:
tmp_best_model_path = best_model_path
shutil.copyfile(tmp_checkpoint_path, tmp_best_model_path)
"""
def train(self):
total_step = len(self.train_loader) * self.args.train_epochs
global_step = 0
eval_step = 1
best_dev_micro_f1 = 0.0
for epoch in range(args.train_epochs):
for train_step, train_data in enumerate(self.train_loader):
self.model.train()
token_ids = train_data['token_ids'].to(self.device)
attention_masks = train_data['attention_masks'].to(self.device)
token_type_ids = train_data['token_type_ids'].to(self.device)
labels = train_data['labels'].to(self.device)
ids = train_data['ids'].to(self.device)
train_outputs = self.model(token_ids, attention_masks, token_type_ids, ids)
loss = self.criterion(train_outputs, labels)
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
logger.info(
"【train】 epoch:{} step:{}/{} loss:{:.6f}".format(epoch, global_step, total_step, loss.item()))
global_step += 1
if global_step % eval_step == 0:
dev_loss, dev_outputs, dev_targets = self.dev()
accuracy, micro_f1, macro_f1 = self.get_metrics(dev_outputs, dev_targets)
logger.info(
"【dev】 loss:{:.6f} accuracy:{:.4f} micro_f1:{:.4f} macro_f1:{:.4f}".format(dev_loss, accuracy, micro_f1, macro_f1))
if macro_f1 > best_dev_micro_f1:
logger.info("------------>Save best model")
checkpoint = {
'epoch': epoch,
'loss': dev_loss,
'state_dict': self.model.state_dict(),
'optimizer': self.optimizer.state_dict(),
}
best_dev_micro_f1 = macro_f1
checkpoint_path = os.path.join(self.args.output_dir, 'best.pt')
self.save_ckp(checkpoint, checkpoint_path)
def dev(self):
self.model.eval()
total_loss = 0.0
dev_outputs = []
dev_targets = []
with torch.no_grad():
for dev_step, dev_data in enumerate(self.dev_loader):
token_ids = dev_data['token_ids'].to(self.device)
attention_masks = dev_data['attention_masks'].to(self.device)
token_type_ids = dev_data['token_type_ids'].to(self.device)
labels = dev_data['labels'].to(self.device)
ids = dev_data['ids'].to(self.device)
outputs = self.model(token_ids, attention_masks, token_type_ids, ids)
loss = self.criterion(outputs, labels)
# val_loss = val_loss + ((1 / (dev_step + 1))) * (loss.item() - val_loss)
total_loss += loss.item()
outputs = np.argmax(outputs.cpu().detach().numpy(), axis=1).flatten()
dev_outputs.extend(outputs.tolist())
dev_targets.extend(labels.cpu().detach().numpy().tolist())
return total_loss, dev_outputs, dev_targets
def test(self, checkpoint_path):
model = self.model
optimizer = self.optimizer
model, optimizer, epoch, loss = self.load_ckp(model, optimizer, checkpoint_path)
model.eval()
model.to(self.device)
total_loss = 0.0
test_outputs = []
test_targets = []
with torch.no_grad():
for test_step, test_data in enumerate(self.test_loader):
token_ids = test_data['token_ids'].to(self.device)
attention_masks = test_data['attention_masks'].to(self.device)
token_type_ids = test_data['token_type_ids'].to(self.device)
labels = test_data['labels'].to(self.device)
ids = test_data['ids'].to(self.device)
outputs = model(token_ids, attention_masks, token_type_ids, ids)
loss = self.criterion(outputs, labels)
# val_loss = val_loss + ((1 / (dev_step + 1))) * (loss.item() - val_loss)
total_loss += loss.item()
outputs = np.argmax(outputs.cpu().detach().numpy(), axis=1).flatten()
test_outputs.extend(outputs.tolist())
test_targets.extend(labels.cpu().detach().numpy().tolist())
return total_loss, test_outputs, test_targets
def predict(self, tokenizer, text, id2label, args, ids):
model = self.model
optimizer = self.optimizer
checkpoint = os.path.join(args.output_dir, 'best.pt')
model, optimizer, epoch, loss = self.load_ckp(model, optimizer, checkpoint)
model.eval()
model.to(self.device)
with torch.no_grad():
inputs = tokenizer.encode_plus(
text=text,
add_special_tokens=True,
max_length=args.max_seq_len,
truncation='longest_first',
padding="max_length",
return_token_type_ids=True,
return_attention_mask=True,
return_tensors='pt'
)
token_ids = inputs['input_ids'].to(self.device).long()
attention_masks = inputs['attention_mask'].to(self.device)
token_type_ids = inputs['token_type_ids'].to(self.device)
ids = torch.from_numpy(np.array([[x + 1 for x in ids]])).to(self.device)
outputs = model(token_ids, attention_masks, token_type_ids, ids)
outputs = np.argmax(outputs.cpu().detach().numpy(), axis=1).flatten().tolist()
if len(outputs) != 0:
outputs = [id2label[i] for i in outputs]
return outputs
else:
return 'sorry, i didnt recognize it'
def get_metrics(self, outputs, targets):
accuracy = accuracy_score(targets, outputs)
micro_f1 = f1_score(targets, outputs, average='micro')
macro_f1 = f1_score(targets, outputs, average='macro')
return accuracy, micro_f1, macro_f1
def get_classification_report(self, outputs, targets, labels):
report = classification_report(targets, outputs, target_names=labels)
return report
if __name__ == '__main__':
args = config.Args().get_parser()
utils.utils.set_seed(args.seed)
utils.utils.set_logger(os.path.join(args.main_log_dir))
processor = preprocess_no_log.Processor()
label2id = {}
id2label = {}
with open('drive/MyDrive/Rearch_Dimas/BERT_RE/input/data/rel_dict.json', 'r') as fp:
labels = json.loads(fp.read())
for k, v in labels.items():
label2id[k] = v
id2label[v] = k
logger.info(label2id)
train_out = preprocess_no_log.get_out(processor, 'drive/MyDrive/Rearch_Dimas/BERT_RE/input/data/train.txt', args, id2label, 'train')
dev_out = preprocess_no_log.get_out(processor, 'drive/MyDrive/Rearch_Dimas/BERT_RE/input/data/test.txt', args, id2label, 'dev')
test_out = preprocess_no_log.get_out(processor, 'drive/MyDrive/Rearch_Dimas/BERT_RE/input/data/test.txt', args, id2label, 'test')
train_features, train_callback_info = train_out
train_dataset = dataset.ReDataset(train_features)
train_sampler = RandomSampler(train_dataset)
train_loader = DataLoader(
dataset=train_dataset,
batch_size=args.train_batch_size,
sampler=train_sampler,
num_workers=2
)
dev_features, dev_callback_info = dev_out
dev_dataset = dataset.ReDataset(dev_features)
dev_loader = DataLoader(
dataset=dev_dataset,
batch_size=args.eval_batch_size,
num_workers=2
)
test_features, test_callback_info = dev_out
test_dataset = dataset.ReDataset(test_features)
test_loader = DataLoader(
dataset=test_dataset,
batch_size=args.eval_batch_size,
num_workers=2
)
trainer = Trainer(args, train_loader, dev_loader, test_loader)
logger.info('======== Training And Validation========')
trainer.train()
logger.info('======== Calculate Testing========')
checkpoint_path = f'{args.output_dir}best.pt'
total_loss, test_outputs, test_targets = trainer.test(checkpoint_path)
accuracy, micro_f1, macro_f1 = trainer.get_metrics(test_outputs, test_targets)
logger.info("【test】 loss:{:.6f} accuracy:{:.4f} micro_f1:{:.4f} macro_f1:{:.4f}".format(total_loss, accuracy, micro_f1, macro_f1))
report = trainer.get_classification_report(test_outputs, test_targets, labels)
logger.info(report)