-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
196 lines (168 loc) · 6.61 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
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
import os
import sys
import shutil
import numpy as np
import time, datetime
import torch
import random
import logging
import argparse
import torch.nn as nn
import torch.utils
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torch.backends.cudnn as cudnn
from PIL import Image
from torch.autograd import Variable
#lighting data augmentation
imagenet_pca = {
'eigval': np.asarray([0.2175, 0.0188, 0.0045]),
'eigvec': np.asarray([
[-0.5675, 0.7192, 0.4009],
[-0.5808, -0.0045, -0.8140],
[-0.5836, -0.6948, 0.4203],
])
}
class Lighting(object):
def __init__(self, alphastd,
eigval=imagenet_pca['eigval'],
eigvec=imagenet_pca['eigvec']):
self.alphastd = alphastd
assert eigval.shape == (3,)
assert eigvec.shape == (3, 3)
self.eigval = eigval
self.eigvec = eigvec
def __call__(self, img):
if self.alphastd == 0.:
return img
rnd = np.random.randn(3) * self.alphastd
rnd = rnd.astype('float32')
v = rnd
old_dtype = np.asarray(img).dtype
v = v * self.eigval
v = v.reshape((3, 1))
inc = np.dot(self.eigvec, v).reshape((3,))
img = np.add(img, inc)
if old_dtype == np.uint8:
img = np.clip(img, 0, 255)
img = Image.fromarray(img.astype(old_dtype), 'RGB')
return img
def __repr__(self):
return self.__class__.__name__ + '()'
#label smooth
class CrossEntropyLabelSmooth(nn.Module):
def __init__(self, num_classes, epsilon):
super(CrossEntropyLabelSmooth, self).__init__()
self.num_classes = num_classes
self.epsilon = epsilon
self.logsoftmax = nn.LogSoftmax(dim=1)
def forward(self, inputs, targets):
log_probs = self.logsoftmax(inputs)
targets = torch.zeros_like(log_probs).scatter_(1, targets.unsqueeze(1), 1)
targets = (1 - self.epsilon) * targets + self.epsilon / self.num_classes
loss = (-targets * log_probs).mean(0).sum()
return loss
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self, name, fmt=':f'):
self.name = name
self.fmt = fmt
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 __str__(self):
fmtstr = '{name} {val' + self.fmt + '} ({avg' + self.fmt + '})'
return fmtstr.format(**self.__dict__)
class ProgressMeter(object):
def __init__(self, num_batches, meters, prefix=""):
self.batch_fmtstr = self._get_batch_fmtstr(num_batches)
self.meters = meters
self.prefix = prefix
def display(self, batch):
entries = [self.prefix + self.batch_fmtstr.format(batch)]
entries += [str(meter) for meter in self.meters]
print('\t'.join(entries))
def _get_batch_fmtstr(self, num_batches):
num_digits = len(str(num_batches // 1))
fmt = '{:' + str(num_digits) + 'd}'
return '[' + fmt + '/' + fmt.format(num_batches) + ']'
def save_checkpoint(state, is_best, save, type):
if not os.path.exists(save):
os.makedirs(save)
if type == 0: # mnist_BAN training
filename = os.path.join(save, 'checkpoint_mnist_non_binary.pth.tar')
elif type == 1: # mnist_BNN case1 training
filename = os.path.join(save, 'checkpoint_mnist.pth.tar')
elif type == 2: # Imagenet_BAN training
filename = os.path.join(save, 'checkpoint_imagenet_BAN.pth.tar')
elif type == 3: # Imagenet_BNN case 1 training
filename = os.path.join(save, 'checkpoint_imagenet.pth.tar')
elif type == 4: # mnist_BNN case4 training
filename = os.path.join(save, 'checkpoint_mnist_case4.pth.tar')
elif type == 5: # Imagenet_BNN case 4 training
filename = os.path.join(save, 'checkpoint_imagenet_case4.pth.tar')
elif type == 6: # Imagenet_BNN case 4 training
filename = os.path.join(save, 'checkpoint_imagenet_case1_non_bn.pth.tar')
else:
print('Doom!\n')
sys.exit(0)
torch.save(state, filename)
if is_best:
if type == 0: # mnist_BAN training
best_filename = os.path.join(save, 'model_best_mnist_non_binary.pth.tar')
elif type == 1: # mnist_BNN case 1 training
best_filename = os.path.join(save, 'model_best_mnist.pth.tar')
elif type == 2: # Imagenet_BAN training
best_filename = os.path.join(save, 'model_best_imagenet_BAN.pth.tar')
elif type == 3: # Imagenet_BNN case 1 training
best_filename = os.path.join(save, 'model_best_imagenet.pth.tar')
elif type == 4: # mnist_BNN case 4 training
best_filename = os.path.join(save, 'model_best_mnist_case4.pth.tar')
elif type == 5: # Imagenet_BNN case 4 training
best_filename = os.path.join(save, 'model_best_imagenet_case4.pth.tar')
elif type == 6: # Imagenet_BNN case 4 training
best_filename = os.path.join(save, 'model_best_imagenet_case1_non_bn.pth.tar')
else:
print('Doom!\n')
sys.exit(0)
shutil.copyfile(filename, best_filename)
def adjust_learning_rate(optimizer, epoch, args):
"""Sets the learning rate to the initial LR decayed by 10 every 100 epochs"""
if(epoch < 5): # warm-up
lr = 0.0 + args.learning_rate * epoch / 5
else:
lr = args.learning_rate * (0.1 ** (epoch // 100))
if epoch >= 150:
lr = lr * 0.1
#print(' Learning rate:', lr)
for param_group in optimizer.param_groups:
param_group['lr'] = lr
return lr
def adjust_learning_rate_mnist(optimizer, epoch, args):
"""Sets the learning rate to the initial LR decayed by 10 every lr_epochs(default:15) epochs"""
lr = args.learning_rate * (0.1 ** (epoch // args.lr_epochs))
#print(' Learning rate:', lr)
for param_group in optimizer.param_groups:
param_group['lr'] = lr
return lr
def accuracy(output, target, topk=(1,)):
"""Computes the accuracy over the k top predictions 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].reshape(-1).float().sum(0, keepdim=True)
res.append(correct_k.mul_(100.0 / batch_size))
return res