-
Notifications
You must be signed in to change notification settings - Fork 2
/
train.py
196 lines (167 loc) · 7.59 KB
/
train.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
# -*- coding: utf-8 -*-
# ------------------
# @Author: BinLiang
# @Mail: bin.liang@stu.hit.edu.cn
# ------------------
import os
import math
import argparse
import random
import numpy
import torch
import torch.nn as nn
from bucket_iterator import BucketIterator
from sklearn import metrics
from data_utils import ABSADatesetReader
from models import CAER
import torch.nn.functional as F
class Instructor:
def __init__(self, opt):
self.opt = opt
absa_dataset = ABSADatesetReader(dataset=opt.dataset, embed_dim=opt.embed_dim)
self.train_data_loader = BucketIterator(data=absa_dataset.train_data, batch_size=opt.batch_size, shuffle=True)
self.test_data_loader = BucketIterator(data=absa_dataset.test_data, batch_size=opt.batch_size, shuffle=False)
self.model = opt.model_class(absa_dataset.embedding_matrix, opt).to(opt.device)
self._print_args()
self.global_f1 = 0.
if torch.cuda.is_available():
print('cuda memory allocated:', torch.cuda.memory_allocated(device=opt.device.index))
def _print_args(self):
n_trainable_params, n_nontrainable_params = 0, 0
for p in self.model.parameters():
n_params = torch.prod(torch.tensor(p.shape)).item()
if p.requires_grad:
n_trainable_params += n_params
else:
n_nontrainable_params += n_params
print('n_trainable_params: {0}, n_nontrainable_params: {1}'.format(n_trainable_params, n_nontrainable_params))
print('> training arguments:')
for arg in vars(self.opt):
print('>>> {0}: {1}'.format(arg, getattr(self.opt, arg)))
def _reset_params(self):
for p in self.model.parameters():
if p.requires_grad:
if len(p.shape) > 1:
self.opt.initializer(p)
else:
stdv = 1. / math.sqrt(p.shape[0])
torch.nn.init.uniform_(p, a=-stdv, b=stdv)
def _train(self, criterion, optimizer):
min_test_loss = 100000
global_step = 0
continue_not_increase = 0
for epoch in range(self.opt.num_epoch):
print('>' * 100)
print('epoch: ', epoch)
n_correct, n_total = 0, 0
increase_flag = False
for i_batch, sample_batched in enumerate(self.train_data_loader):
global_step += 1
self.model.train()
optimizer.zero_grad()
inputs = [sample_batched[col].to(self.opt.device) for col in self.opt.inputs_cols]
outputs, targets = self.model(inputs)
targets = torch.tensor(targets).to(self.opt.device)
loss = criterion(outputs, targets)
loss.backward()
optimizer.step()
if global_step % self.opt.log_step == 0:
print('loss: {:.6f}'.format(loss.item()))
test_loss = self._evaluate_loss()
print('test_loss: {:.6f}'.format(test_loss))
if test_loss < min_test_loss:
increase_flag = True
min_test_loss = test_loss
if self.opt.save and test_f1 > self.global_f1:
self.global_f1 = test_f1
torch.save(self.model.state_dict(), 'state_dict/'+self.opt.model_name+'_'+self.opt.dataset+'.pkl')
print('>>> best model saved.')
if increase_flag == False:
continue_not_increase += 1
if continue_not_increase >= 3:
print('Early stopping.')
break
else:
continue_not_increase = 0
return min_test_loss
def _evaluate_loss(self):
self.model.eval()
n_test_loss, n_test_total = 0, 0
t_targets_all, t_outputs_all = None, None
with torch.no_grad():
for t_batch, t_sample_batched in enumerate(self.test_data_loader):
t_inputs = [t_sample_batched[col].to(opt.device) for col in self.opt.inputs_cols]
t_outputs, t_targets = self.model(t_inputs)
t_targets = torch.tensor(t_targets).to(self.opt.device)
sub_loss = ((t_outputs - t_targets) ** 2) / opt.embed_dim
n_test_loss += F.mse_loss(t_outputs, t_targets)
n_test_total += len(t_outputs)
test_loss = n_test_loss / n_test_total
return test_loss
def run(self):
criterion = nn.MSELoss()
_params = filter(lambda p: p.requires_grad, self.model.parameters())
optimizer = self.opt.optimizer(_params, lr=self.opt.learning_rate, weight_decay=self.opt.l2reg)
if not os.path.exists('log/'):
os.mkdir('log/')
f_out = open('log/'+self.opt.model_name+'_'+self.opt.dataset+'_val.txt', 'w', encoding='utf-8')
self._reset_params()
min_test_loss = self._train(criterion, optimizer)
print('min_test_loss: {0}'.format(min_test_loss))
f_out.write('min_test_loss: {0}'.format(min_test_loss))
f_out.close()
if __name__ == '__main__':
# Hyper Parameters
parser = argparse.ArgumentParser()
parser.add_argument('--model_name', default='caer', type=str)
parser.add_argument('--dataset', default='rest15', type=str, help='sentihood, rest15')
parser.add_argument('--optimizer', default='adam', type=str)
parser.add_argument('--initializer', default='xavier_uniform_', type=str)
parser.add_argument('--learning_rate', default=0.001, type=float)
parser.add_argument('--l2reg', default=0.00001, type=float)
parser.add_argument('--num_epoch', default=100, type=int)
parser.add_argument('--batch_size', default=32, type=int)
parser.add_argument('--log_step', default=5, type=int)
parser.add_argument('--embed_dim', default=300, type=int)
parser.add_argument('--hidden_dim', default=300, type=int)
parser.add_argument('--polarities_dim', default=3, type=int)
parser.add_argument('--save', default=False, type=bool)
parser.add_argument('--seed', default=776, type=int)
parser.add_argument('--device', default=None, type=str)
parser.add_argument('--valset_ratio', default=0, type=float, help='set ratio between 0 and 1 for validation support')
opt = parser.parse_args()
model_classes = {
'caer': CAER,
}
input_colses = {
'caer': ['text_indices', 'aspect_indices', 'target_indices'],
}
initializers = {
'xavier_uniform_': torch.nn.init.xavier_uniform_,
'xavier_normal_': torch.nn.init.xavier_normal,
'orthogonal_': torch.nn.init.orthogonal_,
}
optimizers = {
'adadelta': torch.optim.Adadelta, # default lr=1.0
'adagrad': torch.optim.Adagrad, # default lr=0.01
'adam': torch.optim.Adam, # default lr=0.001
'adamax': torch.optim.Adamax, # default lr=0.002
'asgd': torch.optim.ASGD, # default lr=0.01
'rmsprop': torch.optim.RMSprop, # default lr=0.01
'sgd': torch.optim.SGD,
}
opt.model_class = model_classes[opt.model_name]
opt.inputs_cols = input_colses[opt.model_name]
opt.initializer = initializers[opt.initializer]
opt.optimizer = optimizers[opt.optimizer]
opt.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') \
if opt.device is None else torch.device(opt.device)
if opt.seed is not None:
random.seed(opt.seed)
numpy.random.seed(opt.seed)
torch.manual_seed(opt.seed)
torch.cuda.manual_seed(opt.seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
ins = Instructor(opt)
ins.run()