이동주

calculate each data's variance, kl divergence

1 +# run train.py --dataset cifar10 --model resnet18 --data_augmentation --cutout --length 16
2 +# run train.py --dataset cifar100 --model resnet18 --data_augmentation --cutout --length 8
3 +# run train.py --dataset svhn --model wideresnet --learning_rate 0.01 --epochs 160 --cutout --length 20
4 +
5 +import pdb
6 +import argparse
7 +import numpy as np
8 +from tqdm import tqdm
9 +
10 +import torch
11 +import torch.nn as nn
12 +from torch.autograd import Variable
13 +import torch.backends.cudnn as cudnn
14 +from torch.optim.lr_scheduler import MultiStepLR
15 +
16 +from torchvision.utils import make_grid
17 +from torchvision import datasets, transforms
18 +
19 +from torch.utils.data.dataloader import RandomSampler
20 +from util.misc import CSVLogger
21 +from util.cutout import Cutout
22 +
23 +from model.resnet import ResNet18
24 +from model.wide_resnet import WideResNet
25 +
26 +model_options = ['resnet18', 'wideresnet']
27 +dataset_options = ['cifar10', 'cifar100', 'svhn']
28 +
29 +parser = argparse.ArgumentParser(description='CNN')
30 +parser.add_argument('--dataset', '-d', default='cifar10',
31 + choices=dataset_options)
32 +parser.add_argument('--model', '-a', default='resnet18',
33 + choices=model_options)
34 +parser.add_argument('--batch_size', type=int, default=128,
35 + help='input batch size for training (default: 128)')
36 +parser.add_argument('--epochs', type=int, default=200,
37 + help='number of epochs to train (default: 20)')
38 +parser.add_argument('--learning_rate', type=float, default=0.1,
39 + help='learning rate')
40 +parser.add_argument('--data_augmentation', action='store_true', default=False,
41 + help='augment data by flipping and cropping')
42 +parser.add_argument('--cutout', action='store_true', default=False,
43 + help='apply cutout')
44 +parser.add_argument('--n_holes', type=int, default=1,
45 + help='number of holes to cut out from image')
46 +parser.add_argument('--length', type=int, default=16,
47 + help='length of the holes')
48 +parser.add_argument('--no-cuda', action='store_true', default=False,
49 + help='enables CUDA training')
50 +parser.add_argument('--seed', type=int, default=0,
51 + help='random seed (default: 1)')
52 +
53 +args = parser.parse_args()
54 +args.cuda = not args.no_cuda and torch.cuda.is_available()
55 +cudnn.benchmark = True # Should make training should go faster for large models
56 +
57 +torch.manual_seed(args.seed)
58 +if args.cuda:
59 + torch.cuda.manual_seed(args.seed)
60 +
61 +test_id = args.dataset + '_' + args.model
62 +
63 +print(args)
64 +
65 +# Image Preprocessing
66 +if args.dataset == 'svhn':
67 + normalize = transforms.Normalize(mean=[x / 255.0 for x in[109.9, 109.7, 113.8]],
68 + std=[x / 255.0 for x in [50.1, 50.6, 50.8]])
69 +else:
70 + normalize = transforms.Normalize(mean=[x / 255.0 for x in [125.3, 123.0, 113.9]],
71 + std=[x / 255.0 for x in [63.0, 62.1, 66.7]])
72 +
73 +train_transform = transforms.Compose([])
74 +if args.data_augmentation:
75 + train_transform.transforms.append(transforms.RandomCrop(32, padding=4))
76 + train_transform.transforms.append(transforms.RandomHorizontalFlip())
77 +train_transform.transforms.append(transforms.ToTensor())
78 +train_transform.transforms.append(normalize)
79 +if args.cutout:
80 + train_transform.transforms.append(Cutout(n_holes=args.n_holes, length=args.length))
81 +
82 +
83 +test_transform = transforms.Compose([
84 + transforms.ToTensor(),
85 + normalize])
86 +
87 +if args.dataset == 'cifar10':
88 + num_classes = 10
89 + train_dataset = datasets.CIFAR10(root='data/',
90 + train=True,
91 + transform=train_transform,
92 + download=True)
93 +
94 + test_dataset = datasets.CIFAR10(root='data/',
95 + train=False,
96 + transform=test_transform,
97 + download=True)
98 +elif args.dataset == 'cifar100':
99 + num_classes = 100
100 + train_dataset = datasets.CIFAR100(root='data/',
101 + train=True,
102 + transform=train_transform,
103 + download=True)
104 +
105 + test_dataset = datasets.CIFAR100(root='data/',
106 + train=False,
107 + transform=test_transform,
108 + download=True)
109 +elif args.dataset == 'svhn':
110 + num_classes = 10
111 + train_dataset = datasets.SVHN(root='data/',
112 + split='train',
113 + transform=train_transform,
114 + download=True)
115 +
116 + extra_dataset = datasets.SVHN(root='data/',
117 + split='extra',
118 + transform=train_transform,
119 + download=True)
120 +
121 + # Combine both training splits (https://arxiv.org/pdf/1605.07146.pdf)
122 + data = np.concatenate([train_dataset.data, extra_dataset.data], axis=0)
123 + labels = np.concatenate([train_dataset.labels, extra_dataset.labels], axis=0)
124 + train_dataset.data = data
125 + train_dataset.labels = labels
126 +
127 + test_dataset = datasets.SVHN(root='data/',
128 + split='test',
129 + transform=test_transform,
130 + download=True)
131 +
132 +# Data Loader (Input Pipeline)
133 +train_loader = torch.utils.data.DataLoader(dataset=train_dataset,
134 + batch_size=args.batch_size,
135 + shuffle=False,
136 + # sampler=RandomSampler(train_dataset, True, 40000),
137 + pin_memory=True,
138 + num_workers=0)
139 +
140 +test_loader = torch.utils.data.DataLoader(dataset=test_dataset,
141 + batch_size=args.batch_size,
142 + shuffle=False,
143 + pin_memory=True,
144 + num_workers=0)
145 +
146 +if args.model == 'resnet18':
147 + cnn = ResNet18(num_classes=num_classes)
148 +elif args.model == 'wideresnet':
149 + if args.dataset == 'svhn':
150 + cnn = WideResNet(depth=16, num_classes=num_classes, widen_factor=8,
151 + dropRate=0.4)
152 + else:
153 + cnn = WideResNet(depth=28, num_classes=num_classes, widen_factor=10,
154 + dropRate=0.3)
155 +checkpoint = torch.load('/content/drive/MyDrive/capstone/Cutout/checkpoints/baseline_cifar10_resnet18.pt', map_location = torch.device('cuda:0'))
156 +cnn = cnn.cuda()
157 +cnn.load_state_dict(checkpoint)
158 +criterion = nn.CrossEntropyLoss().cuda()
159 +cnn_optimizer = torch.optim.SGD(cnn.parameters(), lr=args.learning_rate,
160 + momentum=0.9, nesterov=True, weight_decay=5e-4)
161 +
162 +if args.dataset == 'svhn':
163 + scheduler = MultiStepLR(cnn_optimizer, milestones=[80, 120], gamma=0.1)
164 +else:
165 + scheduler = MultiStepLR(cnn_optimizer, milestones=[60, 120, 160], gamma=0.2)
166 +
167 +filename = 'logs/' + test_id + '.csv'
168 +csv_logger = CSVLogger(args=args, fieldnames=['epoch', 'train_acc', 'test_acc'], filename=filename)
169 +
170 +
171 +def test(loader):
172 + cnn.eval() # Change model to 'eval' mode (BN uses moving mean/var).
173 + correct = 0.
174 + total = 0.
175 + for images, labels in loader:
176 + images = images.cuda()
177 + labels = labels.cuda()
178 +
179 + with torch.no_grad():
180 + pred = cnn(images)
181 +
182 + pred = torch.max(pred.data, 1)[1]
183 +
184 + total += labels.size(0)
185 + correct += (pred == labels).sum().item()
186 +
187 + val_acc = correct / total
188 + cnn.train()
189 + return val_acc
190 +
191 +kl_sum = 0
192 +y_bar = torch.Tensor([0] * 10).detach().cuda()
193 +
194 +# y_bar 구하는 epoch
195 +for epoch in range(args.epochs):
196 +
197 + cnn.eval()
198 + xentropy_loss_avg = 0.
199 + correct = 0.
200 + total = 0.
201 + norm_const = 0
202 +
203 + kldiv = 0
204 + # pred_sum = torch.Tensor([0] * 10).detach().cuda()
205 +
206 + progress_bar = tqdm(train_loader)
207 + for i, (images, labels) in enumerate(progress_bar):
208 + progress_bar.set_description('Epoch ' + str(epoch))
209 +
210 + images = images.cuda()
211 + labels = labels.cuda()
212 +
213 + cnn.zero_grad()
214 + pred = cnn(images)
215 + xentropy_loss = criterion(pred, labels)
216 + # xentropy_loss.backward()
217 + # cnn_optimizer.step()
218 +
219 + xentropy_loss_avg += xentropy_loss.item()
220 +
221 + pred_softmax = nn.functional.softmax(pred).cuda()
222 + # Calculate running average of accuracy
223 + pred = torch.max(pred.data, 1)[1]
224 + total += labels.size(0)
225 + correct += (pred == labels.data).sum().item()
226 + accuracy = correct / total
227 + for a in range(pred_softmax.data.size()[0]):
228 + for b in range(y_bar.size()[0]):
229 + y_bar[b] += torch.log(pred_softmax.data[a][b])
230 +
231 +
232 + # expectation(log y_hat)
233 + # y_bar = [x / pred.data.size()[0] for x in y_bar]
234 +
235 + # print(pred.data.size()[0], y_bar.size()[0]) # 128, 10
236 +
237 +
238 + # print(pred)
239 + # y_hat : 모델별 예측값 --> pred_softmax
240 + # y_bar : 예측값들 평균값 -- > pred / total : pred_sum
241 + # labes.data : ground_truth
242 +
243 + # y_bar = pred_sum / (i+1)
244 + # kl = torch.nn.functional.kl_div(pred, y_bar)
245 + # kl_sum += kl
246 +
247 +
248 +
249 + # for문 추가안하면 epoch별 iter마다 xentropy_loss_avg값의 1/iter이 xentropy값으로 출력
250 + # for문 추가하면 epoch 별 iter 마다 xentropy_loss_avg 값은 동일하나 xentropy값 출력이 x_l_avg 값의 1/10으로 출력
251 + # for문 상관 없이 pred, labels 값은 동일하게 확인됨.
252 +
253 + # for a in range(list(pred_sum.size())[0]):
254 + # for b in range(list(pred.size())[0]):
255 + # if pred[b] == a:
256 + # pred_sum[a] += 1
257 +
258 + # variance calculate : E[KL_div(y_bar, y_hat)] -> expectation of KLDivLoss(pred_sum, pred)
259 + # 한 epoch마다 계산해서 출력해야 할듯
260 + # nn.functional.kl_div(pred_sum, pred)
261 +
262 +
263 + # print('\n',i, ' ', xentropy_loss_avg)
264 + progress_bar.set_postfix(
265 + # y_hat = '%.5f' % pred,
266 + # y_bar = '%.5f' % y_bar,
267 + # groun_truth = '%.5f' % labels.data,
268 + # kl = '%.3f' % kl.item(),
269 + # kl_sum = '%.3f' % (kl_sum.item()),
270 + # kl_div = '%.3f' % (kl_sum.item() / (i + 1)), # kl_div 호출
271 + xentropy='%.3f' % (xentropy_loss_avg / (i + 1)),
272 + acc='%.3f' % accuracy)
273 + # pred_sum = [x / 40000 for x in pred_sum]
274 + y_bar = torch.Tensor([x / 50000 for x in y_bar]).cuda()
275 + y_bar = torch.exp(y_bar)
276 + # print(y_bar)
277 + for index in range(y_bar.size()[0]):
278 + norm_const += y_bar[index]
279 + print(y_bar)
280 + print(norm_const)
281 + # print(norm_const)
282 + for index in range(y_bar.size()[0]):
283 + y_bar[index] = y_bar[index] / norm_const
284 + print(y_bar)
285 + # print(y_bar)
286 + # print(pred_softmax)
287 + # print(y_bar)
288 + # kldiv = torch.nn.functional.kl_div(y_bar, pred_softmax, reduction='batchmean')
289 + # kl_sum += kldiv
290 + # print(kldiv, kl_sum)
291 + y_bar_copy = y_bar.clone().detach()
292 + test_acc = test(test_loader)
293 + # print(pred, labels.data)
294 + tqdm.write('test_acc: %.3f' % (test_acc))
295 +
296 + scheduler.step(epoch) # Use this line for PyTorch <1.4
297 + # scheduler.step() # Use this line for PyTorch >=1.4
298 +
299 + row = {'epoch': str(epoch), 'train_acc': str(accuracy), 'test_acc': str(test_acc)
300 + }
301 + csv_logger.writerow(row)
302 + del pred
303 + torch.cuda.empty_cache()
304 +
305 +# kl_div 구하는 epoch
306 +for epoch in range(args.epochs):
307 + cnn.eval()
308 + kldiv = 0
309 + for i, (images, labels) in enumerate(progress_bar):
310 + progress_bar.set_description('Epoch ' + str(epoch) + ': Calculate kl_div')
311 +
312 + images = images.cuda()
313 + labels = labels.cuda()
314 +
315 + cnn.zero_grad()
316 + pred = cnn(images)
317 +
318 + pred_softmax = nn.functional.softmax(pred).cuda()
319 +
320 + # 입력 두 개의 shape이 다르면 batchsize로 평균을 내서 반환.
321 + kldiv = torch.nn.functional.kl_div(y_bar_copy, pred_softmax, reduction='sum')
322 + kl_sum += kldiv.detach()
323 + # print(y_bar_copy.size(), pred_softmax.size())
324 + # print(kl_sum)
325 + print("Average KL_div : ", abs(kl_sum / 50000))
326 + # y_bar = torch.Tensor([x / 40000 for x in y_bar]).cuda()
327 + # y_bar = torch.exp(y_bar)
328 + # # print(y_bar)
329 + # for index in range(y_bar.size()[0]):
330 + # norm_const += y_bar[index]
331 + # # print(norm_const)
332 + # for index in range(y_bar.size()[0]):
333 + # y_bar[index] = y_bar[index] / norm_const
334 + # # print(y_bar)
335 + # # print(pred_softmax)
336 + # # print(y_bar)
337 + # kldiv = torch.nn.functional.kl_div(y_bar, pred_softmax, reduction='batchmean')
338 + # kl_sum += kldiv
339 + # print(kldiv, kl_sum)
340 +
341 +torch.save(cnn.state_dict(), 'checkpoints/' + test_id + '.pt')
342 +csv_logger.close()