-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers.py
334 lines (250 loc) · 11.6 KB
/
helpers.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
import os
import time
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torch.utils.data.sampler import BatchSampler, SubsetRandomSampler
from config.utils import *
import lp.db_semisuper as db_semisuper
import lp.db_eval as db_eval
from models import *
import itertools
import torch.backends.cudnn as cudnn
import torchvision
class StreamBatchSampler(Sampler):
def __init__(self, primary_indices, batch_size):
self.primary_indices = primary_indices
self.primary_batch_size = batch_size
def __iter__(self):
primary_iter = iterate_eternally(self.primary_indices)
return (primary_batch for (primary_batch)
in grouper(primary_iter, self.primary_batch_size)
)
def __len__(self):
return len(self.primary_indices) // self.primary_batch_size
def iterate_eternally(indices):
def infinite_shuffles():
while True:
yield np.random.permutation(indices)
return itertools.chain.from_iterable(infinite_shuffles())
def grouper(iterable, n):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3) --> ABC DEF"
args = [iter(iterable)] * n
return zip(*args)
def create_data_loaders_simple(weak_transformation,strong_transformation,
eval_transformation,
datadir,
args):
traindir = os.path.join(datadir, args.train_subdir)
evaldir = os.path.join(datadir, args.eval_subdir)
with open(args.labels) as f:
labels = dict(line.split(' ') for line in f.read().splitlines())
dataset = db_semisuper.DBSS(traindir, labels , False , args.aug_num , eval_transformation,weak_transformation,strong_transformation)
sampler = SubsetRandomSampler(dataset.labeled_idx)
batch_sampler = BatchSampler(sampler, args.batch_size, drop_last=True)
train_loader = torch.utils.data.DataLoader(dataset,batch_sampler=batch_sampler,num_workers=args.workers,pin_memory=True)
train_loader_noshuff = torch.utils.data.DataLoader(dataset,
batch_size=args.batch_size,
shuffle=False,
num_workers=args.workers,
pin_memory=True,
drop_last=True)
eval_dataset = db_eval.DBE(evaldir, False, eval_transformation)
eval_loader = torch.utils.data.DataLoader(
eval_dataset,
batch_size=args.batch_size,
shuffle=False,
num_workers=args.workers,
pin_memory=True,
drop_last=True)
batch_sampler_l = StreamBatchSampler(dataset.labeled_idx, batch_size=args.labeled_batch_size)
batch_sampler_u = BatchSampler(SubsetRandomSampler(dataset.unlabeled_idx), batch_size=args.batch_size - args.labeled_batch_size, drop_last=True)
train_loader_l = DataLoader(dataset, batch_sampler=batch_sampler_l,
num_workers=args.workers,
pin_memory=True)
train_loader_u = DataLoader(dataset, batch_sampler=batch_sampler_u,
num_workers=args.workers,
pin_memory=True)
return train_loader, eval_loader, train_loader_noshuff , train_loader_l , train_loader_u , dataset
#### Create Model
def create_model(num_classes,args):
model_choice = args.model
if model_choice == "resnet18":
model = resnet18(num_classes)
elif model_choice == "resnet50":
model = resnet50(num_classes)
elif model_choice == "wrn-28-2":
model = build_wideresnet(28,2,0,num_classes)
elif model_choice == "wrn-28-8":
model = build_wideresnet(28,8,0,num_classes)
elif model_choice == "cifarcnn":
model = cifar_cnn(num_classes)
model = nn.DataParallel(model)
model.to(args.device)
cudnn.benchmark = True
return model
def hellinger(p,q):
return np.sqrt(np.sum((np.sqrt(p)-np.sqrt(q))**2))/np.sqrt(2)
def mixup_data(x_1 , index , lam):
mixed_x_1 = lam * x_1 + (1 - lam) * x_1[index, :]
return mixed_x_1
def mixup_criterion(pred, y_a, y_b, lam):
criterion = nn.CrossEntropyLoss(reduction='none').cuda()
return lam * criterion(pred, y_a) + (1 - lam) * criterion(pred, y_b)
def train_sup(train_loader, model, optimizer, epoch, global_step, args, ema_model = None):
# switch to train mode
model.train()
for i, (aug_images , target) in enumerate(train_loader):
target = target.to(args.device)
#Create the mix
alpha = args.alpha
index = torch.randperm(args.batch_size,device=args.device)
lam = np.random.beta(alpha, alpha)
target_a, target_b = target, target[index]
optimizer.zero_grad()
adjust_learning_rate(optimizer, epoch, i, len(train_loader), args)
# Loop over the batches
count = 0
for batch in aug_images:
batch = batch.to(args.device)
m_batch = mixup_data(batch,index,lam)
class_logit , _ = model(m_batch)
if count == 0:
loss_sum = mixup_criterion(class_logit.double(), target_a , target_b , lam).mean()
else:
loss_sum += mixup_criterion(class_logit.double(), target_a , target_b , lam).mean()
count += 1
loss = loss_sum / (args.aug_num)
loss.backward()
optimizer.step()
global_step += 1
return global_step
def train_semi(train_loader_l, train_loader_u , model, optimizer, epoch, global_step, args, ema_model = None):
# switch to train mode
model.train()
lr_length = len(train_loader_u)
train_loader_l = iter(train_loader_l)
if args.progress == True:
from tqdm import tqdm
from torchnet import meter
tk0 = tqdm(train_loader_u,desc="Semi Supervised Learning Epoch " + str(epoch) + "/" +str(args.epochs),unit="batch")
loss_meter = meter.AverageValueMeter()
else:
tk0 = train_loader_u
for i, (aug_images_u,target_u) in enumerate(tk0):
aug_images_l,target_l = next(train_loader_l)
target_l = target_l.to(args.device)
target_u = target_u.to(args.device)
target = torch.cat((target_l,target_u),0)
#Create the mix
alpha = args.alpha
index = torch.randperm(args.batch_size,device=args.device)
lam = np.random.beta(alpha, alpha)
target_a, target_b = target, target[index]
optimizer.zero_grad()
adjust_learning_rate(optimizer, epoch, i, lr_length, args)
count = 0
for batch_l , batch_u in zip(aug_images_l ,aug_images_u):
batch_l = batch_l.to(args.device)
batch_u = batch_u.to(args.device)
batch = torch.cat((batch_l,batch_u),0)
m_batch = mixup_data(batch,index,lam)
class_logit , _ = model(m_batch)
if count == 0:
loss_sum = mixup_criterion(class_logit.double() , target_a , target_b , lam).mean()
else:
loss_sum += mixup_criterion(class_logit.double() , target_a , target_b , lam).mean()
count += 1
loss = loss_sum / (args.aug_num)
loss.backward()
optimizer.step()
if args.progress == True:
loss_meter.add(loss.item())
tk0.set_postfix(loss=loss_meter.mean)
global_step += 1
return global_step
def validate(eval_loader, model, args, global_step, epoch, num_classes =10):
meters = AverageMeterSet()
maxk = 5
if num_classes < 5:
maxk = num_classes
with torch.no_grad():
for batch_idx, (inputs, targets) in enumerate(eval_loader):
batch_size = targets.size(0)
model.eval()
inputs = inputs.to(args.device)
targets = targets.to(args.device)
# print(f'inputs.shape; {inputs.shape}') # inputs.shape; torch.Size([50, 3, 224, 224]) batch_size, channel, height, width
outputs,_ = model(inputs)
# print(f'outputs.shape; {outputs.shape}')
prec1, prec5 = accuracy(outputs, targets, topk=(1, maxk))
# measure accuracy and record loss
prec1, prec5 = accuracy(outputs, targets, topk=(1, maxk))
meters.update('top1', prec1.item(), batch_size)
meters.update('error1', 100.0 - prec1.item(), batch_size)
meters.update('top5', prec5.item(), batch_size)
meters.update('error5', 100.0 - prec5.item(), batch_size)
print(' * Prec@1 {top1.avg:.3f}\tPrec@5 {top5.avg:.3f}'
.format(top1=meters['top1'], top5=meters['top5']))
return meters['top1'].avg, meters['top5'].avg
def 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.reshape(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
def cosine_rampdown(current, rampdown_length):
"""Cosine rampdown from https://arxiv.org/abs/1608.03983"""
assert 0 <= current <= rampdown_length
return float(.5 * (np.cos(np.pi * current / rampdown_length) + 1))
def adjust_learning_rate(optimizer, epoch, step_in_epoch, total_steps_in_epoch, args):
lr = args.lr
epoch = epoch + step_in_epoch / total_steps_in_epoch
# Cosine LR rampdown from https://arxiv.org/abs/1608.03983 (but one cycle only)
if args.lr_rampdown_epochs:
assert args.lr_rampdown_epochs >= args.epochs
lr *= cosine_rampdown(epoch, args.lr_rampdown_epochs)
for param_group in optimizer.param_groups:
param_group['lr'] = lr
def extract_features_simp(train_loader,model,args):
model.eval()
embeddings_all = []
with torch.no_grad():
for i, (batch_input) in enumerate(train_loader):
X_n = batch_input[0].to(args.device)
_ , feats = model(X_n)
embeddings_all.append(feats.data.cpu())
embeddings_all = np.asarray(torch.cat(embeddings_all).numpy())
return embeddings_all
def load_args(args):
args.workers = 4 * torch.cuda.device_count()
label_dir = 'data-local/'
if int(args.label_split) < 10:
args.label_split = args.label_split.zfill(2)
# args.label_split = str(args.label_split).zfill(2)
if args.dataset == "cifar100":
args.test_batch_size = args.batch_size
args.labels = '%s/labels/%s/%d_balanced_labels/%s.txt' % (label_dir,args.dataset,args.num_labeled,args.label_split)
elif args.dataset == "cifar10":
args.test_batch_size = args.batch_size
args.labels = '%s/labels/%s/%d_balanced_labels/%s.txt' % (label_dir,args.dataset,args.num_labeled,args.label_split)
elif args.dataset == "miniimagenet":
args.train_subdir = 'train'
args.test_batch_size = args.batch_size
args.labels = '%s/labels/%s/%d_balanced_labels/%s.txt' % (label_dir,args.dataset,args.num_labeled,args.label_split)
elif args.dataset == "custom":
#args.train_subdir = 'train'
args.test_batch_size = args.batch_size
args.labels = '%s/labels/%s/%s/%d_balanced_labels/%s.txt' % (label_dir,args.dataset,args.datadir,args.num_labeled,args.label_split)
else:
sys.exit('Undefined dataset!')
return args