-
Notifications
You must be signed in to change notification settings - Fork 0
/
trainer.py
186 lines (156 loc) · 6.88 KB
/
trainer.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
import numpy as np, argparse, time, pickle, random
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torch.utils.data.sampler import SubsetRandomSampler
from sklearn.metrics import f1_score, confusion_matrix, accuracy_score, classification_report, \
precision_recall_fscore_support
from utils import person_embed
from tqdm import tqdm
import json
def train_or_eval_model(model, loss_function, dataloader,epoch, cuda, args, optimizer=None, train=False, scheduler=None):
losses, preds, labels = [], [], []
scores, vids = [], []
assert not train or optimizer != None
if train:
model.train()
# dataloader = tqdm(dataloader)
# print(f"current roberta learning rate is :{optimizer.param_groups[0]['lr']}")
# print(f"current other learning rate is :{optimizer.param_groups[1]['lr']}")
else:
model.eval()
cnt = 0
for data in dataloader:
if train:
optimizer.zero_grad()
# text_ids, text_feature, speaker_ids, labels, umask = [d.cuda() for d in data] if cuda else data
label, speakers, lengths, utterances, utts, att_mask = data
# features, label, speakers, lengths, utterances = data
# speaker_vec = person_embed(speaker_ids, person_vec)
if cuda:
# features = features.cuda() # B x T x H
# features = features.view(-1, features.shape[-1]) # (B x T, H)
label = label.cuda() # B x T
# label = label.view(-1) # (B x T, )
lengths = lengths.cuda() # B
speakers = speakers.cuda() # B x T
utts = utts.cuda()
att_mask = att_mask.cuda()
# print(speakers)
log_prob = model(utts, att_mask, lengths, speakers) # (B, T, C)
# log_prob = model(utts, att_mask, lengths, speakers) # (B, T, C)
# print(label)
loss = loss_function(log_prob.permute(0,2,1), label) # B x C x T --- B x T
# loss = loss_function(log_prob, label)
label = label.cpu().numpy().tolist()
pred = torch.argmax(log_prob, dim = 2).cpu().numpy().tolist()
# pred = torch.argmax(log_prob, dim = 1).cpu().numpy().tolist() # (B x T, C)
preds += pred
labels += label
losses.append(loss.item())
if train:
loss_val = loss.item()
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm)
if args.tensorboard:
for param in model.named_parameters():
writer.add_histogram(param[0], param[1].grad, epoch)
# print(f"current learning rate is :{optimizer.param_groups[0]['lr']} and {optimizer.param_groups[1]['lr']}")
optimizer.step()
scheduler.step()
# if train:
# # scheduler.step()
# print(f"current learning rate is :{optimizer.param_groups[0]['lr']} and {optimizer.param_groups[1]['lr']}")
if preds != []:
new_preds = []
new_labels = []
for i,label in enumerate(labels):
for j,l in enumerate(label):
if l != -1:
new_labels.append(l)
new_preds.append(preds[i][j])
# for i, label in enumerate(labels):
# if label != -1:
# new_labels.append(label)
# new_preds.append(preds[i])
else:
return float('nan'), float('nan'), [], [], float('nan'), [], [], [], [], []
if not train:
# print(classification_report(new_labels, new_preds))
pass
# print(preds.tolist())
# print(labels.tolist())
avg_loss = round(np.sum(losses) / len(losses), 4)
avg_accuracy = round(accuracy_score(new_labels, new_preds) * 100, 2)
if args.dataset_name in ['IEMOCAP', 'MELD', 'EmoryNLP', 'jddc']:
avg_fscore = round(f1_score(new_labels, new_preds, average='weighted') * 100, 2)
return avg_loss, avg_accuracy, labels, preds, avg_fscore
else: # DailyDialog
avg_micro_fscore = round(f1_score(new_labels, new_preds, average='micro', labels=list(range(0, 3))) * 100, 2)
avg_macro_fscore = round(f1_score(new_labels, new_preds, average='macro') * 100, 2)
return avg_loss, avg_accuracy, labels, preds, avg_micro_fscore, avg_macro_fscore
def save_badcase(model, dataloader, cuda, args, speaker_vocab, label_vocab):
preds, labels = [], []
scores, vids = [], []
dialogs = []
speakers = []
model.eval()
for data in dataloader:
# text_ids, text_feature, speaker_ids, labels, umask = [d.cuda() for d in data] if cuda else data
features, label, adj,s_mask, s_mask_onehot,lengths, speaker, utterances = data
# speaker_vec = person_embed(speaker_ids, person_vec)
if cuda:
features = features.cuda()
label = label.cuda()
adj = adj.cuda()
s_mask_onehot = s_mask_onehot.cuda()
s_mask = s_mask.cuda()
lengths = lengths.cuda()
# print(speakers)
log_prob = model(features, adj,s_mask, s_mask_onehot, lengths) # (B, N, C)
label = label.cpu().numpy().tolist() # (B, N)
pred = torch.argmax(log_prob, dim = 2).cpu().numpy().tolist() # (B, N)
preds += pred
labels += label
dialogs += utterances
speakers += speaker
# finished here
if preds != []:
new_preds = []
new_labels = []
for i,label in enumerate(labels):
for j,l in enumerate(label):
if l != -1:
new_labels.append(l)
new_preds.append(preds[i][j])
else:
return
cases = []
for i,d in enumerate(dialogs):
case = []
for j,u in enumerate(d):
case.append({
'text': u,
'speaker': speaker_vocab['itos'][speakers[i][j]],
'label': label_vocab['itos'][labels[i][j]] if labels[i][j] != -1 else 'none',
'pred': label_vocab['itos'][preds[i][j]]
})
cases.append(case)
with open('badcase/%s.json'%(args.dataset_name), 'w', encoding='utf-8') as f:
json.dump(cases,f)
# print(preds.tolist())
# print(labels.tolist())
avg_accuracy = round(accuracy_score(new_labels, new_preds) * 100, 2)
if args.dataset_name in ['IEMOCAP', 'MELD', 'EmoryNLP']:
avg_fscore = round(f1_score(new_labels, new_preds, average='weighted') * 100, 2)
print('badcase saved')
print('test_f1', avg_fscore)
return
else:
avg_micro_fscore = round(f1_score(new_labels, new_preds, average='micro', labels=list(range(1, 7))) * 100, 2)
avg_macro_fscore = round(f1_score(new_labels, new_preds, average='macro') * 100, 2)
print('badcase saved')
print('test_micro_f1', avg_micro_fscore)
print('test_macro_f1', avg_macro_fscore)
return