-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
163 lines (142 loc) · 5.03 KB
/
utils.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
import os
import random
import torch
import numpy as np
import torch.nn as nn
import torch.optim as optim
import torch.optim.lr_scheduler as lrs
def set_seed(manualSeed=666):
random.seed(manualSeed)
np.random.seed(manualSeed)
torch.manual_seed(manualSeed)
torch.cuda.manual_seed(manualSeed)
torch.cuda.manual_seed_all(manualSeed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
os.environ['PYTHONHASHSEED'] = str(manualSeed)
def make_optimizer(args, my_model, pretrain=False):
trainable = filter(lambda x: x.requires_grad, my_model.parameters())
if pretrain is False:
if args.sep_decay:
wd_term = 0
else:
wd_term = args.weight_decay
if args.optimizer == 'SGD':
optimizer_function = optim.SGD
kwargs = {'momentum': 0.9,
'lr': args.lr,
'weight_decay': wd_term#args.weight_decay
# 'weight_decay': 1e-4
}
elif args.optimizer == 'Adam':
optimizer_function = optim.Adam
kwargs = {
'betas': (0.9, 0.999),
'eps': 1e-08,
'lr': args.lr,
'weight_decay': wd_term#args.weight_decay
# 'weight_decay': 1e-4
}
elif args.optimizer == 'LBFGS':
optimizer_function = optim.LBFGS
kwargs = {'lr': args.lr,
'history_size': args.history_size,
'line_search_fn': 'strong_wolfe'
}
elif pretrain is True:
if args.optimizer_pretrain == 'SGD':
optimizer_function = optim.SGD
kwargs = {'momentum': 0.9,
'lr': args.lr_pretrain,
'weight_decay': 0#args.weight_decay
}
elif args.optimizer_pretrain == 'Adam':
optimizer_function = optim.Adam
kwargs = {
'betas': (0.9, 0.999),
'eps': 1e-08,
'lr': args.lr_pretrain,
'weight_decay': 0#args.weight_decay
}
elif args.optimizer_pretrain == 'LBFGS':
optimizer_function = optim.LBFGS
kwargs = {'lr': args.lr_pretrain,
'history_size': args.history_size,
'line_search_fn': 'strong_wolfe'
}
return optimizer_function(trainable, **kwargs)
def make_scheduler(args, my_optimizer, pretrain=False):
if pretrain is False:
if args.decay_type == 'step':
scheduler = lrs.StepLR(
my_optimizer,
step_size=args.patience,
gamma=args.gamma
)
elif args.decay_type.find('step') >= 0:
milestones = args.decay_type.split('_')
milestones.pop(0)
milestones = list(map(lambda x: int(x), milestones))
scheduler = lrs.MultiStepLR(
my_optimizer,
milestones=milestones,
gamma=args.gamma
)
elif pretrain is True:
if args.decay_type == 'step':
scheduler = lrs.StepLR(
my_optimizer,
step_size=args.patience_pretrain,
gamma=args.gamma_pretrain
)
elif args.decay_type.find('step') >= 0:
milestones = args.decay_type.split('_')
milestones.pop(0)
milestones = list(map(lambda x: int(x), milestones))
scheduler = lrs.MultiStepLR(
my_optimizer,
milestones=milestones,
gamma=args.gamma_pretrain
)
return scheduler
def make_criterion(args):
if args.loss == 'CrossEntropy':
criterion = nn.CrossEntropyLoss()
elif args.loss == 'MSE':
criterion = nn.MSELoss()
return criterion
class AverageMeter(object):
"""Computes and stores the average and current value
Imported from https://github.com/pytorch/examples/blob/master/imagenet/main.py#L247-L262
"""
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 count_network_parameters(model):
parameters = filter(lambda p: p.requires_grad, model.parameters())
return sum([np.prod(p.size()) for p in parameters])
def print_and_save(text_str, file_stream):
print(text_str)
if file_stream is not None:
print(text_str, file=file_stream)
def compute_accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
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].reshape(-1).float().sum(0)
res.append(correct_k.mul_(100.0 / batch_size))
return res