-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathtrain_pure.py
466 lines (377 loc) · 16.3 KB
/
train_pure.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
from __future__ import print_function
import argparse
import numpy as np
import os
import csv
import math
from PIL import Image
from cvxpy import *
from fancyimpute import SoftImpute, BiScaler
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
import torch.utils.data as Data
import models
from utils import progress_bar
# Checkpoint related
START_EPOCH = 0
# Device configuration
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def nuclear_norm_solve(A, mask, mu):
"""Nuclear norm minimization solver.
:param A: matrix to complete
:param mask: matrix with entries zero (if missing) or one (if present)
:param mu: control trade-off between nuclear norm and square loss
:return: completed matrix
"""
X = Variable(shape=A.shape)
objective = Minimize(mu * norm(X, "nuc") + sum_squares(multiply(mask, X-A)))
problem = Problem(objective, [])
problem.solve(solver=SCS)
return X.value
def nucnorm(img, maskp):
"""Preprocessing with nuclear norm algorithm.
Data matrix is scaled between [-1, 1] before matrix estimation (and rescaled back after ME)
[Candès, J. and Recht, B. Exact matrix completion via convex optimization. 2009.]
:param img: original image
:param maskp: observation probability of each entry in mask matrix
:return: preprocessed image
"""
h, w, c = img.shape
img = img.astype('float64') * 2 / 255 - 1
if args.me_channel == 'concat':
img = img.transpose(2, 0, 1)
img = np.concatenate((np.concatenate((img[0], img[1]), axis=1), img[2]), axis=1)
mask = np.random.binomial(1, maskp, h * w * c).reshape(h, w * c)
W = nuclear_norm_solve(img, mask, mu=args.mu)
W[W < -1] = -1
W[W > 1] = 1
est_matrix = (W + 1) * 255 / 2
outputs = np.zeros((h, w, c))
for channel in range(c):
outputs[:, :, channel] = est_matrix[:, channel * w:(channel + 1) * w]
else:
mask = np.random.binomial(1, maskp, h * w).reshape(h, w)
outputs = np.zeros((h, w, c))
for channel in range(c):
W = nuclear_norm_solve(img[:, :, channel], mask, mu=args.mu)
W[W < -1] = -1
W[W > 1] = 1
outputs[:, :, channel] = (W + 1) * 255 / 2
return outputs
def usvt(img, maskp):
"""Preprocessing with universal singular value thresholding (USVT) approach.
Data matrix is scaled between [-1, 1] before matrix estimation (and rescaled back after ME)
[Chatterjee, S. et al. Matrix estimation by universal singular value thresholding. 2015.]
:param img: original image
:param maskp: observation probability of each entry in mask matrix
:return: preprocessed image
"""
h, w, c = img.shape
img = img.astype('float64') * 2 / 255 - 1
if args.me_channel == 'concat':
img = img.transpose(2, 0, 1)
img = np.concatenate((np.concatenate((img[0], img[1]), axis=1), img[2]), axis=1)
mask = np.random.binomial(1, maskp, h * w * c).reshape(h, w * c)
p_obs = len(mask[mask == 1]) / (h * w * c)
u, sigma, v = np.linalg.svd(img * mask)
S = np.zeros((h, h))
for j in range(int(args.svdprob * h)):
S[j][j] = sigma[j]
S = np.concatenate((S, np.zeros((h, w*(c-1)))), axis=1)
W = np.dot(np.dot(u, S), v) / p_obs
W[W < -1] = -1
W[W > 1] = 1
est_matrix = (W + 1) * 255 / 2
outputs = np.zeros((h, w, c))
for channel in range(c):
outputs[:, :, channel] = est_matrix[:, channel * w:(channel + 1) * w]
else:
mask = np.random.binomial(1, maskp, h * w).reshape(h, w)
p_obs = len(mask[mask == 1]) / (h * w)
outputs = np.zeros((h, w, c))
for channel in range(c):
u, sigma, v = np.linalg.svd(img[:, :, channel] * mask)
S = np.zeros((h, h))
sigma = np.concatenate((sigma, np.zeros(h - len(sigma))), axis=0)
for j in range(int(args.svdprob * h)):
S[j][j] = sigma[j]
W = np.dot(np.dot(u, S), v) / p_obs
W[W < -1] = -1
W[W > 1] = 1
outputs[:, :, channel] = (W + 1) * 255 / 2
return outputs
def softimp(img, maskp):
"""Preprocessing with Soft-Impute approach.
Data matrix is scaled between [-1, 1] before matrix estimation (and rescaled back after ME)
[Mazumder, R. et al. Spectral regularization algorithms for learning large incomplete matrices. 2010.]
:param img: original image
:param maskp: observation probability of each entry in mask matrix
:return: preprocessed image
"""
h, w, c = img.shape
img = img.astype('float64') * 2 / 255 - 1
if args.me_channel == 'concat':
img = img.transpose(2, 0, 1)
img = np.concatenate((np.concatenate((img[0], img[1]), axis=1), img[2]), axis=1)
mask = np.random.binomial(1, maskp, h * w * c).reshape(h, w * c).astype(float)
mask[mask < 1] = np.nan
W = SoftImpute(verbose=False).fit_transform(mask * img)
W[W < -1] = -1
W[W > 1] = 1
est_matrix = (W + 1) * 255 / 2
outputs = np.zeros((h, w, c))
for channel in range(c):
outputs[:, :, channel] = est_matrix[:, channel * w:(channel + 1) * w]
else:
mask = np.random.binomial(1, maskp, h * w).reshape(h, w).astype(float)
mask[mask < 1] = np.nan
outputs = np.zeros((h, w, c))
for channel in range(c):
mask_img = img[:, :, channel] * mask
W = SoftImpute(verbose=False).fit_transform(mask_img)
W[W < -1] = -1
W[W > 1] = 1
outputs[:, :, channel] = (W + 1) * 255 / 2
return outputs
def unpickle(file):
import pickle
with open(file, 'rb') as fo:
dict = pickle.load(fo, encoding='bytes')
return dict
def get_data(train=False):
data = None
labels = None
if train:
for i in range(1, 6):
batch = unpickle(args.data_dir + 'cifar-10-batches-py/data_batch_' + str(i))
if i == 1:
data = batch[b'data']
else:
data = np.concatenate([data, batch[b'data']])
if i == 1:
labels = batch[b'labels']
else:
labels = np.concatenate([labels, batch[b'labels']])
data_tmp = data
labels_tmp = labels
# repeat n times for different masks
for i in range(args.mask_num - 1):
data = np.concatenate([data, data_tmp])
labels = np.concatenate([labels, labels_tmp])
else:
batch = unpickle(args.data_dir + 'cifar-10-batches-py/test_batch')
data = batch[b'data']
labels = batch[b'labels']
return data, labels
def target_transform(label):
label = np.array(label)
target = torch.from_numpy(label).long()
return target
# ME-Net pre-processing
def menet(train_data, train=True):
if train:
for i in range(train_data.shape[0]):
maskp = args.startp + math.ceil((i + 1) / 50000) * (args.endp - args.startp) / args.mask_num
train_data[i] = globals()[args.me_type](train_data[i], maskp)
# Bar visualization
progress_bar(i, train_data.shape[0], ' | Training data')
else:
for i in range(train_data.shape[0]):
maskp = (args.startp + args.endp) / 2
train_data[i] = globals()[args.me_type](train_data[i], maskp)
# Bar visualization
progress_bar(i, train_data.shape[0], ' | Testing data')
return train_data
class CIFAR10_Dataset(Data.Dataset):
def __init__(self, train=True, target_transform=None):
self.target_transform = target_transform
self.train = train
if self.train:
self.train_data, self.train_labels = get_data(train)
self.train_data = self.train_data.reshape((self.train_data.shape[0], 3, 32, 32))
self.train_data = self.train_data.transpose((0, 2, 3, 1))
self.train_data = menet(self.train_data, train=True)
else:
self.test_data, self.test_labels = get_data()
self.test_data = self.test_data.reshape((self.test_data.shape[0], 3, 32, 32))
self.test_data = self.test_data.transpose((0, 2, 3, 1))
self.test_data = menet(self.test_data, train=False)
def __getitem__(self, index):
if self.train:
img, label = self.train_data[index], self.train_labels[index]
else:
img, label = self.test_data[index], self.test_labels[index]
img = Image.fromarray(img)
if self.train:
img = transform_train(img)
else:
img = transform_test(img)
if self.target_transform is not None:
target = self.target_transform(label)
return img, target
def __len__(self):
if self.train:
return len(self.train_data)
else:
return len(self.test_data)
def train(epoch):
print('\nEpoch: %d' % epoch)
model.train()
train_loss = 0
correct = 0
total = 0
for batch_idx, (inputs, targets) in enumerate(train_loader):
inputs, targets = inputs.to(device), targets.to(device)
# Forward pass
outputs = model(inputs)
loss = criterion(outputs, targets)
train_loss += loss.item()
_, pred_idx = torch.max(outputs.data, 1)
total += targets.size(0)
correct += pred_idx.eq(targets.data).cpu().sum().float()
# Backward and optimize
optimizer.zero_grad()
loss.backward()
optimizer.step()
progress_bar(batch_idx, len(train_loader),
'Loss: %.3f | Acc: %.3f%% (%d/%d)'
% (train_loss/(batch_idx+1), 100.*correct/total, correct, total))
return train_loss/batch_idx, 100.*correct/total
def test(epoch):
model.eval()
test_loss = 0
correct = 0
total = 0
for batch_idx, (inputs, targets) in enumerate(test_loader):
inputs, targets = inputs.to(device), targets.to(device)
outputs = model(inputs)
loss = criterion(outputs, targets)
test_loss += loss.item()
_, pred_idx = torch.max(outputs.data, 1)
total += targets.size(0)
correct += pred_idx.eq(targets.data).cpu().sum().float()
progress_bar(batch_idx, len(test_loader),
'Loss: %.3f | Acc: %.3f%% (%d/%d)'
% (test_loss/(batch_idx+1), 100.*correct/total, correct, total))
return test_loss/batch_idx, 100.*correct/total
def save_checkpoint(acc, epoch):
print('=====> Saving checkpoint...')
state = {
'model': model,
'acc': acc,
'epoch': epoch,
'rng_state': torch.get_rng_state()
}
if not os.path.isdir('checkpoint'):
os.mkdir('checkpoint')
torch.save(state, args.save_dir + args.name + '_epoch' + str(epoch) + '.ckpt')
# Decrease the learning rate at 100 and 150 epoch
def adjust_lr(optimizer, epoch):
lr = args.lr
if epoch >= 100:
lr /= 10
if epoch >= 150:
lr /= 10
for param_group in optimizer.param_groups:
param_group['lr'] = lr
if __name__ == '__main__':
parser = argparse.ArgumentParser()
# Directory
parser.add_argument('--data-dir', default='./data/', help='data path')
parser.add_argument('--save-dir', default='./checkpoint/', help='save path')
# Hyper-parameters
parser.add_argument('--lr', type=float, default=0.1, help='learning rate (default=0.1)')
parser.add_argument('--mu', type=float, default=1, help='Nuclear Norm hyper-param (default: 1)')
parser.add_argument('--svdprob', type=float, default=0.8, help='USVT hyper-param (default: 0.8)')
parser.add_argument('--startp', type=float, default=0.8, help='start probability of mask sampling (default: 0.8)')
parser.add_argument('--endp', type=float, default=1, help='end probability of mask sampling (default: 1)')
parser.add_argument('--batch-size', '-b', type=int, default=256, help='batch size')
parser.add_argument('--epoch', type=int, default=200, help='total epochs')
parser.add_argument('--no-augment', dest='augment', action='store_false')
parser.add_argument('--decay', type=float, default=1e-4, help='weight decay')
parser.add_argument('--mask-num', type=int, default=10, help='number of sampled masks (default: 10)')
parser.add_argument('--num_ckpt_steps', type=int, default=10, help='save checkpoint steps (default: 10)')
# ME parameters
parser.add_argument('--me-channel', type=str, default='concat',
choices=['separate', 'concat'],
help='handle RGB channels separately as independent matrices, or jointly by concatenating')
parser.add_argument('--me-type', type=str, default='usvt',
choices=['usvt', 'softimp', 'nucnorm'],
help='method of matrix estimation')
# Utility parameters
parser.add_argument('--resume', '-r', action='store_true', help='resume from checkpoint')
parser.add_argument('--model', type=str, default='ResNet18', help='choose model type (default: ResNet18)')
parser.add_argument('--name', type=str, help='name of the run')
args = parser.parse_args()
# Data
print('=====> Preparing data...')
if args.augment:
transform_train = transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465),
(0.2023, 0.1994, 0.2010)),
])
else:
transform_train = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465),
(0.2023, 0.1994, 0.2010)),
])
transform_test = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465),
(0.2023, 0.1994, 0.2010)),
])
train_dataset = CIFAR10_Dataset(True, target_transform)
test_dataset = CIFAR10_Dataset(False, target_transform)
if torch.cuda.is_available():
n_gpu = torch.cuda.device_count()
batch_size = args.batch_size * n_gpu
train_loader = torch.utils.data.DataLoader(dataset=train_dataset,
batch_size=batch_size,
shuffle=True,
num_workers=6*n_gpu)
test_loader = torch.utils.data.DataLoader(dataset=test_dataset,
batch_size=batch_size,
shuffle=False,
num_workers=6*n_gpu)
# Models
if args.resume:
print('=====> Resuming from checkpoint...')
assert os.path.isdir('checkpoint'), 'Error: no checkpoint directory found!'
checkpoint = torch.load(args.save_dir + args.name + '.ckpt')
model = checkpoint['model']
acc = checkpoint['acc']
START_EPOCH = checkpoint['epoch'] + 1
rng_state = checkpoint['rng_state']
torch.set_rng_state(rng_state)
else:
print('=====> Building model...')
model = models.__dict__[args.model]()
model = model.to(device)
if not os.path.isdir('results'):
os.mkdir('results')
logname = ('results/log_' + args.name + '.csv')
if torch.cuda.device_count() > 1:
print("=====> Use", torch.cuda.device_count(), "GPUs")
model = nn.DataParallel(model)
# Loss and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=args.lr, momentum=0.9, weight_decay=args.decay)
if not os.path.exists(logname):
with open(logname, 'w') as logfile:
logwriter = csv.writer(logfile, delimiter=',')
logwriter.writerow(['Epoch', 'Train Loss', 'Train Acc', 'Test Loss', 'Test Acc'])
for epoch in range(START_EPOCH, args.epoch):
train_loss, train_acc = train(epoch)
test_loss, test_acc = test(epoch)
adjust_lr(optimizer, epoch)
with open(logname, 'a') as logfile:
logwriter = csv.writer(logfile, delimiter=',')
logwriter.writerow([epoch, train_loss, train_acc, test_loss, test_acc])
if epoch % args.num_ckpt_steps == 0:
save_checkpoint(test_acc, epoch)