-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutil.py
218 lines (174 loc) · 6.83 KB
/
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
from __future__ import print_function
import math
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.utils as vutils
import matplotlib.pyplot as plt
plt.switch_backend('agg')
class TwoCropTransform:
"""Create two crops of the same image"""
def __init__(self, transform):
self.transform = transform
def __call__(self, x):
return [self.transform(x), self.transform(x)]
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 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].view(-1).float().sum(0, keepdim=True)
res.append(correct_k.mul_(100.0 / batch_size))
return res
def adjust_learning_rate(args, optimizer, epoch):
lr = args.learning_rate
if args.cosine:
eta_min = lr * (args.lr_decay_rate ** 3)
lr = eta_min + (lr - eta_min) * (
1 + math.cos(math.pi * epoch / args.epochs)) / 2
else:
steps = np.sum(epoch > np.asarray(args.lr_decay_epochs))
if steps > 0:
lr = lr * (args.lr_decay_rate ** steps)
for param_group in optimizer.param_groups:
param_group['lr'] = lr
def warmup_learning_rate(args, epoch, batch_id, total_batches, optimizer):
if args.warm and epoch <= args.warm_epochs:
p = (batch_id + (epoch - 1) * total_batches) / \
(args.warm_epochs * total_batches)
lr = args.warmup_from + p * (args.warmup_to - args.warmup_from)
for param_group in optimizer.param_groups:
param_group['lr'] = lr
def set_optimizer(opt, model):
optimizer = optim.SGD(model.parameters(),
lr=opt.learning_rate,
momentum=opt.momentum,
weight_decay=opt.weight_decay)
return optimizer
def save_model(model, optimizer, opt, epoch, save_file):
print('==> Saving...')
state = {
'opt': opt,
'model': model.state_dict(),
'optimizer': optimizer.state_dict(),
'epoch': epoch,
}
torch.save(state, save_file)
del state
def ImageShow(data_loader, encoder, decoder, opt, epoch, save=True):
encoder.eval()
decoder.eval()
fake_img, real_img = [], []
for i, (images, labels, idxs) in enumerate(data_loader):
if i > 1:
break
if torch.cuda.is_available():
images = images.cuda(non_blocking=True)
batch_size = labels.size(0)
# inference
_, features, feat_enc = encoder(images.detach())
feat_enc = feat_enc[5].view(batch_size, 1, 32, 64)
out = decoder(feat_enc)
fake_img.append(vutils.make_grid(out.detach().cpu(), padding=2, normalize=True))
real_img.append(vutils.make_grid(images.detach().cpu(), padding=2, normalize=True))
# Plot the fake images from the first epoch
plt.subplot(1, 2, 1)
plt.axis("off")
plt.title("Fake Images")
plt.imshow(np.transpose(fake_img[-1], (1, 2, 0)))
# Plot the real images from the first epoch
plt.subplot(1, 2, 2)
plt.axis("off")
plt.title("Real Images")
plt.imshow(np.transpose(real_img[-1], (1, 2, 0)))
if save:
plt.savefig('./figures/images/alpha_5/real_fake_epoch_{epoch}.jpg'.format(epoch=epoch))
print('**********************')
print('images saved')
else:
plt.show()
plt.close()
def normalization(data):
_range = np.max(data) - np.min(data)
return (data - np.min(data)) / _range
def PSNR(fake_img, ori_img):
MSE = nn.MSELoss()
batch_size = fake_img.size(0)
return - 10 * MSE(fake_img.cuda(), ori_img.cuda()).log10()
def ReconstructionErrorHist(data_loader, encoder, decoder, opt, epoch, save=True):
encoder.eval()
decoder.eval()
all_labels = []
fake_img, real_img = torch.Tensor(), torch.Tensor()
for i, (images, labels, idxs) in enumerate(data_loader):
batch_size = labels.size(0)
# Modify labels first
for ind, k in enumerate(labels):
if k in opt.original_index:
labels[ind] = opt.original_index.index(k)
else:
labels[ind] = len(opt.original_index) # label as last label
if torch.cuda.is_available():
images = images.cuda(non_blocking=True)
labels = labels.cuda(non_blocking=True)
all_labels.append(labels.data.cpu().numpy())
# inference
_, features, feat_enc = encoder(images.detach())
feat_enc = feat_enc[5].view(batch_size, 1, 32, 64)
out = decoder(feat_enc)
# for renconstruction error histogram
real_img = torch.cat([real_img, images.detach().cpu()], dim=0)
fake_img = torch.cat([fake_img, out.detach().cpu()], dim=0)
test_labels = np.concatenate(all_labels, 0)
MSE = nn.MSELoss()
bsz = fake_img.size(0)
match_err = []
unmatch_err = []
for i in range(bsz):
if test_labels[i] == len(opt.original_index):
#unmatch_err.append(torch.mean(torch.abs(fake_img[i] - real_img[i])).data.cpu().numpy())
unmatch_err.append(MSE(fake_img[i], real_img[i]).data.cpu().numpy())
else:
#match_err.append(torch.mean(torch.abs(fake_img[i] - real_img[i])).data.cpu().numpy())
match_err.append(MSE(fake_img[i], real_img[i]).data.cpu().numpy())
match_err = np.array(match_err)
unmatch_err = np.array(unmatch_err)
# print('**********************')
# print('size of matching pairs is {size}'.format(size=match_err.size))
# print('size of unmatching pairs is {size}'.format(size=unmatch_err.size))
# plot histogram of reconstruction error
bins_1 = np.linspace(min(match_err), max(match_err), 300)
bins_2 = np.linspace(min(unmatch_err), max(unmatch_err), 200)
plt.hist(match_err, bins_1, facecolor='g', label='Known')
plt.hist(unmatch_err, bins_2, facecolor='r', label='Unknown')
plt.xlabel('Reconstruction Error')
plt.ylabel('Histogram')
plt.legend()
if save:
plt.savefig('./figures/hist/alpha_5/hist_epoch_{epoch}.jpg'.format(epoch=epoch))
print('**********************')
print('histogram saved')
print('**********************')
else:
plt.show()
plt.close()