-
Notifications
You must be signed in to change notification settings - Fork 0
/
trainer.py
319 lines (258 loc) · 14.6 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
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
import os
import cv2
import time
import pdb
from matplotlib import image
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from tqdm import tqdm
from tensorboardX import SummaryWriter
from dataloader import get_loader, gt_to_tensor
from util.utils import AvgMeter
from util.metrics import Evaluation_metrics
from util.losses import Optimizer, Scheduler, Criterion, Criterion_edge
from model.PEN import PEN
class Trainer():
def __init__(self, args, save_path):
self.writer = SummaryWriter(save_path + 'summary')
super(Trainer, self).__init__()
self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
self.size = args.img_size
self.tr_img_folder = os.path.join(args.data_path, args.dataset, 'Train/Image')
self.tr_gt_folder = os.path.join(args.data_path, args.dataset, 'Train/GT_Object')
self.tr_edge_folder = os.path.join(args.data_path, args.dataset, 'Train/GT_Edge')
# pdb.set_trace()
self.train_loader = get_loader(self.tr_img_folder, self.tr_gt_folder, self.tr_edge_folder, train_size=args.img_size, phase='train',
batch_size=args.batch_size, shuffle=True, num_workers=args.num_workers,
augmentation = args.augmentation, seed=args.seed)
self.val_loader = get_loader(self.tr_img_folder, self.tr_gt_folder, self.tr_edge_folder, train_size=args.img_size, phase='val',
batch_size=args.batch_size, shuffle=False, num_workers=args.num_workers,
augmentation = args.augmentation, seed=args.seed)
# Network
self.model = PEN(args).to(self.device)
self.l_weight = [0.7,0.7,1.1,1.1,0.3,0.3,1.3]
if args.multi_gpu:
self.model = nn.DataParallel(self.model).to(self.device)
# Loss and Optimizer
self.criterion = Criterion(args)
self.criterion_edge = Criterion_edge()
self.optimizer = Optimizer(args, self.model)
self.scheduler = Scheduler(args, self.optimizer)
# Train / Validate
min_loss = 1000000000
early_stopping = 0
t = time.time()
for epoch in range(1, args.epochs + 1):
self.epoch = epoch
train_loss, train_mae = self.training(args)
val_loss, val_mae = self.validate()
if args.scheduler == 'Reduce':
self.scheduler.step(val_loss)
else:
self.scheduler.step()
self.writer.add_scalar('lr', self.optimizer.state_dict()['param_groups'][0]['lr'], global_step=epoch)
# Save models
if val_loss < min_loss:
early_stopping = 0
best_epoch = epoch
best_mae = val_mae
min_loss = val_loss
torch.save(self.model.state_dict(), os.path.join(save_path, 'best_model.pth'))
print(f'-----------------SAVE:{best_epoch}epoch----------------')
self.writer.add_scalar('mae',best_mae,epoch)
self.writer.add_scalar('loss',min_loss,epoch)
else:
early_stopping += 1
if early_stopping == args.patience + 10:
break
print(f'\nBest Val Epoch:{best_epoch} | Val Loss:{min_loss:.3f} | Val MAE:{best_mae:.3f} '
f'time: {(time.time() - t) / 60:.3f}M')
# Test time
# datasets = ['DUTS', 'DUT-O', 'HKU-IS', 'ECSSD', 'PASCAL-S']
# for dataset in datasets:
# args.dataset = dataset
# test_loss, test_mae, test_maxf, test_avgf, test_s_m = self.test(args, os.path.join(save_path))
# print(
# f'Test Loss:{test_loss:.3f} | MAX_F:{test_maxf:.3f} | AVG_F:{test_avgf:.3f} | MAE:{test_mae:.3f} '
# f'| S_Measure:{test_s_m:.3f}, time: {time.time() - t:.3f}s')
end = time.time()
print(f'Total Process time:{(end - t) / 60:.3f}Minute')
def training(self, args):
self.model.train()
train_loss = AvgMeter()
train_mae = AvgMeter()
train_edge = AvgMeter()
for images, masks, edges in tqdm(self.train_loader):
images = torch.tensor(images, device=self.device, dtype=torch.float32)
masks = torch.tensor(masks, device=self.device, dtype=torch.float32)
edges = torch.tensor(edges, device=self.device, dtype=torch.float32)
self.optimizer.zero_grad()
outputs, edges_mask, ds_map = self.model(images)
loss1 = self.criterion(outputs, masks)
loss2 = self.criterion(ds_map[0], masks)
loss3 = self.criterion(ds_map[1], masks)
loss4 = self.criterion(ds_map[2], masks)
loss5 = self.criterion(ds_map[3], masks)
loss_mask = self.criterion_edge(edges_mask, edges)
# loss_mask = sum(self.criterion_edge(edge_mask, edges, weight) for edge_mask, weight in zip(edges_mask, self.l_weight))
loss = loss1 + loss2 + loss3 + loss4 + loss5 + loss_mask
loss.backward()
# loss.backward()
nn.utils.clip_grad_norm_(self.model.parameters(), args.clipping)
self.optimizer.step()
# Metric
mae = torch.mean(torch.abs(outputs - masks))
# log
train_loss.update(loss.item(), n=images.size(0))
train_mae.update(mae.item(), n=images.size(0))
train_edge.update(loss_mask.item(), n=images.size(0))
print(f'Epoch:[{self.epoch:03d}/{args.epochs:03d}]')
print(f'Train Loss:{train_loss.avg:.4f} | MAE:{train_mae.avg:.4f} | Train Loss_mask:{train_edge.avg:.4f}')
return train_loss.avg, train_mae.avg
def validate(self):
self.model.eval()
val_loss = AvgMeter()
val_mae = AvgMeter()
val_edge = AvgMeter()
with torch.no_grad():
for images, masks, edges in tqdm(self.val_loader):
images = torch.tensor(images, device=self.device, dtype=torch.float32)
masks = torch.tensor(masks, device=self.device, dtype=torch.float32)
edges = torch.tensor(edges, device=self.device, dtype=torch.float32)
outputs, edges_mask, ds_map = self.model(images)
loss1 = self.criterion(outputs, masks)
loss2 = self.criterion(ds_map[0], masks)
loss3 = self.criterion(ds_map[1], masks)
loss4 = self.criterion(ds_map[2], masks)
loss5 = self.criterion(ds_map[3], masks)
loss_mask = self.criterion_edge(edges_mask, edges)
# loss_mask = sum(self.criterion_edge(edge_mask, edges, weight) for edge_mask, weight in zip(edges_mask, self.l_weight))
loss = loss1 + loss2 + loss3 + loss4 + loss5 + loss_mask
# Metric
mae = torch.mean(torch.abs(outputs - masks))
# log
val_loss.update(loss.item(), n=images.size(0))
val_mae.update(mae.item(), n=images.size(0))
val_edge.update(loss_mask.item(), n=images.size(0))
print(f'Valid Loss:{val_loss.avg:.4f} | MAE:{val_mae.avg:.4f} | Valid Loss_mask:{val_edge.avg:.4f}')
return val_loss.avg, val_mae.avg
def test(self, args, save_path):
path = os.path.join(save_path, 'best_model.pth')
self.model.load_state_dict(torch.load(path))
print('###### pre-trained Model restored #####')
te_img_folder = os.path.join(args.data_path, args.dataset, 'Test/Image')
te_gt_folder = os.path.join(args.data_path, args.dataset, 'Test/GT_Object')
test_loader = get_loader(te_img_folder, te_gt_folder, edge_folder=None, train_size=args.img_size, phase='test',
batch_size=args.batch_size, shuffle=False,
num_workers=args.num_workers, transform=self.test_transform)
self.model.eval()
test_loss = AvgMeter()
test_mae = AvgMeter()
test_maxf = AvgMeter()
test_avgf = AvgMeter()
test_s_m = AvgMeter()
Eval_tool = Evaluation_metrics(args.dataset, self.device)
with torch.no_grad():
for i, (images, masks, original_size, image_name) in enumerate(tqdm(test_loader)):
images = torch.tensor(images, device=self.device, dtype=torch.float32)
outputs, edge_mask, ds_map = self.model(images)
H, W = original_size
for i in range(images.size(0)):
mask = gt_to_tensor(masks[i])
h, w = H[i].item(), W[i].item()
output = F.interpolate(outputs[i].unsqueeze(0), size=(h, w), mode='bilinear')
loss = self.criterion(output, mask)
# Metric
mae, max_f, avg_f, s_score = Eval_tool.cal_total_metrics(output, mask)
# log
test_loss.update(loss.item(), n=1)
test_mae.update(mae, n=1)
test_maxf.update(max_f, n=1)
test_avgf.update(avg_f, n=1)
test_s_m.update(s_score, n=1)
test_loss = test_loss.avg
test_mae = test_mae.avg
test_maxf = test_maxf.avg
test_avgf = test_avgf.avg
test_s_m = test_s_m.avg
return test_loss, test_mae, test_maxf, test_avgf, test_s_m
class Tester():
def __init__(self, args, save_path):
super(Tester, self).__init__()
self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
self.args = args
self.save_path = save_path
# Network
self.model = self.model = PEN(args).to(self.device)
if args.multi_gpu:
self.model = nn.DataParallel(self.model).to(self.device)
path = os.path.join(save_path, 'best_model.pth')
self.model.load_state_dict(torch.load(path))
print('###### pre-trained Model restored #####')
self.criterion = Criterion(args)
te_img_folder = os.path.join(args.data_path, 'TestDataset', args.dataset, 'Imgs')
te_gt_folder = os.path.join(args.data_path, 'TestDataset', args.dataset, 'GT')
self.test_loader = get_loader(te_img_folder, te_gt_folder, edge_folder=None, train_size=args.img_size, phase='test',
batch_size=args.batch_size, shuffle=False,
num_workers=args.num_workers, augmentation=True)
if args.save_map is not None:
os.makedirs(os.path.join('/Data/ZZY/P_Edge_N', 'snapshot', 'exp'+str(self.args.exp_num), self.args.dataset), exist_ok=True)
def test(self):
self.model.eval()
test_loss = AvgMeter()
test_mae = AvgMeter()
test_maxf = AvgMeter()
test_avgf = AvgMeter()
test_s_m = AvgMeter()
t = time.time()
Eval_tool = Evaluation_metrics(self.args.dataset, self.device)
with torch.no_grad():
for i, (images, masks, original_size, image_name) in enumerate(tqdm(self.test_loader)):
images = torch.tensor(images, device=self.device, dtype=torch.float32)
outputs, edges_mask, ds_map = self.model(images)
H, W = original_size
for i in range(images.size(0)):
mask = gt_to_tensor(masks[i])
h, w = H[i].item(), W[i].item()
if image_name[i] == 'animal-62':
w = 998
if image_name[i] == 'animal-74':
h = 678
output = F.interpolate(outputs[i].unsqueeze(0), size=(h, w), mode='bilinear')
loss = self.criterion(output, mask)
# Metric
mae, max_f, avg_f, s_score = Eval_tool.cal_total_metrics(output, mask)
# Save prediction map
if self.args.save_map is not None:
output = (output.squeeze().detach().cpu().numpy()*255.0).astype(np.uint8) # convert uint8 type
# ds_map_0 = (ds_map[0][i].squeeze().detach().cpu().numpy()*255.0).astype(np.uint8) # convert uint8 type
# ds_map_1 = (ds_map[1][i].squeeze().detach().cpu().numpy()*255.0).astype(np.uint8) # convert uint8 type
# ds_map_2 = (ds_map[2][i].squeeze().detach().cpu().numpy()*255.0).astype(np.uint8) # convert uint8 type
# edge_mask = (edges_mask[i].squeeze().detach().cpu().numpy()*255.0).astype(np.uint8) # convert uint8 type
cv2.imwrite(os.path.join('/Data/ZZY/P_Edge_N', 'snapshot', \
'exp'+str(self.args.exp_num), self.args.dataset, image_name[i]+'.png'), output)
# cv2.imwrite(os.path.join('/Data/ZZY/P_Edge_N', 'snapshot', \
# 'exp'+str(self.args.exp_num), 'dissertation_image', image_name[i]+'_map_0.png'), ds_map_0)
# cv2.imwrite(os.path.join('/Data/ZZY/P_Edge_N', 'snapshot', \
# 'exp'+str(self.args.exp_num), 'dissertation_image', image_name[i]+'_map_1.png'), ds_map_1)
# cv2.imwrite(os.path.join('/Data/ZZY/P_Edge_N', 'snapshot', \
# 'exp'+str(self.args.exp_num), 'dissertation_image', image_name[i]+'_map_2.png'), ds_map_2)
# cv2.imwrite(os.path.join('/Data/ZZY/P_Edge_N', 'snapshot', \
# 'exp'+str(self.args.exp_num), 'dissertation_image', image_name[i]+'_edge.png'), edge_mask)
# log
test_loss.update(loss.item(), n=1)
test_mae.update(mae, n=1)
test_maxf.update(max_f, n=1)
test_avgf.update(avg_f, n=1)
test_s_m.update(s_score, n=1)
test_loss = test_loss.avg
test_mae = test_mae.avg
test_maxf = test_maxf.avg
test_avgf = test_avgf.avg
test_s_m = test_s_m.avg
print('--------------test---------------')
print(f'Test Loss:{test_loss:.4f} | MAX_F:{test_maxf:.4f} | MAE:{test_mae:.4f} '
f'| S_Measure:{test_s_m:.4f}, time: {time.time() - t:.3f}s')
return test_loss, test_mae, test_maxf, test_avgf, test_s_m