forked from uvm-neurobotics-lab/ANML
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevaluate_classification.py
422 lines (337 loc) · 18 KB
/
evaluate_classification.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
import argparse
import logging
import random
import pickle
import numpy as np
import torch
import torch.nn as nn
from pandas import DataFrame
from tensorboardX import SummaryWriter
from torch.nn import functional as F
import datasets.datasetfactory as df
import model.learner as learner
import model.modelfactory as mf
import utils
from experiment.experiment import experiment
logger = logging.getLogger('experiment')
def pickle_dict(dictionary, filename):
p = pickle.Pickler(open("{0}.p".format(filename),"wb"))
p.fast = True
p.dump(dictionary)
def main(args):
# torch.autograd.set_detect_anomaly(True)
torch.manual_seed(args.seed)
torch.cuda.manual_seed_all(args.seed)
np.random.seed(args.seed)
random.seed(args.seed)
my_experiment = experiment(args.name, args, "../results/", args.commit)
writer = SummaryWriter(my_experiment.path + "tensorboard")
results_df = DataFrame(columns=["Num Classes", "Meta-test test", "Meta-test train", "LR"])
results_path = os.path.join(my_experiment.path, "accuracies_vs_numclasses.csv")
print("results_path:", results_path)
logger = logging.getLogger('experiment')
logger.setLevel(logging.INFO)
total_clases = 10
frozen_layers = []
for temp in range(args.rln * 2):
frozen_layers.append("vars." + str(temp))
logger.info("Frozen layers = %s", " ".join(frozen_layers))
#for v in range(6):
# frozen_layers.append("vars_bn.{0}".format(v))
final_results_all = []
temp_result = []
total_clases = args.schedule
for tot_class in total_clases:
lr_list = [0.001, 0.0006, 0.0004, 0.00035, 0.0003, 0.00025, 0.0002, 0.00015, 0.0001, 0.00009, 0.00008, 0.00006, 0.00003, 0.00001]
lr_all = []
for lr_search in range(10):
# lr_all = [0.001]
# for lr_search in range(0):
keep = np.random.choice(list(range(650)), tot_class, replace=False)
dataset = utils.remove_classes_omni(
df.DatasetFactory.get_dataset("omniglot", train=True, background=False, path=args.dataset_path), keep)
iterator_sorted = torch.utils.data.DataLoader(
utils.iterator_sorter_omni(dataset, False, classes=total_clases),
batch_size=1,
shuffle=args.iid, num_workers=2)
dataset = utils.remove_classes_omni(
df.DatasetFactory.get_dataset("omniglot", train=not args.test, background=False, path=args.dataset_path),
keep)
iterator = torch.utils.data.DataLoader(dataset, batch_size=1,
shuffle=False, num_workers=1)
print(args)
if torch.cuda.is_available():
device = torch.device('cuda')
else:
device = torch.device('cpu')
results_mem_size = {}
for mem_size in [args.memory]:
max_acc = -10
max_lr = -10
for lr in lr_list:
print(lr)
logger.info(f"Loading model {args.model}")
maml = torch.load(args.model, map_location='cpu')
if args.scratch:
config = mf.ModelFactory.get_model("OML", args.dataset)
maml = learner.Learner(config)
# maml = MetaLearingClassification(args, config).to(device).net
maml = maml.to(device)
for name, param in maml.named_parameters():
param.learn = True
for name, param in maml.named_parameters():
# logger.info(name)
if name in frozen_layers:
param.learn = False
else:
if args.reset:
w = nn.Parameter(torch.ones_like(param))
# logger.info("W shape = %s", str(len(w.shape)))
if len(w.shape) > 1:
torch.nn.init.kaiming_normal_(w)
else:
w = nn.Parameter(torch.zeros_like(param))
param.data = w
param.learn = True
# frozen_layers = []
# for temp in range(args.rln * 2):
# frozen_layers.append("vars." + str(temp))
torch.nn.init.kaiming_normal_(maml.parameters()[-2])
w = nn.Parameter(torch.zeros_like(maml.parameters()[-1]))
maml.parameters()[-1].data = w
if args.neuromodulation:
weights2reset = ["vars_26"]
biases2reset = ["vars_27"]
else:
weights2reset = ["vars_14"]
biases2reset = ["vars_15"]
for n, a in maml.named_parameters():
n = n.replace(".", "_")
if n in weights2reset:
w = nn.Parameter(torch.ones_like(a)).to(device)
torch.nn.init.kaiming_normal_(w)
a.data = w
if n in biases2reset:
w = nn.Parameter(torch.zeros_like(a)).to(device)
a.data = w
filter_list = ["vars.{0}".format(v) for v in range(6)]
logger.info("Filter list = %s", ",".join(filter_list))
list_of_names = list(
map(lambda x: x[1], list(filter(lambda x: x[0] not in filter_list, maml.named_parameters()))))
list_of_params = list(filter(lambda x: x.learn, maml.parameters()))
list_of_names = list(filter(lambda x: x[1].learn, maml.named_parameters()))
if args.scratch or args.no_freeze:
print("Empty filter list")
list_of_params = maml.parameters()
for x in list_of_names:
logger.info("Unfrozen layer = %s", str(x[0]))
opt = torch.optim.Adam(list_of_params, lr=lr)
for _ in range(0, args.epoch):
for img, y in iterator_sorted:
img = img.to(device)
y = y.to(device)
pred = maml(img)
opt.zero_grad()
loss = F.cross_entropy(pred, y)
loss.backward()
opt.step()
logger.info("Result after one epoch for LR = %f", lr)
correct = 0
for img, target in iterator:
img = img.to(device)
target = target.to(device)
logits_q = maml(img, vars=None, bn_training=False, feature=False)
pred_q = (logits_q).argmax(dim=1)
correct += torch.eq(pred_q, target).sum().item() / len(img)
logger.info(str(correct / len(iterator)))
if (correct / len(iterator) > max_acc):
max_acc = correct / len(iterator)
max_lr = lr
lr_all.append(max_lr)
results_mem_size[mem_size] = (max_acc, max_lr)
logger.info("Final Max Result = %s", str(max_acc))
writer.add_scalar(f'/finetune/best_acc_lr_{lr}', max_acc, lr_search)
temp_result.append((tot_class, results_mem_size))
print("A= ", results_mem_size)
logger.info("Temp Results = %s", str(results_mem_size))
my_experiment.results["Temp Results"] = temp_result
my_experiment.store_json()
print("LR RESULTS = ", temp_result)
from scipy import stats
best_lr = float(stats.mode(lr_all)[0][0])
logger.info(f"BEST LR={best_lr} for num_class={tot_class}")
writer.add_scalar('/lr_search/best_per_num_classes', best_lr, tot_class)
for aoo in range(args.runs):
keep = np.random.choice(list(range(650)), tot_class, replace=False)
if args.dataset == "omniglot":
dataset_train = utils.remove_classes_omni(
df.DatasetFactory.get_dataset("omniglot", train=True, background=False), keep)
dataset_test = utils.remove_classes_omni(
df.DatasetFactory.get_dataset("omniglot", train=False, background=False), keep)
iterator_sorted = torch.utils.data.DataLoader(dataset_train, batch_size=1,shuffle=args.iid, num_workers=2)
iterator_train = torch.utils.data.DataLoader(dataset_train, batch_size=1, shuffle=False, num_workers=1)
iterator_test = torch.utils.data.DataLoader(dataset_test, batch_size=1, shuffle=False, num_workers=1)
elif args.dataset == "CIFAR100":
keep = np.random.choice(list(range(50, 100)), tot_class)
dataset = utils.remove_classes(df.DatasetFactory.get_dataset(args.dataset, train=True), keep)
iterator_sorted = torch.utils.data.DataLoader(
utils.iterator_sorter(dataset, False, classes=tot_class),
batch_size=16,
shuffle=args.iid, num_workers=2)
dataset = utils.remove_classes(df.DatasetFactory.get_dataset(args.dataset, train=False), keep)
iterator = torch.utils.data.DataLoader(dataset, batch_size=128,
shuffle=False, num_workers=1)
print(args)
if torch.cuda.is_available():
device = torch.device('cuda')
else:
device = torch.device('cpu')
results_mem_size = {}
for mem_size in [args.memory]:
max_acc = -10
max_lr = -10
lr = best_lr
logger.info(f"Using best lr {best_lr}")
logger.info(f"Loading model {args.model}")
maml = torch.load(args.model, map_location='cpu')
if args.scratch:
config = mf.ModelFactory.get_model("MRCL", args.dataset)
maml = learner.Learner(config)
maml = maml.to(device)
for name, param in maml.named_parameters():
param.learn = True
for name, param in maml.named_parameters():
# logger.info(name)
if name in frozen_layers:
param.learn = False
else:
if args.reset:
w = nn.Parameter(torch.ones_like(param))
if len(w.shape) > 1:
torch.nn.init.kaiming_normal_(w)
else:
w = nn.Parameter(torch.zeros_like(param))
param.data = w
param.learn = True
# frozen_layers = []
# for temp in range(args.rln * 2):
# frozen_layers.append("vars." + str(temp))
torch.nn.init.kaiming_normal_(maml.parameters()[-2])
w = nn.Parameter(torch.zeros_like(maml.parameters()[-1]))
maml.parameters()[-1].data = w
for n, a in maml.named_parameters():
n = n.replace(".", "_")
if args.neuromodulation:
weights2reset = ["vars_26"]
biases2reset = ["vars_27"]
else:
weights2reset = ["vars_14"]
biases2reset = ["vars_15"]
for n, a in maml.named_parameters():
n = n.replace(".", "_")
if n in weights2reset:
w = nn.Parameter(torch.ones_like(a)).to(device)
torch.nn.init.kaiming_normal_(w)
a.data = w
if n in biases2reset:
w = nn.Parameter(torch.zeros_like(a)).to(device)
a.data = w
correct = 0
for img, target in iterator_train:
with torch.no_grad():
img = img.to(device)
target = target.to(device)
logits_q = maml(img, vars=None, bn_training=False, feature=False)
pred_q = (logits_q).argmax(dim=1)
correct += torch.eq(pred_q, target).sum().item() / len(img)
logger.info("Pre-epoch train accuracy %s", str(correct / len(iterator_train)))
correct = 0
for img, target in iterator_test:
with torch.no_grad():
img = img.to(device)
target = target.to(device)
logits_q = maml(img, vars=None, bn_training=False, feature=False)
pred_q = (logits_q).argmax(dim=1)
correct += torch.eq(pred_q, target).sum().item() / len(img)
logger.info("Pre-epoch test accuracy %s", str(correct / len(iterator_test)))
list_of_params = list(filter(lambda x: x.learn, maml.parameters()))
list_of_names = list(filter(lambda x: x[1].learn, maml.named_parameters()))
if args.scratch or args.no_freeze:
print("Empty filter list")
list_of_params = maml.parameters()
for x in list_of_names:
logger.info("Unfrozen layer = %s", str(x[0]))
opt = torch.optim.Adam(list_of_params, lr=lr)
for epoch in range(0, args.epoch):
for img, y in iterator_sorted:
img = img.to(device)
y = y.to(device)
pred = maml(img)
opt.zero_grad()
loss = F.cross_entropy(pred, y)
loss.backward()
opt.step()
logger.info(f"Result after epoch {epoch} for LR = {lr}")
correct = 0
total = 0
for img, target in iterator_train:
img = img.to(device)
target = target.to(device)
logits_q = maml(img, vars=None, bn_training=False, feature=False)
pred_q = (logits_q).argmax(dim=1)
correct += torch.eq(pred_q, target).sum().item()
total += len(target)
train_acc = correct / total
correct = 0
total = 0
for img, target in iterator_test:
img = img.to(device)
target = target.to(device)
logits_q = maml(img, vars=None, bn_training=False, feature=False)
pred_q = (logits_q).argmax(dim=1)
correct += torch.eq(pred_q, target).sum().item()
total += len(target)
test_acc = correct / total
logger.info(str(test_acc))
if (test_acc > max_acc):
max_acc = test_acc
max_lr = lr
lr_list = [max_lr]
results_mem_size[mem_size] = (max_acc, max_lr)
logger.info("Final Max Result = %s", str(max_acc))
results_df.loc[len(results_df.index)] = (tot_class, test_acc, train_acc, lr)
writer.add_scalar(f'/metatest/train_acc/num_classes_{tot_class}', train_acc, aoo)
writer.add_scalar(f'/metatest/test_acc/num_classes_{tot_class}', test_acc, aoo)
writer.add_scalar(f'/best_acc/test_acc/best_per_num_classes', max_acc, tot_class)
final_results_all.append((tot_class, results_mem_size))
print("A= ", results_mem_size)
logger.info("Final results = %s", str(results_mem_size))
my_experiment.results["Final Results"] = final_results_all
my_experiment.store_json()
print("FINAL RESULTS = ", final_results_all)
results_df.to_csv(results_path)
writer.close()
if __name__ == '__main__':
argparser = argparse.ArgumentParser()
argparser.add_argument('--epoch', type=int, help='epoch number', default=1)
argparser.add_argument('--seed', type=int, help='epoch number', default=222)
argparser.add_argument('--schedule', type=int, nargs='+', default=[10,50,75,100,200,300,400,500,600],
help='Decrease learning rate at these epochs.')
argparser.add_argument('--memory', type=int, help='epoch number', default=0)
argparser.add_argument('--model', type=str, help='epoch number', default="none")
argparser.add_argument('--scratch', action='store_true', default=False)
argparser.add_argument('--dataset', help='Name of experiment', default="omniglot")
argparser.add_argument('--dataset-path', help='Name of experiment', default=None)
argparser.add_argument('--name', help='Name of experiment', default="evaluation")
argparser.add_argument("--commit", action="store_true")
argparser.add_argument("--no-freeze", action="store_true")
argparser.add_argument('--reset', action="store_true")
argparser.add_argument('--test', action="store_true")
argparser.add_argument("--iid", action="store_true")
argparser.add_argument("--rln", type=int, default=6)
argparser.add_argument("--runs", type=int, default=50)
argparser.add_argument("--neuromodulation", action="store_true")
args = argparser.parse_args()
import os
args.name = "/".join([args.dataset, "eval", str(args.epoch).replace(".", "_"), args.name])
main(args)