-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
280 lines (219 loc) · 9.01 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
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
# -*- coding: utf-8 -*-
"""IL_project.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1-aj7oHOAjpjuhqT-ZoZn5fRj4ZQRhnnT
**Import libraries**
"""
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, ConcatDataset
import torchvision
from torchvision import datasets, models, transforms
import numpy as np
from tqdm import tqdm
import random
from data_loader import iCIFAR100
from model import incrementalNet
from iCarl import iCaRLNet
from LF_iCarl import LFiCaRLNet
from sklearn.metrics import confusion_matrix
import seaborn as sn
import pandas as pd
import matplotlib.pyplot as plt
"""**Prepare Dataset**"""
train_transform = transforms.Compose([transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(), # Turn PIL Image to torch.Tensor
transforms.Normalize((0.507, 0.487, 0.441), (0.267, 0.256, 0.276))
])
eval_transform = transforms.Compose([transforms.ToTensor(), # Turn PIL Image to torch.Tensor
transforms.Normalize((0.507, 0.487, 0.441), (0.267, 0.256, 0.276))
])
random.seed(34)
order = np.arange(0,100)
random.shuffle(order)
"""LEARNING WITHOUT FORGETTING/FINETUNING"""
BATCH_SIZE = 128
iNet = incrementalNet(10, 100, finetuning=True, verbose = False)
iNet.cuda()
conf_matrix_pred = []
conf_matrix_labels = []
for i in range(0,100,10):
train_dataset = iCIFAR100("cifar-100", classes=order[i:(i+10)], train=True, download=True, transform=train_transform)
test_dataset = iCIFAR100("cifar-100", classes=order[0:(i+10)], train=False, transform=eval_transform)
test_dataloader = DataLoader(test_dataset, batch_size=BATCH_SIZE,
shuffle=False, num_workers=4, drop_last=False)
train_dataloader = DataLoader(train_dataset, batch_size=BATCH_SIZE,
shuffle=False, num_workers=4, drop_last=False)
iNet.update_representation(train_dataset, order)
iNet.n_known += iNet.n_classes
print ("\niCaRL classes: %d" % iNet.n_known)
total = 0.0
correct = 0.0
iNet.resnet.train(False)
for images, labels in train_dataloader:
images = images.to(device="cuda")
labels = labels.to(device="cuda")
preds = iNet.forward(images)
_, preds = torch.max(preds.data, 1)
#preds = torch.tensor([order[i] for i in preds]).cuda()
total += labels.size(0)
correct += (preds == labels.data).sum()
accuracy = 100 * correct / total
print('Train Accuracy: %.1f %%' % (accuracy))
if iNet.finetuning:
suf = 'finetuning.txt'
else:
suf = 'lwf.txt'
with open("train_accuracy_"+suf, "a") as f:
f.write(str(accuracy.data)+"\n")
total = 0.0
correct = 0.0
for images, labels in test_dataloader:
images = images.to(device="cuda")
labels = labels.to(device="cuda")
preds = iNet.forward(images)
_, preds = torch.max(preds.data, 1)
#preds = torch.tensor([order[i] for i in preds]).cuda()
total += labels.size(0)
correct += (preds == labels.data).sum()
if iNet.n_known == 100:
conf_matrix_pred += list(preds.data)
conf_matrix_labels += list(labels.data)
accuracy = 100 * correct / total
print('Test Accuracy: %.1f %%\n---------------' % (accuracy))
with open("test_accuracy_"+suf, "a") as f:
f.write(str(accuracy.data)+"\n")
array = confusion_matrix([list(order).index(i.item()) for i in conf_matrix_labels], [list(order).index(i.item()) for i in conf_matrix_pred])
df_cm = pd.DataFrame(array, range(100), range(100))
plt.figure(figsize = (20,14))
sn.heatmap(df_cm)
"""**ICARL**"""
K = 2000 # number of exemplars
"""Possible choices as classifier:
'standard' --> Nearest Mean
'svm' -------> Linear SVM
'knn' -------> K-nearest neighbours
'trees' -----> Random forest
"""
cl_name = 'standard'
"""Possible choices as loss combination:
'bce+bce' --> class: bce, dist: bce
'ce+bce' ---> class: ce, dist: bce
'l2+bce' ---> class: L2, dist: bce
'bce+l2' ---> class: bce, dist: L2
"""
loss_combination = 'bce+bce'
icarl = iCaRLNet(10, 100, eval_transform, loss=loss_combination, classifier_name=cl_name, verbose=False)
icarl.cuda()
BATCH_SIZE = 128
conf_matrix_pred = []
conf_matrix_labels = []
for i in range(0,100,10):
train_dataset = iCIFAR100("cifar-100", classes=order[i:(i+10)], train=True, download=True, transform=train_transform)
test_dataset = iCIFAR100("cifar-100", classes=order[0:(i+10)], train=False, transform=eval_transform)
train_dataloader = DataLoader(train_dataset, batch_size=BATCH_SIZE, shuffle=False, num_workers=4)
test_dataloader = DataLoader(test_dataset, batch_size=BATCH_SIZE, shuffle=False, num_workers=4)
icarl.update_representation(train_dataset, order)
icarl.n_known += icarl.n_classes
m = int(K / icarl.n_known)
# Compute centroids before exemplars reduction
if cl_name == 'standard':
icarl.compute_means_and_features(train_dataset)
# Reduce exemplar sets for known classes
icarl.reduce_exemplar_sets(m)
# Construct exemplar sets for new classes
for y in tqdm(order[i:(i+10)], desc="Generating exemplars"):
images = train_dataset.get_image_class(y)
icarl.construct_exemplar_set(images, m)
# Compute features after exemplars construction
if cl_name != 'standard':
icarl.compute_means_and_features(train_dataset)
print ("\niCaRL classes: %d" % icarl.n_known)
total = 0.0
correct = 0.0
icarl.resnet.eval()
for images, labels in train_dataloader:
images = images.to(device="cuda")
preds = icarl.classify(images)
total += labels.size(0)
correct += (preds.data.cpu() == labels).sum()
accuracy = 100 * correct / total
print('Train Accuracy: %.3f %%' % (accuracy))
with open("train_accuracy_iCaRL.txt", "a") as f:
f.write(str(accuracy.data)+"\n")
total = 0.0
correct = 0.0
icarl.resnet.eval()
for images, labels in test_dataloader:
images = images.to(device="cuda")
preds = icarl.classify(images)
total += labels.size(0)
correct += (preds.data.cpu() == labels).sum()
if icarl.n_known == 100:
conf_matrix_pred += list(preds.data)
conf_matrix_labels += list(labels.data)
accuracy = 100 * correct / total
print('Test Accuracy: %.3f %%\n---------------' % (accuracy))
with open("test_accuracy_iCaRL.txt", "a") as f:
f.write(str(accuracy.data)+"\n")
array = confusion_matrix([list(order).index(i.item()) for i in conf_matrix_labels], [list(order).index(i.item()) for i in conf_matrix_pred])
df_cm = pd.DataFrame(array, range(100), range(100))
plt.figure(figsize = (20,14))
sn.heatmap(df_cm)
"""**MODIFIED ICARL**"""
K = 2000 # number of exemplars
icarl = LFiCaRLNet(10, 100, eval_transform, verbose=False)
icarl.cuda()
BATCH_SIZE = 128
conf_matrix_pred = []
conf_matrix_labels = []
for i in range(0,100,10):
train_dataset = iCIFAR100("cifar-100", classes=order[i:(i+10)], train=True, download=True, transform=train_transform)
test_dataset = iCIFAR100("cifar-100", classes=order[0:(i+10)], train=False, transform=eval_transform)
train_dataloader = DataLoader(train_dataset, batch_size=BATCH_SIZE, shuffle=False, num_workers=4)
test_dataloader = DataLoader(test_dataset, batch_size=BATCH_SIZE, shuffle=False, num_workers=4)
icarl.update_representation(train_dataset, order)
icarl.n_known += icarl.n_classes
m = int(K / icarl.n_known)
# Compute centroids before exemplars reduction
icarl.compute_means_and_features(train_dataset)
# Reduce exemplar sets for known classes
icarl.reduce_exemplar_sets(m)
# Construct exemplar sets for new classes
for y in tqdm(order[i:(i+10)], desc="Generating exemplars"):
images = train_dataset.get_image_class(y)
icarl.construct_exemplar_set(images, m)
print ("\niCaRL classes: %d" % icarl.n_known)
total = 0.0
correct = 0.0
icarl.resnet.eval()
for images, labels in train_dataloader:
images = images.to(device="cuda")
preds = icarl.classify(images)
total += labels.size(0)
correct += (preds.data.cpu() == labels).sum()
accuracy = 100 * correct / total
print('Train Accuracy: %.3f %%' % (accuracy))
with open("train_accuracy_LF_iCaRL.txt", "a") as f:
f.write(str(accuracy.data)+"\n")
total = 0.0
correct = 0.0
icarl.resnet.eval()
for images, labels in test_dataloader:
images = images.to(device="cuda")
preds = icarl.classify(images)
total += labels.size(0)
correct += (preds.data.cpu() == labels).sum()
if icarl.n_known == 100:
conf_matrix_pred += list(preds.data)
conf_matrix_labels += list(labels.data)
accuracy = 100 * correct / total
print('Test Accuracy: %.3f %%\n---------------' % (accuracy))
with open("test_accuracy_LF_iCaRL.txt", "a") as f:
f.write(str(accuracy.data)+"\n")
array = confusion_matrix([list(order).index(i.item()) for i in conf_matrix_labels], [list(order).index(i.item()) for i in conf_matrix_pred])
df_cm = pd.DataFrame(array, range(100), range(100))
plt.figure(figsize = (20,14))
sn.heatmap(df_cm)