-
Notifications
You must be signed in to change notification settings - Fork 1
/
train_neural_models.py
216 lines (207 loc) · 12.5 KB
/
train_neural_models.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
import torch
import torch.optim as optim
import time
import random
from torch.autograd import Variable
from evaluation import *
import progressbar
from torch.optim.lr_scheduler import LambdaLR
from torch.optim.lr_scheduler import StepLR
import matplotlib.pyplot as plt
from sklearn import linear_model
from sklearn.utils import class_weight
from numpy import *
import math
USE_CUDA = torch.cuda.is_available()
FloatTensor = torch.cuda.FloatTensor if USE_CUDA else torch.FloatTensor
LongTensor = torch.cuda.LongTensor if USE_CUDA else torch.LongTensor
def train(params, training_docs, test_docs, data, model):
if params['model_type'] == 'clique':
training_data, training_labels = data.create_cliques(training_docs, params['task'], params['train_data_limit'])
test_data, test_labels = data.create_cliques(test_docs, params['task'], params['train_data_limit'])
elif params['model_type'] == 'sent_avg':
training_data, training_labels, train_ids = data.create_doc_sents(training_docs, 'sentence', params['task'], params['train_data_limit'])
test_data, test_labels, test_ids = data.create_doc_sents(test_docs, 'sentence', params['task'], params['train_data_limit'])
elif params['model_type'] == 'par_seq':
training_data, training_labels, train_ids = data.create_doc_sents(training_docs, 'paragraph', params['task'],
params['train_data_limit'])
test_data, test_labels, test_ids = data.create_doc_sents(test_docs, 'paragraph', params['task'], params['train_data_limit'])
elif params['model_type']=='sem_rel':
training_data, training_labels, train_ids = data.create_doc_sents(training_docs, 'paragraph', params['task'],
params['train_data_limit'])
test_data, test_labels, test_ids = data.create_doc_sents(test_docs, 'paragraph', params['task'], params['train_data_limit'])
if USE_CUDA:
model.cuda()
if params['train_data_limit'] != -1:
training_docs = training_docs[:10]
test_docs = test_docs[:10]
parameters = filter(lambda p: p.requires_grad, model.parameters())
optimizer = optim.Adam(parameters, weight_decay=params['l2_reg'])
scheduler = None
if params['lr_decay'] == 'step':
scheduler = StepLR(optimizer, step_size=30, gamma=0.1)
elif params['lr_decay'] == 'lambda':
lambda1 = lambda epoch: 0.95 ** epoch
scheduler = LambdaLR(optimizer, lr_lambda=[lambda1])
if params['task'] == 'class' or params['task'] == 'perm' or params['task'] == 'minority':
loss_fn = torch.nn.CrossEntropyLoss()
elif params['task'] == 'score_pred':
loss_fn = torch.nn.MSELoss()
timestamp = time.time()
best_test_acc = 0
#test_acc_tab=[]
#test_ep_tab=[]
for epoch in range(params['num_epochs']):
if params['lr_decay'] == 'lambda' or params['lr_decay'] == 'step':
scheduler.step()
print(optimizer.param_groups[0]['lr'])
print("EPOCH "+str(epoch))
total_loss = 0
steps = int(len(training_data) / params['batch_size'])
indices = list(range(len(training_data)))
random.shuffle(indices)
bar = progressbar.ProgressBar()
model.train()
for step in bar(range(steps)):
batch_ind = indices[(step * params["batch_size"]):((step + 1) * params["batch_size"])]
sentences, orig_batch_labels = data.get_batch(training_data, training_labels, batch_ind, params['model_type'], params['clique_size'])
batch_padded, batch_lengths, original_index = data.pad_to_batch(sentences, data.word_to_idx, params['model_type'], params['clique_size'])
model.zero_grad()
if params['model_type']== 'sem_rel':
batch_data_frame= model(batch_padded, batch_lengths, original_index)
X = batch_data_frame[['sent','par']]
print("========================= X ==========================")
print(X)
Y = orig_batch_labels
print("============================ Y ==========================")
print(Y)
regr = linear_model.LinearRegression()
regr.fit(X, Y)
print("========================= regr ==========================")
print(regr)
reg_prediction = regr.predict(X)
print("========================= reg_prediction ==========================")
print(reg_prediction)
reg_prediction = torch.from_numpy(reg_prediction)
print("========================= reg_prediction transformed into tensor ==========================")
print(reg_prediction)
reg_prediction = reg_prediction.unsqueeze(1)
reg_prediction= F.softmax(reg_prediction, dim=0)
print("========================= reg_prediction softmax ==========================")
print(reg_prediction)
print("============================ Y ==========================")
print(Y)
Y = np.array(Y)
class_weights=class_weight.compute_class_weight(class_weight='balanced',classes= np.unique(Y),y= Y)
print("===================== Class weights ==========================")
print(class_weights)
class_weights = torch.from_numpy(class_weights)
# class_weights= class_weights.unsqueeze(1)
# print("===================== Class weights unsequeeze==========================")
# print(class_weights)
loss_fn = torch.nn.CrossEntropyLoss(weight=class_weights,reduction='mean')
loss = loss_fn(reg_prediction, Variable(LongTensor(orig_batch_labels)))
else:
pred_coherence, avg_deg_train= model(batch_padded, batch_lengths, original_index)
if params['task'] == 'score_pred':
loss = loss_fn(pred_coherence, Variable(FloatTensor(orig_batch_labels)))
else:
loss = loss_fn(pred_coherence, Variable(LongTensor(orig_batch_labels)))
mean_loss = loss / params["batch_size"]
mean_loss.backward()
total_loss += loss.cpu().data.numpy()
optimizer.step()
current_time = time.time()
print("Time %-5.2f min" % ((current_time - timestamp) / 60.0))
print("Train loss: " + str(total_loss))
output_name = params['model_name'] + '_epoch' + str(epoch)
if params['model_type'] == 'sent_avg' or params['model_type'] == 'par_seq' or params['model_type']=='sem_rel':
if params['task'] == 'minority':
test_f05, test_precision, test_recall, test_loss = eval_docs(model, loss_fn, test_data, test_labels,
data, params)
elif params['model_type']== 'sem_rel':
test_accuracy, test_loss = eval_docs(model, loss_fn, test_data, test_labels, data, params)
elif params['task'] == 'class' or params['task'] == 'score_pred':
test_accuracy, test_loss, global_eval_pred, global_avg_deg_test = eval_docs(model, loss_fn, test_data, test_labels, data, params)
print("=========== GLOBAL EVAL PRED ===================")
print(global_eval_pred)
print("=========== GLOBAL EVAL PRED SIZE ===================")
print(len(global_eval_pred))
print("=========== GLOBAL AVG DEG ===================")
print(global_avg_deg_test)
print("=============================GLOBAL AVG DEG TEST SIZE ====================")
print(len(global_avg_deg_test))
# plt.scatter(global_avg_deg_test, global_eval_pred)
# plt.title('EPOCH N°' + str(epoch))
# plt.xlabel('Cosine similarity')
# plt.ylabel('Scores de cohérence')
# plt.show()
elif params['task'] == 'perm':
test_accuracy, test_loss = eval_docs_rank(model, test_docs, data, params)
print("Test loss: %0.3f" % test_loss)
if params['task'] == 'score_pred':
print("Test correlation: %0.5f" % (test_accuracy))
elif params['task'] == 'minority':
print("Test F0.5: %0.2f Precision: %0.2f Recall: %0.2f" % (test_f05, test_precision, test_recall))
else:
print("Test accuracy: %0.2f%%" % (test_accuracy * 100))
elif params['model_type'] == 'clique':
train_accuracy, train_loss = eval_cliques(model, loss_fn, training_data,
training_labels,
params['batch_size'],
params['clique_size'], data,
params['model_type'], params['task'])
if params['task'] == 'score_pred':
print("Train clique corr: %0.5f" % (train_accuracy))
else:
print("Train clique accuracy: %0.2f%%" % (train_accuracy * 100))
test_clique_accuracy, test_loss = eval_cliques(model, loss_fn, test_data,
test_labels,
params['batch_size'],
params['clique_size'], data, params['model_type'], params['task'])
print("Test loss: %0.3f" % test_loss)
if params['task'] == 'score_pred':
print("Test clique corr: %0.5f" % ((test_clique_accuracy)))
else:
print("Test clique accuracy: %0.2f%%" % ((test_clique_accuracy * 100)))
doc_accuracy, test_precision, test_recall, test_f05 = eval_doc_cliques(model, test_docs, data, params)
if params['task'] == 'score_pred':
print("Test document corr: %0.5f" % (doc_accuracy))
elif params['task'] == 'minority':
print("Test F0.5: %0.2f Precision: %0.2f Recall: %0.2f" % (test_f05, test_precision, test_recall))
else:
print("Test document ranking accuracy: %0.2f%%" % (doc_accuracy * 100))
test_accuracy = doc_accuracy
if params['task'] == 'minority':
if test_f05 > best_test_acc:
best_test_acc = test_f05
# save best model
torch.save(model.state_dict(), params['model_dir'] + '/' + params['model_name'] + '_best')
print('saved model ' + params['model_dir'] + '/' + params['model_name'] + '_best')
else:
if test_accuracy > best_test_acc:
best_test_acc = test_accuracy
# save best model
torch.save(model.state_dict(), params['model_dir'] + '/' + params['model_name'] + '_best')
print('saved model ' + params['model_dir'] + '/' + params['model_name'] + '_best')
print()
print("==================== BEST TEST ACCURACY =================================")
print(best_test_acc)
return best_test_acc
def test(params, test_docs, data, model):
if params['model_type'] == 'clique':
test_data, test_labels = data.create_cliques(test_docs, params['task'])
elif params['model_type'] == 'sent_avg':
test_data, test_labels, test_ids = data.create_doc_sents(test_docs, 'sentence', params['task'], params['train_data_limit'])
elif params['model_type'] == 'par_seq':
test_data, test_labels, test_ids = data.create_doc_sents(test_docs, 'paragraph', params['task'], params['train_data_limit'])
if USE_CUDA:
model.cuda()
loss_fn = torch.nn.CrossEntropyLoss()
# output_name = params['model_name'] + '_test'
if params['model_type'] == 'par_seq' or params['model_type'] == 'sent_avg':
test_accuracy, test_loss = eval_docs(model, loss_fn, test_data, test_labels, data, params)
print("Test accuracy: %0.2f%%" % (test_accuracy * 100))
elif params['model_type'] == 'clique':
doc_accuracy = eval_doc_cliques(model, test_docs, data, params)
print("Test document ranking accuracy: %0.2f%%" % (doc_accuracy * 100))