-
Notifications
You must be signed in to change notification settings - Fork 5
/
resnet34_corn.py
292 lines (222 loc) · 7.83 KB
/
resnet34_corn.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
import argparse
from functools import partial
import os
import time
import torch
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torch.utils.data import SubsetRandomSampler
from torchvision.datasets import MNIST
from torchvision import transforms
# Import from local helper file
from helper import parse_cmdline_args
from helper import compute_mae_and_rmse
from helper import resnet34base
# Argparse helper
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
args = parse_cmdline_args(parser)
##########################
# Settings and Setup
##########################
NUM_WORKERS = args.numworkers
LEARNING_RATE = args.learningrate
NUM_EPOCHS = args.epochs
BATCH_SIZE = args.batchsize
OUTPUT_DIR = args.output_dir
LOSS_PRINT_INTERVAL = args.loss_print_interval
if os.path.exists(args.output_dir):
raise ValueError('Output directory already exists.')
else:
os.makedirs(args.output_dir)
BEST_MODEL_PATH = os.path.join(args.output_dir, 'best_model.pt')
LOGFILE_PATH = os.path.join(args.output_dir, 'training.log')
if args.cuda >= 0 and torch.cuda.is_available():
DEVICE = torch.device(f'cuda:{args.cuda}')
else:
DEVICE = torch.device('cpu')
if args.seed == -1:
RANDOM_SEED = None
else:
RANDOM_SEED = args.seed
############################
# Dataset
############################
def train_transform():
return transforms.Compose([transforms.ToTensor()])
def validation_transform():
return transforms.Compose([transforms.ToTensor()])
NUM_CLASSES = 10
GRAYSCALE = True
RESNET34_AVGPOOLSIZE = 1
train_dataset = MNIST(root='./datasets',
train=True,
download=True,
transform=train_transform())
valid_dataset = MNIST(root='./datasets',
train=True,
transform=validation_transform(),
download=False)
test_dataset = MNIST(root='./datasets',
train=False,
transform=validation_transform(),
download=False)
train_indices = torch.arange(1000, 60000)
valid_indices = torch.arange(0, 1000)
train_sampler = SubsetRandomSampler(train_indices)
valid_sampler = SubsetRandomSampler(valid_indices)
train_loader = DataLoader(dataset=train_dataset,
batch_size=BATCH_SIZE,
shuffle=False, # SubsetRandomSampler shuffles
drop_last=True,
num_workers=NUM_WORKERS,
sampler=train_sampler)
valid_loader = DataLoader(dataset=valid_dataset,
batch_size=BATCH_SIZE,
shuffle=False,
num_workers=NUM_WORKERS,
sampler=valid_sampler)
test_loader = DataLoader(dataset=test_dataset,
batch_size=BATCH_SIZE,
shuffle=False,
num_workers=NUM_WORKERS)
##########################
# MODEL
##########################
model = resnet34base(
num_classes=NUM_CLASSES,
grayscale=GRAYSCALE,
resnet34_avg_poolsize=RESNET34_AVGPOOLSIZE)
model.output_layer = torch.nn.Linear(512, NUM_CLASSES-1)
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = self.avgpool(x)
x = x.view(x.size(0), -1)
logits = self.output_layer(x)
return logits
def add_method(obj, func):
'Bind a function and store it in an object'
setattr(obj, func.__name__, partial(func, obj))
add_method(model, forward)
model.to(DEVICE)
optimizer = torch.optim.Adam(model.parameters(), lr=LEARNING_RATE)
#######################################
# Loss and Evaluation Functions
#######################################
def loss_corn(logits, y_train, num_classes):
sets = []
for i in range(num_classes-1):
label_mask = y_train > i-1
label_tensor = (y_train[label_mask] > i).to(torch.int64)
sets.append((label_mask, label_tensor))
num_examples = 0
losses = 0.
for task_index, s in enumerate(sets):
train_examples = s[0]
train_labels = s[1]
if len(train_labels) < 1:
continue
num_examples += len(train_labels)
pred = logits[train_examples, task_index]
loss = -torch.sum(F.logsigmoid(pred)*train_labels
+ (F.logsigmoid(pred) - pred)*(1-train_labels)
)
losses += loss
return losses/num_examples
def label_from_logits(logits):
""" Converts logits to class labels.
This is function is specific to CORN.
"""
probas = torch.sigmoid(logits)
probas = torch.cumprod(probas, dim=1)
predict_levels = probas > 0.5
predicted_labels = torch.sum(predict_levels, dim=1)
return predicted_labels
#######################################
# Training
#######################################
best_valid_mae = torch.tensor(float('inf'))
s = (f'Script: {__file__}\n'
f'PyTorch version: {torch.__version__}\n'
f'Device: {DEVICE}\n'
f'Learning rate: {LEARNING_RATE}\n'
f'Batch size: {BATCH_SIZE}\n')
print(s)
with open(LOGFILE_PATH, 'w') as f:
f.write(f'{s}\n')
start_time = time.time()
for epoch in range(1, NUM_EPOCHS+1):
model.train()
for batch_idx, (features, targets) in enumerate(train_loader):
features = features.to(DEVICE)
targets = targets.to(DEVICE)
# FORWARD AND BACK PROP
logits = model(features)
# CORN loss
loss = loss_corn(logits, targets, NUM_CLASSES)
# ##--------------------------------------------------------------------###
optimizer.zero_grad()
loss.backward()
optimizer.step()
# Logging
if not batch_idx % LOSS_PRINT_INTERVAL:
s = (f'Epoch: {epoch:03d}/{NUM_EPOCHS:03d} | '
f'Batch {batch_idx:04d}/'
f'{len(train_dataset)//BATCH_SIZE:04d} | '
f'Loss: {loss:.4f}')
print(s)
with open(LOGFILE_PATH, 'a') as f:
f.write(f'{s}\n')
# Logging: Evaluate after epoch
model.eval()
with torch.no_grad():
valid_mae, valid_rmse = compute_mae_and_rmse(
model=model,
data_loader=valid_loader,
device=DEVICE,
label_from_logits_func=label_from_logits
)
if valid_mae < best_valid_mae:
best_valid_mae = valid_mae
best_epoch = epoch
torch.save(model.state_dict(), BEST_MODEL_PATH)
s = (f'MAE Current Valid: {valid_mae:.2f} Ep. {epoch}'
f' | Best Valid: {best_valid_mae:.2f} Ep. {best_epoch}')
s += f'\nTime elapsed: {(time.time() - start_time)/60:.2f} min'
print(s)
with open(LOGFILE_PATH, 'a') as f:
f.write('%s\n' % s)
# Final
model.load_state_dict(torch.load(BEST_MODEL_PATH))
model.eval()
with torch.no_grad():
train_mae, train_rmse = compute_mae_and_rmse(
model=model,
data_loader=train_loader,
device=DEVICE,
label_from_logits_func=label_from_logits
)
valid_mae, valid_rmse = compute_mae_and_rmse(
model=model,
data_loader=valid_loader,
device=DEVICE,
label_from_logits_func=label_from_logits
)
test_mae, test_rmse = compute_mae_and_rmse(
model=model,
data_loader=valid_loader,
device=DEVICE,
label_from_logits_func=label_from_logits
)
s = ('\n\n=========================================\n\n'
'Performance of best model based on validation set MAE:'
f'Train MAE / RMSE: {train_mae:.2f} / {train_rmse:.2f}'
f'Valid MAE / RMSE: {valid_mae:.2f} / {valid_rmse:.2f}'
f'Test MAE / RMSE: {test_mae:.2f} / {test_rmse:.2f}')