-
Notifications
You must be signed in to change notification settings - Fork 12
/
common.py
237 lines (195 loc) · 8.2 KB
/
common.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
from __future__ import print_function
import argparse
import os
import shutil
import time
import random
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data as data
import torchvision.transforms as transforms
import torch.nn.functional as F
import models.wrn as models
from dataset import get_cifar10, get_cifar100, get_stl10
from utils import Bar, Logger, AverageMeter, accuracy, mkdir_p, savefig
from tensorboardX import SummaryWriter
from scipy import optimize
def validate(valloader, model, criterion, use_cuda, mode, num_class=10):
batch_time = AverageMeter()
data_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
# switch to evaluate mode
model.eval()
end = time.time()
bar = Bar(f'{mode}', max=len(valloader))
classwise_correct = torch.zeros(num_class)
classwise_num = torch.zeros(num_class)
section_acc = torch.zeros(3)
with torch.no_grad():
for batch_idx, (inputs, targets, _) in enumerate(valloader):
# measure data loading time
data_time.update(time.time() - end)
if use_cuda:
inputs, targets = inputs.cuda(), targets.cuda(non_blocking=True)
# compute output
outputs, _ = model(inputs)
loss = criterion(outputs, targets)
# measure accuracy and record loss
prec1, prec5 = accuracy(outputs, targets, topk=(1, 5))
losses.update(loss.item(), inputs.size(0))
top1.update(prec1.item(), inputs.size(0))
top5.update(prec5.item(), inputs.size(0))
# classwise prediction
pred_label = outputs.max(1)[1]
pred_mask = (targets == pred_label).float()
for i in range(num_class):
class_mask = (targets == i).float()
classwise_correct[i] += (class_mask * pred_mask).sum()
classwise_num[i] += class_mask.sum()
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
# plot progress
bar.suffix = '({batch}/{size}) Data: {data:.3f}s | Batch: {bt:.3f}s | Total: {total:} | ETA: {eta:} | ' \
'Loss: {loss:.4f} | top1: {top1: .4f} | top5: {top5: .4f}'.format(
batch=batch_idx + 1,
size=len(valloader),
data=data_time.avg,
bt=batch_time.avg,
total=bar.elapsed_td,
eta=bar.eta_td,
loss=losses.avg,
top1=top1.avg,
top5=top5.avg,
)
bar.next()
bar.finish()
# Major, Neutral, Minor
section_num = int(num_class / 3)
classwise_acc = (classwise_correct / classwise_num)
section_acc[0] = classwise_acc[:section_num].mean()
section_acc[2] = classwise_acc[-1 * section_num:].mean()
section_acc[1] = classwise_acc[section_num:-1 * section_num].mean()
GM = 1
for i in range(num_class):
if classwise_acc[i] == 0:
# To prevent the N/A values, we set the minimum value as 0.001
GM *= (1/(100 * num_class)) ** (1/num_class)
else:
GM *= (classwise_acc[i]) ** (1/num_class)
return (losses.avg, top1.avg, section_acc.numpy(), GM)
def estimate_pseudo(q_y, saved_q, num_class=10, alpha=2):
pseudo_labels = torch.zeros(len(saved_q), num_class)
k_probs = torch.zeros(num_class)
for i in range(1, num_class + 1):
i = num_class - i
num_i = int(alpha * q_y[i])
sorted_probs, idx = saved_q[:, i].sort(dim=0, descending=True)
pseudo_labels[idx[: num_i], i] = 1
k_probs[i] = sorted_probs[:num_i].sum()
return pseudo_labels, (q_y + 1e-6) / (k_probs + 1e-6)
def f(x, a, b, c, d):
return np.sum(a * b * np.exp(-1 * x/c)) - d
def opt_solver(probs, target_distb, num_iter=10, th=0.1, num_newton=30):
entropy = (-1 * probs * torch.log(probs + 1e-6)).sum(1)
weights = (1 / entropy)
N, K = probs.size(0), probs.size(1)
A, w, lam, nu, r, c = probs.numpy(), weights.numpy(), np.ones(N), np.ones(K), np.ones(N), target_distb.numpy()
A_e = A / math.e
X = np.exp(-1 * lam / w)
Y = np.exp(-1 * nu.reshape(1, -1) / w.reshape(-1, 1))
prev_Y = np.zeros(K)
X_t, Y_t = X, Y
for n in range(num_iter):
# Normalization
denom = np.sum(A_e * Y_t, 1)
X_t = r / denom
# Newton method
Y_t = np.zeros(K)
for i in range(K):
Y_t[i] = optimize.newton(f, prev_Y[i], maxiter=num_newton, args=(A_e[:, i], X_t, w, c[i]), tol=th)
prev_Y = Y_t
Y_t = np.exp(-1 * Y_t.reshape(1, -1) / w.reshape(-1, 1))
denom = np.sum(A_e * Y_t, 1)
X_t = r / denom
M = torch.Tensor(A_e * X_t.reshape(-1, 1) * Y_t)
return M
def make_imb_data(max_num, class_num, gamma):
mu = np.power(1/gamma, 1/(class_num - 1))
class_num_list = []
for i in range(class_num):
if i == (class_num - 1):
class_num_list.append(int(max_num / gamma))
else:
class_num_list.append(int(max_num * np.power(mu, i)))
print(class_num_list)
return list(class_num_list)
def save_checkpoint(state, epoch, checkpoint='none', filename='checkpoint.pth.tar'):
filepath = os.path.join(checkpoint, filename)
torch.save(state, filepath)
if epoch % 100 == 0:
shutil.copyfile(filepath, os.path.join(checkpoint, 'model_' + str(epoch) + '.pth.tar'))
def linear_rampup(current, rampup_length=0):
if rampup_length == 0:
return 1.0
else:
current = np.clip(current / rampup_length, 0.0, 1.0)
return float(current)
class SemiLoss(object):
def __call__(self, args, outputs_x, targets_x, outputs_u, targets_u, epoch, mask=None):
if args.semi_method == 'mix':
probs_u = torch.softmax(outputs_u, dim=1)
Lx = -torch.mean(torch.sum(F.log_softmax(outputs_x, dim=1) * targets_x, dim=1))
Lu = torch.mean((probs_u - targets_u)**2)
return Lx, Lu, args.lambda_u * linear_rampup(epoch, args.epochs)
elif args.semi_method == 'remix':
Lx = -torch.mean(torch.sum(F.log_softmax(outputs_x, dim=1) * targets_x, dim=1))
Lu = -torch.mean(torch.sum(F.log_softmax(outputs_u, dim=1) * targets_u, dim=1))
return Lx, Lu, args.lambda_u * linear_rampup(epoch, args.epochs)
elif args.semi_method == 'fix':
Lx = -torch.mean(torch.sum(F.log_softmax(outputs_x, dim=1) * targets_x, dim=1))
Lu = -torch.mean(torch.sum(F.log_softmax(outputs_u, dim=1) * targets_u, dim=1) * mask)
return Lx, Lu
else:
raise Exception('Wrong type of semi-supervised method (Please select among |mix|remix|fix|)')
class WeightEMA(object):
def __init__(self, model, ema_model, lr=0.002, alpha=0.999):
self.model = model
self.ema_model = ema_model
self.alpha = alpha
self.params = list(model.state_dict().values())
self.ema_params = list(ema_model.state_dict().values())
self.wd = 0.02 * lr
for param, ema_param in zip(self.params, self.ema_params):
param.data.copy_(ema_param.data)
def step(self):
one_minus_alpha = 1.0 - self.alpha
for param, ema_param in zip(self.params, self.ema_params):
# print(ema_param.mean())
ema_param.mul_(self.alpha)
ema_param.add_(param * one_minus_alpha)
# customized weight decay
param.mul_(1 - self.wd)
def interleave_offsets(batch, nu):
groups = [batch // (nu + 1)] * (nu + 1)
for x in range(batch - sum(groups)):
groups[-x - 1] += 1
offsets = [0]
for g in groups:
offsets.append(offsets[-1] + g)
assert offsets[-1] == batch
return offsets
def interleave(xy, batch):
nu = len(xy) - 1
offsets = interleave_offsets(batch, nu)
xy = [[v[offsets[p]:offsets[p + 1]] for p in range(nu + 1)] for v in xy]
for i in range(1, nu + 1):
xy[0][i], xy[i][i] = xy[i][i], xy[0][i]
return [torch.cat(v, dim=0) for v in xy]