forked from yechengxi/deconvolution
-
Notifications
You must be signed in to change notification settings - Fork 0
/
net_util.py
344 lines (239 loc) · 8.72 KB
/
net_util.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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
from __future__ import print_function
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
import torchvision
import torchvision.transforms as transforms
import os
import argparse
import time
from copy import deepcopy
from torch.autograd import Variable
from util import tensor2array
import shutil
def set_parameters(args):
'''
This function is called before training/testing to set parameters
:param args:
:return args:
'''
if not args.__contains__('train_losses'):
args.train_losses=[]
if not args.__contains__('train_accuracies'):
args.train_accuracies = []
if not args.__contains__('valid_losses'):
args.valid_losses = []
if not args.__contains__('valid_accuracies'):
args.valid_accuracies = []
if not args.__contains__('test_losses'):
args.test_losses = []
if not args.__contains__('test_accuracies'):
args.test_accuracies = []
if not args.__contains__('best_acc'):
args.best_acc = 0.0
if not args.__contains__('lowest_loss'):
args.lowest_loss = 1e4
if not args.__contains__('checkpoint_path'):
args.checkpoint_path = 'checkpoints'
if not os.path.exists(args.checkpoint_path):
os.makedirs(args.checkpoint_path)
if not args.__contains__('checkpoint_epoch'):
args.checkpoint_epoch = 5
def train_net(net,args):
top1 = AverageMeter()
top5 = AverageMeter()
losses = AverageMeter()
print('training at epoch {}'.format(args.epoch+1))
net.train()
total_time=0
data_time=0
total=1e-3
correct=0
extra=0.
optimizer=args.current_optimizer
end_time = time.time()
for batch_idx, (inputs, targets) in enumerate(args.data_loader):
#ff
if args.use_gpu:
targets = targets.cuda()
data_time += (time.time() - end_time)#loading time
outputs = net(inputs)
maps=None
if type(outputs) is list:
maps=outputs
outputs=outputs[-1]
#loss = args.criterion(outputs, targets).mean()
if args.loss=='CE':
loss = args.criterion(outputs, targets)#.mean()
elif args.loss=='L2':
from util import targets_to_one_hot
targets_one_hot=targets_to_one_hot(targets,args.num_outputs)
loss = args.criterion(outputs, targets_one_hot)*args.num_outputs*0.5
losses.update(loss.item(), inputs.size(0))
prec1, prec5 = accuracy(outputs.data, targets, topk=(1, 5))
top1.update(prec1[0].item(), inputs.size(0))
top5.update(prec5[0].item(), inputs.size(0))
#bp
loss.backward()
optimizer.step()
if args.lr_scheduler == 'cosine':
args.current_scheduler.step()
if args.tensorboard:
if args.logger_n_iter%args.print_freq==0:
args.writer.add_scalar('loss', loss.item(), args.logger_n_iter )
args.logger_n_iter += 1
optimizer.zero_grad() # flush
total_time += (time.time() - end_time)
end_time = time.time()
if args.msg:
print('Loss: %.3f | top1: %.3f%% ,top5: %.3f%%'
% (losses.avg, top1.avg, top5.avg))
args.train_batch_logger.log({
'epoch': (args.epoch+1),
'batch': batch_idx + 1,
'loss': losses.avg,
'top1': top1.avg,
'top5': top5.avg,
'time': total_time,
})
args.train_epoch_logger.log({
'epoch': (args.epoch+1),
'loss': losses.avg,
'top1': top1.avg,
'top5':top5.avg,
'time': total_time,
})
print('Loss: %.3f | top1: %.3f%%, top5: %.3f%% elasped time: %3.f seconds.'
% (losses.avg, top1.avg, top5.avg, total_time))
args.train_accuracies.append(top1.avg)
args.train_losses.append(losses.avg)
def eval_net(net,args):
top1 = AverageMeter()
top5 = AverageMeter()
losses = AverageMeter()
if args.validating:
print('Validating at epoch {}'.format(args.epoch + 1))
if args.testing:
print('Testing at epoch {}'.format(args.epoch + 1))
if not args.__contains__('validating'):
args.validating = False
if not args.__contains__('testing'):
args.testing = False
net.eval()
total = 1e-3
total_time = 0
end_time = time.time()
for batch_idx, (inputs, targets) in enumerate(args.data_loader):
with torch.no_grad():
if args.use_gpu:
targets = targets.cuda()
outputs = net(inputs)
if type(outputs) is list:
outputs = outputs[-1]
if args.loss == 'CE':
loss = args.criterion(outputs, targets) # .mean()
elif args.loss == 'L2':
from util import targets_to_one_hot
targets_one_hot = targets_to_one_hot(targets, args.num_outputs)
loss = args.criterion(outputs, targets_one_hot)*args.num_outputs*0.5
losses.update(loss.item(), inputs.size(0))
prec1, prec5 = accuracy(outputs, targets, topk=(1, 5))
top1.update(prec1[0].item(), inputs.size(0))
top5.update(prec5[0].item(), inputs.size(0))
total_time += (time.time() - end_time)
end_time = time.time()
if args.msg:
print('Loss: %.3f | top1: %.3f%% ,top5: %.3f%%'
% (losses.avg, top1.avg, top5.avg))
if args.testing:
args.test_losses.append(losses.avg)
args.test_accuracies.append(top1.avg)
args.test_epoch_logger.log({
'epoch': (args.epoch + 1),
'loss': losses.avg,
'top1': top1.avg,
'top5': top5.avg,
'time': total_time,
})
if args.validating:
args.valid_losses.append(losses.avg)
args.valid_accuracies.append(top1.avg)
args.valid_epoch_logger.log({
'epoch': (args.epoch + 1),
'loss': losses.avg,
'top1': top1.avg,
'top5': top5.avg,
'time': total_time,
})
# Save checkpoint.
is_best=(top1.avg > args.best_acc)
if is_best:
args.best_acc = top1.avg
states = {
'state_dict': net.module.state_dict() if hasattr(net,'module') else net.state_dict(),
'epoch': args.epoch+1,
'arch': args.arch,
'best_acc': args.best_acc,
'train_losses': args.train_losses,
'optimizer': args.current_optimizer.state_dict()
}
if args.__contains__('acc'):
states['acc']=top1.avg,
if args.__contains__('valid_losses'):
states['valid_losses']=args.valid_losses
if args.__contains__('test_losses'):
states['test_losses'] = args.test_losses
if (args.checkpoint_epoch > 0):
if not os.path.isdir(args.checkpoint_path):
os.mkdir(args.checkpoint_path)
save_file_path = os.path.join(args.checkpoint_path, 'checkpoint.pth.tar')
torch.save(states, save_file_path)
if is_best:
shutil.copyfile(save_file_path, os.path.join(args.checkpoint_path,'model_best.pth.tar'))
print('Loss: %.3f | top1: %.3f%%, top5: %.3f%%, elasped time: %3.f seconds. Best Acc: %.3f%%'
% (losses.avg , top1.avg, top5.avg, total_time, args.best_acc))
import csv
class Logger(object):
def __init__(self, path, header):
self.log_file = open(path, 'w')
self.logger = csv.writer(self.log_file, delimiter='\t')
self.logger.writerow(header)
self.header = header
def __del(self):
self.log_file.close()
def log(self, values):
write_values = []
for col in self.header:
assert col in values
write_values.append(values[col])
self.logger.writerow(write_values)
self.log_file.flush()
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
with torch.no_grad():
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)
res.append(correct_k.mul_(100.0 / batch_size))
return res