-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolver.py
211 lines (187 loc) · 8.11 KB
/
solver.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
import copy
import numpy as np
import torch
import time
from tqdm import tqdm
class Solver():
def __init__(self, net, criterion, optimizer, train_dataset, valid_dataset) -> None:
super().__init__()
self.net = net
self.criterion = criterion
self.optimizer = optimizer
self.train_dataset = train_dataset
self.valid_dataset = valid_dataset
def train(self, max_epoch=100, disp_freq=-1, check_points=1):
avg_train_loss = 0
avg_val_loss = 0
self.avg_train_loss_set = []
self.avg_val_loss_set = []
train_start = np.inf
valid_start = np.inf
if check_points == 1:
self.all_models = {}
for epoch in range(max_epoch):
starttime = time.time()
batch_train_loss = self.train_one_epoch(max_epoch, disp_freq, epoch)
batch_val_loss = self.validate()
avg_train_loss += batch_train_loss
avg_val_loss += batch_val_loss
self.avg_train_loss_set.append(batch_train_loss)
self.avg_val_loss_set.append(batch_val_loss)
if batch_train_loss < train_start:
train_start = batch_train_loss
self.train_best_model = copy.deepcopy(self.net)
if batch_val_loss < valid_start:
valid_start = batch_val_loss
self.valid_best_model = copy.deepcopy(self.net)
if check_points == 1:
self.all_models['epoch%d' % epoch] = copy.deepcopy(
self.net).cpu().state_dict()
print('Epoch [{}/{}]\t Average training and validation loss: {:.4E} {:.4E}\tTime: {:.2f}s'.format(
epoch + 1, max_epoch, batch_train_loss, batch_val_loss, time.time() - starttime))
def train_one_epoch(self, max_epoch, disp_freq, epoch):
self.net.train()
train_loss = 0
iteration = 0
for data in self.train_dataset:
if torch.cuda.is_available():
for i in range(len(data)):
data[i] = data[i].cuda()
iteration += 1
self.optimizer.zero_grad()
y = self.net(data[0 : -1])
loss = self.criterion(y, data[-1])
# loss = loss.to(torch.double)
loss.backward()
self.optimizer.step()
train_loss += loss.item()
if iteration % disp_freq == 0 and disp_freq > 0:
print("Epoch [{}][{}]\t Batch [{}][{}]\t Training Loss {:.4f}".format(
epoch + 1, max_epoch, iteration, len(self.train_dataset),
train_loss / iteration))
return train_loss / len(self.train_dataset)
def validate(self):
self.net.eval()
data = self.valid_dataset.dataset.data
target = self.valid_dataset.dataset.label
if torch.cuda.is_available():
for i in range(len(data)):
data[i] = data[i].cuda()
target = target.cuda()
with torch.no_grad():
y = self.net(data)
val_loss = self.criterion(y, target)
return val_loss.item()
def train_atten(self, max_epoch=100, disp_freq=-1, check_points=1):
avg_train_loss = 0
avg_val_loss = 0
self.avg_train_loss_set = []
self.avg_val_loss_set = []
train_start = np.inf
valid_start = np.inf
if check_points == 1:
self.all_models = {}
for epoch in range(max_epoch):
starttime = time.time()
batch_train_loss = self.train_one_epoch_atten(max_epoch, disp_freq, epoch)
_, batch_val_loss = self.validate_atten()
avg_train_loss += batch_train_loss
avg_val_loss += batch_val_loss
self.avg_train_loss_set.append(batch_train_loss)
self.avg_val_loss_set.append(batch_val_loss)
if batch_train_loss < train_start:
train_start = batch_train_loss
self.train_best_model = copy.deepcopy(self.net)
if batch_val_loss < valid_start:
valid_start = batch_val_loss
self.valid_best_model = copy.deepcopy(self.net)
if check_points == 1:
self.all_models['epoch%d' % epoch] = copy.deepcopy(
self.net).cpu().state_dict()
print('Epoch [{}/{}]\t Average training and validation loss: {:.4E} {:.4E}\tTime: {:.2f}s'.format(
epoch + 1, max_epoch, batch_train_loss, batch_val_loss, time.time() - starttime))
def train_one_epoch_atten(self, max_epoch, disp_freq, epoch):
self.net.train()
train_loss = 0
iteration = 0
for data, target in self.valid_dataset:
iteration += 1
# GPU加速
self.optimizer.zero_grad()
target_disloc = torch.zeros(target.size()).cuda()
target_disloc[:, 1:, :] = target[:, :-1, :]
y = self.net(data, target_disloc)
loss = self.criterion(y, target)
# loss = loss.to(torch.double)
loss.backward()
self.optimizer.step()
train_loss += loss.item()
if iteration % disp_freq == 0 and disp_freq > 0:
print("Epoch [{}][{}]\t Batch [{}][{}]\t Training Loss {:.4f}".format(
epoch + 1, max_epoch, iteration, len(self.valid_dataset),
train_loss / iteration))
return train_loss / len(self.valid_dataset)
def validate_atten(self):
self.net.eval()
val_loss = 0
prediction = []
for data, target in self.valid_dataset:
# GPU加速
with torch.no_grad():
target_disloc = torch.zeros(target.size()).cuda()
target_disloc[:, 1:, :] = target[:, :-1, :]
y = self.net(data, target_disloc)
prediction.append(y.cpu().detach().numpy())
loss = self.criterion(y, target)
val_loss += loss.item()
prediction = torch.tensor(prediction)
return prediction, val_loss / len(self.valid_dataset)
def test(model, criterion, dataset, batch=0):
test_loss = 0
model.eval()
if batch == 0:
data = dataset.dataset.data
target = dataset.dataset.label
if torch.cuda.is_available():
for i in range(len(data)):
data[i] = data[i].cuda()
target = target.cuda()
with torch.no_grad():
y = model(data)
prediction = y.cpu()
test_loss = criterion(y, target)
else:
data = dataset.dataset.data
target = dataset.dataset.label
if torch.cuda.is_available():
for i in range(len(data)):
data[i] = data[i].cuda()
target = target.cuda()
prediction = torch.zeros_like(target)
num = int(data[0].shape[0] / batch)
for i in range(num):
with torch.no_grad():
prediction[i * batch : i * batch + batch, ...] = model([da[i * batch : i * batch + batch, ...] for da in data])
if num * batch < data[0].shape[0]:
with torch.no_grad():
prediction[num * batch:, ...] = model([da[num * batch:, ...] for da in data])
test_loss = criterion(prediction, target)
prediction = prediction.cpu()
return prediction, test_loss.item()
def test_atten(model, criterion, dataset, batch=0):
test_loss = 0
model.eval()
prediction = []
pbar = tqdm(dataset, desc='计算中', ncols=100)
for data, target in pbar:
# GPU加速
y_temp = torch.zeros(target.shape[0], 1, target.shape[2])
with torch.no_grad():
for i in range(target.shape[-2]):
y = model(data, y_temp)
y_temp = torch.concat([y_temp, y[:, -1:, :]], dim=1)
prediction.append(y.cpu().detach().numpy())
loss = criterion(y, target)
test_loss += loss.item()
prediction = torch.tensor(prediction)
return prediction, test_loss / len(dataset)