-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
202 lines (174 loc) · 7.71 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
197
198
199
200
201
202
import os
import logging
import torch
from torch import nn
from torch import optim
from torch.utils.data import DataLoader
from torchvision import transforms as ttf
from torchvision import datasets, models
from termcolor import colored
from torch_randaug import RandAugment
from ctaug import CTAugment
from wideresnet import WideResNet
def get_logger(args):
# create logger
logger = logging.getLogger()
# set logger level
if args.cfg.param.logger_level == "info":
logger.setLevel(logging.INFO)
elif args.cfg.param.logger_level == "debug":
logger.setLevel(logging.DEBUG)
else:
raise Exception("Not supported logger level")
# set formatting
stream_handler = logging.StreamHandler()
formatter = logging.Formatter(colored('[%(filename)s %(lineno)d]', 'green') + \
colored('%(levelname)s', 'blue') + colored(': %(message)s', 'yellow'))
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)
return logger
def get_transforms(args):
# strong transforms
strong_transforms = []
strong_transforms.append(ttf.Resize((args.cfg.transform.input_size, args.cfg.transform.input_size)))
if args.cfg.transform.strong.RA: # Random augment + Cutout for the stong augmentation
strong_transforms.append(RandAugment(args.cfg.transform.strong.RA_num, args.cfg.transform.strong.RA_mag))
strong_transforms.append(ttf.ToTensor())
strong_transforms.append(ttf.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)))
strong_transforms.append(Cutout())
elif args.cfg.transform.strong.CTA: # CTAugment including Cutout for the strong augmentation
# Note: Official Tensorflow implementation seems not to normalize
strong_transforms.append(ttf.PILToTensor())
strong_transforms.append(CTAugment(img_size=(args.cfg.transform.input_size, args.cfg.transform.input_size)))
strong_transforms.append(Div255())
strong_transforms.append(ttf.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)))
strong_transforms.append(Cutout())
# weak transforms
weak_transforms = []
weak_transforms.append(ttf.Resize((args.cfg.transform.input_size, args.cfg.transform.input_size)))
weak_tf_names = args.cfg.transform.weak.augs.split(",")
for name in weak_tf_names:
if name == "RandomHorizontalFlip":
weak_transforms.append(eval("ttf." + name + "(" + str(args.cfg.transform.weak.params.hflip_p) + ")"))
elif name == "RandomAffine":
weak_transforms.append(eval("ttf." + name + \
"(0, translate=(" + str(args.cfg.transform.weak.params.trans_x) + "," + \
str(args.cfg.transform.weak.params.trans_y) + "))"))
weak_transforms.append(ttf.ToTensor())
weak_transforms.append(ttf.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)))
# test transforms
test_transforms = [ttf.Resize((args.cfg.transform.input_size, args.cfg.transform.input_size)), ttf.ToTensor(), ttf.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]
return ttf.Compose(strong_transforms), ttf.Compose(weak_transforms), ttf.Compose(test_transforms)
def get_dataset(args):
if args.cfg.data.name == "stl10":
train_labeled = datasets.STL10(args.cfg.data.root, "train", transform=args.weak_transforms, download=True)
train_unlabeled = datasets.STL10(args.cfg.data.root, "unlabeled", transform=None, download=True)
testset = datasets.STL10(args.cfg.data.root, "test", transform=args.test_transforms, download=True)
else:
raise Exception("Not supported dataset")
return train_labeled, train_unlabeled, testset
def collate_unlabeled(batch):
images, labels = zip(*batch)
return images, labels
def get_loaders(args):
trainloader = DataLoader(args.train_labeled, args.cfg.train.batch_size, shuffle=True, num_workers=args.cfg.train.num_workers)
trainloader_u = DataLoader(
args.train_unlabeled,
args.cfg.train.batch_size * args.cfg.train.mu,
shuffle=True,
num_workers=args.cfg.train.num_workers,
collate_fn=collate_unlabeled)
testloader = DataLoader(args.testset, args.cfg.train.batch_size, shuffle=False, num_workers=args.cfg.train.num_workers)
return trainloader, trainloader_u, testloader
def get_model(args):
if "wideresnet" in args.cfg.model.name:
_, depth, width = args.cfg.model.name.split("-")
depth, width = int(depth), int(width)
model = WideResNet(depth, args.cfg.data.num_classes, width)
else:
raise Exception("Not supported model architecture")
return model
def get_optim(args):
# optimizer
if args.cfg.train.optim.optimizer == "SGD":
optimizer = optim.SGD(
args.model.parameters(),
lr=args.cfg.train.optim.lr,
momentum=args.cfg.train.optim.momentum,
weight_decay=args.cfg.train.optim.weight_decay,
nesterov=args.cfg.train.optim.nesterov)
else:
raise Exception("Not spported optimizer")
# scheduler
if args.cfg.train.optim.scheduler == "CosineAnnealingLR":
scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, args.cfg.train.optim.t_max)
else:
raise Exception("Not spported scheduler")
return optimizer, scheduler
def get_criterion(args):
if args.cfg.train.criterion == "ce":
criterion = nn.BCELoss()
else:
raise Exception("Not spported criterion")
return criterion
def save_model(args):
save_dict = {
"state_dict": args.model.module.state_dict() if isinstance(args.model, nn.DataParallel) else args.model.state_dict(),
"optimizer": args.optimizer.state_dict(),
"scheduler": args.scheduler.state_dict(),
"epoch": args.current_epoch,
"best_val_acc": args.best_val_acc,
"best_val_loss": args.best_val_loss
}
torch.save(save_dict, os.path.join(args.cfg.param.checkpoint_dir, args.cfg.param.log_name, args.cfg.param.checkpoint_name))
def load_model(args):
cp = torch.load(os.path.join(args.cfg.param.checkpoint_dir, args.cfg.param.log_name, args.cfg.param.checkpoint_name))
args.model.load_state_dict(cp["state_dict"])
if "optimizer" in cp:
args.optimizer.load_state_dict(cp["optimizer"])
if "scheduler" in cp:
args.scheduler.load_state_dict(cp["scheduler"])
if ("epoch" in cp) and ("best_val_acc" in cp) and ("best_val_loss" in cp):
params = [cp["epoch"] + 1, cp["best_val_acc"], cp["best_val_loss"]]
else:
params = None
return args, params
class Cutout(torch.nn.Module):
"""
Sets a random square patch of side-length (L×image width) pixels to gray.
"""
def __init__(self, L=0.5):
super().__init__()
self.L = L
self.sampler = torch.distributions.uniform.Uniform(0.0, L)
def forward(self, img):
"""
Args:
Tensor: Tensor of size (C, H, W).
"""
c, h, w = img.size()
# patch size and location
patch_size = round(float(w * self.sampler.sample()))
x = torch.randint(low=0, high=w - patch_size, size=(1,))
y = torch.randint(low=0, high=h - patch_size, size=(1,))
# gray value
if img.dtype == torch.float32:
if img.min() >= 0: # 0 ~ 1
value = 0.5
else: # -1 ~ 1
value = 0.0
elif img.dtype == torch.uint8: # 0 ~ 255
value = 127
else:
raise Exception("Not supported tensor dtype.")
# cutout
img[:, y:y+patch_size, x:x+patch_size] = value
return img
class Div255(nn.Module):
def __init__(self):
super().__init__()
def forward(self, tensor):
if (tensor.max() > 1) or (tensor.dtype == torch.uint8):
return (tensor / 255.).to(torch.float32)
else:
return tensor