-
Notifications
You must be signed in to change notification settings - Fork 1
/
train_utils.py
1507 lines (1190 loc) · 55.2 KB
/
train_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
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from collections import defaultdict
import csv
import random
import time
from imagenet16 import ImageNet16
import torch
import numpy as np
import copy
import os
from torch.utils.data import Dataset, Subset, DataLoader
from torch.utils.data.dataset import random_split
from torchvision.datasets.folder import default_loader
import torchvision.datasets as datasets
import torch.optim as optim
import torch.nn as nn
import torch.optim as optim
from torch.optim.lr_scheduler import StepLR, CosineAnnealingLR
from torchvision import datasets
from torchvision.transforms import Resize, ToTensor, Normalize, Compose, \
RandomHorizontalFlip, RandomCrop, RandomRotation, RandomErasing, RandomResizedCrop, CenterCrop, \
TrivialAugmentWide, InterpolationMode
from torch.utils.data import Dataset
from torchvision.datasets.folder import default_loader
from torchvision.transforms import v2
from torch.nn.modules.batchnorm import _BatchNorm
import torch.nn.functional as F
class LoadingBar:
def __init__(self, length: int = 40):
self.length = length
self.symbols = ['┈', '░', '▒', '▓']
def __call__(self, progress: float) -> str:
p = int(progress * self.length*4 + 0.5)
d, r = p // 4, p % 4
return '┠┈' + d * '█' + ((self.symbols[r]) + max(0, self.length-1-d) * '┈' if p < self.length*4 else '') + "┈┨"
class Log:
def __init__(self, log_each: int, initial_epoch=-1):
self.loading_bar = LoadingBar(length=27)
self.best_accuracy = 0.0
self.log_each = log_each
self.epoch = initial_epoch
self.best_model = None
self.best_loss = float('inf')
def train(self, model, optim, len_dataset: int) -> None:
self.epoch += 1
if self.epoch == 0:
self._print_header()
else:
self.flush(model, optim)
self.is_train = True
self.last_steps_state = {"loss": 0.0, "accuracy": 0.0, "steps": 0}
self._reset(len_dataset)
def eval(self, model, optim, len_dataset: int) -> None:
self.flush(model, optim)
self.is_train = False
self._reset(len_dataset)
def __call__(self, model, loss, accuracy, learning_rate: float = None) -> None:
if self.is_train:
self._train_step(model, loss, accuracy, learning_rate)
else:
self._eval_step(loss, accuracy)
def flush(self, model, optim) -> None:
if self.is_train:
loss = self.epoch_state["loss"] / self.epoch_state["steps"]
accuracy = self.epoch_state["accuracy"] / self.epoch_state["steps"]
print(
f"\r┃{self.epoch:12d} ┃{loss:12.4f} │{100*accuracy:10.2f} % ┃{self.learning_rate:12.3e} │{self._time():>12} ┃",
end="",
flush=True,
)
else:
loss = self.epoch_state["loss"] / self.epoch_state["steps"]
accuracy = self.epoch_state["accuracy"] / self.epoch_state["steps"]
print(f"{loss:12.4f} │{100*accuracy:10.2f} % ┃", flush=True)
if loss<self.best_loss: #accuracy > self.best_accuracy:
#print('LOSS: ', loss, 'BEST LOSS: ', self.best_loss)
self.best_accuracy = accuracy
self.best_loss = loss
#save the state of the best model
#self.best_model = {'weights_state': model.state_dict(), 'optim_state':optim.state_dict()}
def _train_step(self, model, loss, accuracy, learning_rate: float) -> None:
self.learning_rate = learning_rate
self.last_steps_state["loss"] += (loss.item() * accuracy.size(0)) #sum().item()
self.last_steps_state["accuracy"] += accuracy.sum().item()
self.last_steps_state["steps"] += accuracy.size(0) #loss.size(0)
self.epoch_state["loss"] += (loss.item() * accuracy.size(0)) #sum().item()
self.epoch_state["accuracy"] += accuracy.sum().item()
self.epoch_state["steps"] += accuracy.size(0) #loss.size(0)
self.step += 1
if self.step % self.log_each == self.log_each - 1:
loss = self.last_steps_state["loss"] / self.last_steps_state["steps"]
accuracy = self.last_steps_state["accuracy"] / self.last_steps_state["steps"]
self.last_steps_state = {"loss": 0.0, "accuracy": 0.0, "steps": 0}
progress = self.step / self.len_dataset
print(
f"\r┃{self.epoch:12d} ┃{loss:12.4f} │{100*accuracy:10.2f} % ┃{learning_rate:12.3e} │{self._time():>12} {self.loading_bar(progress)}",
end="",
flush=True,
)
def _eval_step(self, loss, accuracy) -> None:
self.epoch_state["loss"] += (loss.item() * accuracy.size(0)) #sum().item()
self.epoch_state["accuracy"] += accuracy.sum().item()
self.epoch_state["steps"] += accuracy.size(0) #loss.size(0)
def _reset(self, len_dataset: int) -> None:
self.start_time = time.time()
self.step = 0
self.len_dataset = len_dataset
self.epoch_state = {"loss": 0.0, "accuracy": 0.0, "steps": 0}
def _time(self) -> str:
time_seconds = int(time.time() - self.start_time)
return f"{time_seconds // 60:02d}:{time_seconds % 60:02d} min"
def _print_header(self) -> None:
print(f"┏━━━━━━━━━━━━━━┳━━━━━━━╸T╺╸R╺╸A╺╸I╺╸N╺━━━━━━━┳━━━━━━━╸S╺╸T╺╸A╺╸T╺╸S╺━━━━━━━┳━━━━━━━╸V╺╸A╺╸L╺╸I╺╸D╺━━━━━━━┓")
print(f"┃ ┃ ╷ ┃ ╷ ┃ ╷ ┃")
print(f"┃ epoch ┃ loss │ accuracy ┃ l.r. │ elapsed ┃ loss │ accuracy ┃")
print(f"┠──────────────╂──────────────┼──────────────╂──────────────┼──────────────╂──────────────┼──────────────┨")
def save_checkpoint(model, optimizer, filename='checkpoint.pth'):
checkpoint = {
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
}
torch.save(checkpoint, filename)
def load_checkpoint(model, optimizer, device, filename='checkpoint.pth'):
checkpoint = torch.load(filename, map_location=device)
model.load_state_dict(checkpoint['model_state_dict'])
optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
'''
model.to(device)
for state in optimizer.state.values():
if isinstance(state, torch.Tensor):
state.data = state.data.to(device)
elif isinstance(state, dict):
for k, v in state.items():
if isinstance(v, torch.Tensor):
state[k] = v.to(device)
'''
return model, optimizer
def train(train_loader, val_loader, num_epochs, model, device, optimizer, criterion, scheduler, log, ckpt_path=None, label_smoothing=0.1):
model.to(device)
best_model = copy.deepcopy({'state_dict': model.state_dict(), 'optimizer': optimizer.state_dict()}) #initialize best model with the first model
for epoch in range(num_epochs):
model.train()
log.train(model, optimizer, len_dataset=len(train_loader))
for (inputs,targets) in train_loader:
#inputs = F.interpolate(inputs, size=180, mode='bicubic', align_corners=False)
inputs, targets = inputs.to(device), targets.to(device)
# first forward-backward step
if isinstance(optimizer, SAM):
enable_running_stats(model)
else:
optimizer.zero_grad()
predictions = model(inputs)
loss = criterion(predictions, targets)
loss.backward()
if not isinstance(optimizer, SAM):
optimizer.step()
else:
optimizer.first_step(zero_grad=True)
# second forward-backward step
disable_running_stats(model)
criterion(model(inputs), targets).backward()
optimizer.second_step(zero_grad=True)
with torch.no_grad():
correct = torch.argmax(predictions.data, 1) == targets
log(model, loss.cpu(), correct.cpu(), scheduler.get_last_lr()[0])
scheduler.step()
model.eval()
log.eval(model, optimizer, len_dataset=len(val_loader))
with torch.no_grad():
for batch in val_loader:
inputs, targets = (b.to(device) for b in batch)
predictions = model(inputs)
loss = criterion(predictions, targets)
correct = torch.argmax(predictions, 1) == targets
log(model, loss.cpu(), correct.cpu())
curr_loss=log.epoch_state["loss"] / log.epoch_state["steps"]
if curr_loss < log.best_loss:
best_model = copy.deepcopy({'state_dict': model.state_dict(), 'optimizer': optimizer.state_dict()})
log.flush(model, optimizer)
model.load_state_dict(best_model['state_dict']) # load best model for inference
optimizer.load_state_dict(best_model['optimizer']) # load optim for further training
if ckpt_path is not None:
save_checkpoint(model, optimizer, ckpt_path)
top1=log.best_accuracy
return top1, model, optimizer
'''
def train(train_loader, val_loader, num_epochs, model, device, criterion, optimizer, print_freq=10, ckpt='ckpt'):
batch_time = AverageMeter('Time', ':6.3f')
top1 = AverageMeter('Acc@1', ':6.2f')
progress = ProgressMeter(len(train_loader), [batch_time, top1], prefix='Train: ')
model = model.to(device)
for epoch in range(num_epochs):
# Training phase
model.train()
end = time.time()
for i, (images, labels) in enumerate(train_loader):
images, labels = images.to(device), labels.to(device)
optimizer.zero_grad()
outputs = model(images)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
# Update training statistics
acc1 = accuracy(outputs, labels, topk=(1,))
top1.update(acc1[0].cpu().numpy()[0], images.size(0))
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % print_freq == 0:
progress.display(i)
# Validation phase
model.eval()
top1_val = validate(val_loader, model, device, print_freq) # Reuse the validate function
# Print training and validation statistics
print(f'Train Epoch: {epoch + 1}, Train Accuracy: {top1.avg:.2f}%, Val Accuracy: {top1_val:.2f}%')
# Save the trained model weights
save_checkpoint(model, optimizer, ckpt)
def train_mix(train_loader, val_loader, num_epochs, model, n_classes, device, criterion, optimizer, print_freq=10, ckpt='ckpt'):
batch_time = AverageMeter('Time', ':6.3f')
top1 = AverageMeter('Acc@1', ':6.2f')
progress = ProgressMeter(len(train_loader), [batch_time, top1], prefix='Train: ')
model = model.to(device)
cutmix = v2.CutMix(num_classes=n_classes)
mixup = v2.MixUp(num_classes=n_classes)
cutmix_or_mixup = v2.RandomChoice([cutmix, mixup])
for epoch in range(num_epochs):
# Training phase
model.train()
end = time.time()
for i, (images, labels) in enumerate(train_loader):
images, ori_labels = images.to(device), labels.to(device)
images, labels = cutmix_or_mixup(images, ori_labels)
optimizer.zero_grad()
outputs = model(images)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
# Update training statistics
acc1 = accuracy(outputs, ori_labels, topk=(1,))
top1.update(acc1[0].cpu().numpy()[0], images.size(0))
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % print_freq == 0:
progress.display(i)
# Validation phase
model.eval()
top1_val = validate(val_loader, model, device, print_freq) # Reuse the validate function
# Print training and validation statistics
print(f'Train Epoch: {epoch + 1}, Train Accuracy: {top1.avg:.2f}%, Val Accuracy: {top1_val:.2f}%')
# Save the trained model weights
save_checkpoint(model, optimizer, ckpt)
'''
def validate(val_loader, model, device=None, print_info=True, print_freq=0):
batch_time = AverageMeter('Time', ':6.3f')
top1 = AverageMeter('Acc@1', ':6.2f')
progress = ProgressMeter(len(val_loader), [batch_time, top1], prefix='Test: ')
model.to(device)
device = next(model.parameters()).device
print(f"Model is on device: {device}")
# switch to evaluate mode
model.eval()
with torch.no_grad():
end = time.time()
for i, (images, target) in enumerate(val_loader):
images, target = images.to(device), target.to(device)
# compute output
output = model(images)
# measure accuracy and record loss
acc1 = accuracy(output, target, topk=(1, ))
top1.update(acc1[0].cpu().numpy()[0], images.size(0))
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if print_info and print_freq and i % print_freq == 0:
progress.display(i)
if print_info:
print('* Acc@1 {top1.avg:.3f} '.format(top1=top1))
return top1.avg
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
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) + ']'
class TinyImagenet(Dataset):
"""Tiny Imagenet Pytorch Dataset"""
filename = ('tiny-imagenet-200.zip',
'http://cs231n.stanford.edu/tiny-imagenet-200.zip')
md5 = '90528d7ca1a48142e341f4ef8d21d0de'
def __init__(
self,
root,
*,
train: bool = True,
transform=None,
target_transform=None,
loader=default_loader,
download=True):
"""
Creates an instance of the Tiny Imagenet dataset.
:param root: folder in which to download dataset. Defaults to None,
which means that the default location for 'tinyimagenet' will be
used.
:param train: True for training set, False for test set.
:param transform: Pytorch transformation function for x.
:param target_transform: Pytorch transformation function for y.
:param loader: the procedure to load the instance from the storage.
:param bool download: If True, the dataset will be downloaded if
needed.
"""
self.transform = transform
self.target_transform = target_transform
self.train = train
self.loader = loader
# super(TinyImagenet, self).__init__(
# root, self.filename[1], self.md5, download=download, verbose=True)
self.root = root
# self._load_dataset()
self._load_metadata()
# def _load_dataset(self) -> None:
# """
# The standardized dataset download and load procedure.
# For more details on the coded procedure see the class documentation.
# This method shouldn't be overridden.
# This method will raise and error if the dataset couldn't be loaded
# or downloaded.
# :return: None
# """
# metadata_loaded = False
# metadata_load_error = None
#
# try:
# metadata_loaded = self._load_metadata()
# except Exception as e:
# metadata_load_error = e
#
# if metadata_loaded:
# if self.verbose:
# print('Files already downloaded and verified')
# return
#
# if not self.download:
# msg = 'Error loading dataset metadata (dataset download was ' \
# 'not attempted as "download" is set to False)'
# if metadata_load_error is None:
# raise RuntimeError(msg)
# else:
# print(msg)
# raise metadata_load_error
def _load_metadata(self) -> bool:
self.data_folder = self.root / 'tiny-imagenet-200'
self.label2id, self.id2label = TinyImagenet.labels2dict(
self.data_folder)
self.data, self.targets = self.load_data()
return True
@staticmethod
def labels2dict(data_folder):
"""
Returns dictionaries to convert class names into progressive ids
and viceversa.
:param data_folder: The root path of tiny imagenet
:returns: label2id, id2label: two Python dictionaries.
"""
label2id = {}
id2label = {}
with open(str(data_folder / 'wnids.txt'), 'r') as f:
reader = csv.reader(f)
curr_idx = 0
for ll in reader:
if ll[0] not in label2id:
label2id[ll[0]] = curr_idx
id2label[curr_idx] = ll[0]
curr_idx += 1
return label2id, id2label
def load_data(self):
"""
Load all images paths and targets.
:return: train_set, test_set: (train_X_paths, train_y).
"""
data = [[], []]
classes = list(range(200))
for class_id in classes:
class_name = self.id2label[class_id]
if self.train:
X = self.get_train_images_paths(class_name)
Y = [class_id] * len(X)
else:
# test set
X = self.get_test_images_paths(class_name)
Y = [class_id] * len(X)
data[0] += X
data[1] += Y
return data
def get_train_images_paths(self, class_name):
"""
Gets the training set image paths.
:param class_name: names of the classes of the images to be
collected.
:returns img_paths: list of strings (paths)
"""
train_img_folder = self.data_folder / 'train' / class_name / 'images'
img_paths = [f for f in train_img_folder.iterdir() if f.is_file()]
return img_paths
def get_test_images_paths(self, class_name):
"""
Gets the test set image paths
:param class_name: names of the classes of the images to be
collected.
:returns img_paths: list of strings (paths)
"""
val_img_folder = self.data_folder / 'val' / 'images'
annotations_file = self.data_folder / 'val' / 'val_annotations.txt'
valid_names = []
# filter validation images by class using appropriate file
with open(str(annotations_file), 'r') as f:
reader = csv.reader(f, dialect='excel-tab')
for ll in reader:
if ll[1] == class_name:
valid_names.append(ll[0])
img_paths = [val_img_folder / f for f in valid_names]
return img_paths
def __len__(self):
""" Returns the length of the set """
return len(self.data)
def __getitem__(self, index):
""" Returns the index-th x, y pattern of the set """
path, target = self.data[index], int(self.targets[index])
# doing this so that it is consistent with all other datasets
# to return a PIL Image
img = self.loader(path)
if self.transform is not None:
img = self.transform(img)
if self.target_transform is not None:
target = self.target_transform(target)
return img, target
def get_device(model: nn.Module):
return next(model.parameters()).device
class EarlyStopping:
def __init__(self, tolerance, min=True, **kwargs):
self.initial_tolerance = tolerance
self.tolerance = tolerance
self.min = min
if self.min:
self.current_value = np.inf
self.c = lambda a, b: a < b
else:
self.current_value = -np.inf
self.c = lambda a, b: a > b
def step(self, v):
if self.c(v, self.current_value):
self.tolerance = self.initial_tolerance
self.current_value = v
return 1
else:
self.tolerance -= 1
if self.tolerance <= 0:
return -1
return 0
def reset(self):
self.tolerance = self.initial_tolerance
self.current_value = 0
if self.min:
self.current_value = np.inf
self.c = lambda a, b: a < b
else:
self.current_value = -np.inf
self.c = lambda a, b: a > b
class Cutout(object):
def __init__(self, length):
self.length = length
def __call__(self, img):
h, w = img.size(1), img.size(2)
mask = np.ones((h, w), np.float32)
y = np.random.randint(h)
x = np.random.randint(w)
y1 = np.clip(y - self.length // 2, 0, h)
y2 = np.clip(y + self.length // 2, 0, h)
x1 = np.clip(x - self.length // 2, 0, w)
x2 = np.clip(x + self.length // 2, 0, w)
mask[y1: y2, x1: x2] = 0.
mask = torch.from_numpy(mask)
mask = mask.expand_as(img)
img *= mask
return img
def get_dataset(name, model_name=None, augmentation=False, resolution=32, val_split=0, balanced_val=False, autoaugment=True, cutout=True, cutout_length=16):
if name == 'mnist':
t = [Resize((32, 32)),
ToTensor(),
Normalize((0.1307,), (0.3081,)),
]
if model_name == 'lenet-300-100':
t.append(torch.nn.Flatten())
t = Compose(t)
train_set = datasets.MNIST(
root='~/datasets/mnist/',
train=True,
transform=t,
download=True
)
test_set = datasets.MNIST(
root='~/datasets/mnist/',
train=False,
transform=t,
download=True
)
classes = 10
input_size = (1, 32, 32)
elif name == 'flat_mnist':
t = Compose([ToTensor(),
Normalize(
(0.1307,), (0.3081,)),
torch.nn.Flatten(0)
])
train_set = datasets.MNIST(
root='~/datasets/mnist/',
train=True,
transform=t,
download=True
)
test_set = datasets.MNIST(
root='~/datasets/mnist/',
train=False,
transform=t,
download=True
)
classes = 10
input_size = 28 * 28
elif name == 'svhn':
if augmentation:
tt = [RandomHorizontalFlip(),
RandomCrop(32, padding=4)]
else:
tt = []
tt.extend([ToTensor(),
Normalize((0.4376821, 0.4437697, 0.47280442),
(0.19803012, 0.20101562, 0.19703614))])
t = [
ToTensor(),
Normalize((0.4376821, 0.4437697, 0.47280442),
(0.19803012, 0.20101562, 0.19703614))]
# if 'resnet' in model_name:
# tt = [transforms.Resize(256), transforms.CenterCrop(224)] + tt
# t = [transforms.Resize(256), transforms.CenterCrop(224)] + t
transform = Compose(t)
train_transform = Compose(tt)
train_set = datasets.SVHN(
root='~/datasets/svhn', split='train', download=True,
transform=train_transform)
test_set = datasets.SVHN(
root='~/datasets/svhn', split='test', download=True,
transform=transform)
input_size, classes = (3, 32, 32), 10
elif name == 'cifar10':
norm_mean = [0.49139968, 0.48215827, 0.44653124]
norm_std = [0.24703233, 0.24348505, 0.26158768]
if resolution==32:
# data processing used in NACHOS
#tt = [Resize((resolution, resolution))]
if augmentation:
tt=[RandomHorizontalFlip(),
RandomCrop(resolution, padding=resolution//8)]
else:
tt = [RandomResizedCrop(resolution, scale=(0.08,1.0)),
RandomHorizontalFlip()] #p=0.5 default]
tt.extend([ ToTensor(),
Normalize(norm_mean, norm_std)
])
'''
tt = [RandomResizedCrop(resolution, scale=(0.08,1.0)),
#RandomCrop(32, padding=4),
RandomHorizontalFlip(), #p=0.5 default
#ToTensor(),
#Normalize(norm_mean, norm_std)
]
if autoaugment:
tt.extend([CIFAR10Policy()])
tt.extend([ToTensor()])
if cutout:
tt.extend([Cutout(cutout_length)])
tt.extend([Normalize(norm_mean, norm_std)])
'''
t = [
Resize((resolution, resolution)),
ToTensor(),
Normalize(norm_mean, norm_std)]
transform = Compose(t)
train_transform = Compose(tt)
train_set = datasets.CIFAR10(
root='~/datasets/cifar10', train=True, download=True,
transform=train_transform)
test_set = datasets.CIFAR10(
root='~/datasets/cifar10', train=False, download=True,
transform=transform)
input_size, classes = (3, resolution, resolution), 10
val_split=0.2
elif name == 'cifar100':
tt = [Resize((resolution, resolution))]
if augmentation:
tt.extend([
RandomCrop(resolution, padding=resolution//8),
RandomHorizontalFlip(),
])
tt.extend([
ToTensor(),
Normalize((0.4914, 0.4822, 0.4465),
(0.2023, 0.1994, 0.2010))])
t = [
Resize((resolution, resolution)),
ToTensor(),
Normalize((0.4914, 0.4822, 0.4465),
(0.2023, 0.1994, 0.2010))]
transform = Compose(t)
train_transform = Compose(tt)
train_set = datasets.CIFAR100(
root='~/datasets/cifar100', train=True, download=True,
transform=train_transform)
test_set = datasets.CIFAR100(
root='~/datasets/cifar100', train=False, download=True,
transform=transform)
input_size, classes = (3, resolution, resolution), 100
val_split=0.2
elif name == 'cinic10':
tt = [Resize((resolution, resolution))]
if augmentation:
tt.extend([RandomHorizontalFlip(),
RandomCrop(resolution, padding=resolution//8)])
tt.extend([ToTensor(),
Normalize([0.47889522, 0.47227842, 0.43047404],
[0.24205776, 0.23828046, 0.25874835])])
t = [
Resize((resolution, resolution)),
ToTensor(),
Normalize([0.47889522, 0.47227842, 0.43047404],
[0.24205776, 0.23828046, 0.25874835])]
transform = Compose(t)
train_transform = Compose(tt)
train_set = datasets.ImageFolder('~/datasets/cinic10/train',
transform=train_transform)
test_set = datasets.ImageFolder('~/datasets/cinic10/test',
transform=transform)
input_size, classes = (3, resolution, resolution), 10
elif name == 'tinyimagenet':
tt = [Resize((resolution, resolution))]
if augmentation:
tt.extend([
RandomRotation(20),
RandomHorizontalFlip(0.5),
ToTensor(),
Normalize((0.4802, 0.4481, 0.3975),
(0.2302, 0.2265, 0.2262)),
])
else:
tt.extend([
Normalize((0.4802, 0.4481, 0.3975),
(0.2302, 0.2265, 0.2262)),
ToTensor()])
t = [
Resize((resolution, resolution)),
ToTensor(),
Normalize((0.4802, 0.4481, 0.3975),
(0.2302, 0.2265, 0.2262))
]
transform = Compose(t)
train_transform = Compose(tt)
train_set = datasets.ImageFolder('../datasets/tiny-imagenet-200/train',
transform=train_transform)
test_set = datasets.ImageFolder('../datasets/tiny-imagenet-200/val',
transform=transform)
input_size, classes = (3, resolution, resolution), 200
elif name == 'ImageNet16':
IMAGENET16_MEAN = [x / 255 for x in [122.68, 116.66, 104.01]]
IMAGENET16_STD = [x / 255 for x in [63.22, 61.26, 65.09]]
train_transform = Compose([
RandomHorizontalFlip(),
RandomResizedCrop(resolution), #RandomCrop(resolution, padding=2),
ToTensor(),
Normalize(IMAGENET16_MEAN, IMAGENET16_STD),
])
valid_transform = Compose([
Resize(resolution),
ToTensor(),
Normalize(IMAGENET16_MEAN, IMAGENET16_STD),
])
classes=120
train_set = ImageNet16(root='../datasets/ImageNet16', train=True, transform=train_transform, use_num_of_class_only=classes)
test_set = ImageNet16(root='../datasets/ImageNet16', train=False, transform=valid_transform, use_num_of_class_only=classes)
input_size, classes = (3, resolution, resolution), classes
elif name == 'imagenette':
IMAGENET_MEAN = [0.485, 0.456, 0.406]
IMAGENET_STD = [0.229, 0.224, 0.225]
train_transform = Compose([
RandomResizedCrop(resolution, scale=(0.08,1.0)),
RandomHorizontalFlip(),
ToTensor(),
Normalize(IMAGENET_MEAN, IMAGENET_STD),
])
valid_transform = Compose([
Resize(resolution),
CenterCrop((resolution, resolution)),
ToTensor(),
Normalize(IMAGENET_MEAN, IMAGENET_STD),
])
train_set = datasets.Imagenette('../datasets/imagenette/train', split='train', size='160px', download=False, transform=train_transform)
test_set = datasets.Imagenette('../datasets/imagenette/val', split='val', size='160px', download=False, transform=valid_transform)
input_size, classes = (3, resolution, resolution), 10
else:
assert False
val_set = None
# Split the dataset into training and validation sets
if val_split:
train_len = len(train_set)
eval_len = int(train_len * val_split)
train_len = train_len - eval_len
#print("VAL SPLIT: ", val_split)
#val_split=0.5
if balanced_val:
train_set, val_set = random_split_with_equal_per_class(train_set, val_split)
else:
train_set, val_set = torch.utils.data.random_split(train_set,
[train_len,
eval_len])
val_set.dataset = copy.deepcopy(val_set.dataset)
val_set.dataset.transform = test_set.transform
if hasattr(val_set.dataset, 'target_transform'):
val_set.dataset.target_transform = test_set.target_transform
return train_set, val_set, test_set, input_size, classes
def random_split_with_equal_per_class(train_set, val_split):
"""
Randomly shuffle and split a dataset into training and validation sets with an equal number of samples per class in the validation set.
Args:
train_set (Dataset): The dataset to split.
val_split (float): The fraction of the dataset to include in the validation set.
Returns:
train_set (Subset): The training subset of the dataset.
val_set (Subset): The validation subset of the dataset.
"""
# Shuffle the train set
train_size = len(train_set)
shuffled_indices = torch.randperm(train_size).tolist()
train_set = Subset(train_set, shuffled_indices)
# Determine the number of samples per class for the validation set
class_counts = defaultdict(int)
for _, target in train_set:
class_counts[target] += 1
samples_per_class = {cls: int(val_split * count) for cls, count in class_counts.items()}
print("SAMPLES PER CLASS: ", samples_per_class)
# Initialize lists to hold indices for the validation set
val_indices = []