-
Notifications
You must be signed in to change notification settings - Fork 20
/
main.py
147 lines (132 loc) · 6.29 KB
/
main.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
import torch
import torch.utils.data
import torch.nn as nn
import torch.optim as optim
from torchvision import transforms
from torch.nn import functional as F
from torch.utils.data import DataLoader
from torch.optim.lr_scheduler import StepLR
from torch.autograd import Variable
import os
import math
import argparse
import resource
import pandas as pd
import numpy as np
import sklearn.metrics
from scipy import stats
from PIL import Image
from PASS import protoAugSSL
from ResNet import resnet18_cbam
from myNetwork import network
from iCIFAR100 import iCIFAR100
parser = argparse.ArgumentParser(description='Prototype Augmentation and Self-Supervision for Incremental Learning')
parser.add_argument('--epochs', default=101, type=int, help='Total number of epochs to run')
parser.add_argument('--batch_size', default=64, type=int, help='Batch size for training')
parser.add_argument('--print_freq', default=10, type=int, help='print frequency (default: 10)')
parser.add_argument('--data_name', default='cifar100', type=str, help='Dataset name to use')
parser.add_argument('--total_nc', default=100, type=int, help='class number for the dataset')
parser.add_argument('--fg_nc', default=50, type=int, help='the number of classes in first task')
parser.add_argument('--task_num', default=10, type=int, help='the number of incremental steps')
parser.add_argument('--learning_rate', default=0.001, type=float, help='initial learning rate')
parser.add_argument('--protoAug_weight', default=10.0, type=float, help='protoAug loss weight')
parser.add_argument('--kd_weight', default=10.0, type=float, help='knowledge distillation loss weight')
parser.add_argument('--temp', default=0.1, type=float, help='trianing time temperature')
parser.add_argument('--gpu', default='0', type=str, help='GPU id to use')
parser.add_argument('--save_path', default='model_saved_check/', type=str, help='save files directory')
args = parser.parse_args()
print(args)
def map_new_class_index(y, order):
return np.array(list(map(lambda x: order.index(x), y)))
def setup_data(test_targets, shuffle, seed):
order = [i for i in range(len(np.unique(test_targets)))]
if shuffle:
np.random.seed(seed)
order = np.random.permutation(len(order)).tolist()
else:
order = range(len(order))
class_order = order
print(100 * '#')
print(class_order)
return map_new_class_index(test_targets, class_order)
def main():
cuda_index = 'cuda:' + args.gpu
device = torch.device(cuda_index if torch.cuda.is_available() else "cpu")
task_size = int((args.total_nc - args.fg_nc) / args.task_num) # number of classes in each incremental step
file_name = args.data_name + '_' + str(args.fg_nc) + '_' + str(args.task_num) + '*' + str(task_size)
feature_extractor = resnet18_cbam()
model = protoAugSSL(args, file_name, feature_extractor, task_size, device)
class_set = list(range(args.total_nc))
model.setup_data(shuffle=True, seed=1993)
for i in range(args.task_num+1):
if i == 0:
old_class = 0
else:
old_class = len(class_set[:args.fg_nc + (i - 1) * task_size])
model.beforeTrain(i)
model.train(i, old_class=old_class)
model.afterTrain()
####### Test ######
test_transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5071, 0.4867, 0.4408), (0.2675, 0.2565, 0.2761))])
print("############# Test for each Task #############")
test_dataset = iCIFAR100('./dataset', test_transform=test_transform, train=False, download=True)
test_dataset.targets = setup_data(test_dataset.targets, shuffle=True, seed=1993)
acc_all = []
for current_task in range(args.task_num+1):
class_index = args.fg_nc + current_task*task_size
filename = args.save_path + file_name + '/' + '%d_model.pkl' % (class_index)
model = torch.load(filename)
model.eval()
acc_up2now = []
for i in range(current_task+1):
if i == 0:
classes = [0, args.fg_nc]
else:
classes = [args.fg_nc + (i - 1) * task_size, args.fg_nc + i * task_size]
test_dataset.getTestData_up2now(classes)
test_loader = DataLoader(dataset=test_dataset,
shuffle=True,
batch_size=args.batch_size)
correct, total = 0.0, 0.0
for setp, (indexs, imgs, labels) in enumerate(test_loader):
imgs, labels = imgs.to(device), labels.to(device)
with torch.no_grad():
outputs = model(imgs)
outputs = outputs[:, ::4]
predicts = torch.max(outputs, dim=1)[1]
correct += (predicts.cpu() == labels.cpu()).sum()
total += len(labels)
accuracy = correct.item() / total
acc_up2now.append(accuracy)
if current_task < args.task_num:
acc_up2now.extend((args.task_num-current_task)*[0])
acc_all.append(acc_up2now)
print(acc_up2now)
print(acc_all)
print("############# Test for up2now Task #############")
test_dataset = iCIFAR100('./dataset', test_transform=test_transform, train=False, download=True)
test_dataset.targets = setup_data(test_dataset.targets, shuffle=True, seed=1993)
for current_task in range(args.task_num+1):
class_index = args.fg_nc + current_task*task_size
filename = args.save_path + file_name + '/' + '%d_model.pkl' % (class_index)
model = torch.load(filename)
model.to(device)
model.eval()
classes = [0, args.fg_nc + current_task * task_size]
test_dataset.getTestData_up2now(classes)
test_loader = DataLoader(dataset=test_dataset,
shuffle=True,
batch_size=args.batch_size)
correct, total = 0.0, 0.0
for setp, (indexs, imgs, labels) in enumerate(test_loader):
imgs, labels = imgs.to(device), labels.to(device)
with torch.no_grad():
outputs = model(imgs)
outputs = outputs[:, ::4]
predicts = torch.max(outputs, dim=1)[1]
correct += (predicts.cpu() == labels.cpu()).sum()
total += len(labels)
accuracy = correct.item() / total
print(accuracy)
if __name__ == "__main__":
main()