Repository navigation
Expand file tree
/
Copy pathclassifier_ensemble.py
More file actions
348 lines (321 loc) · 13.3 KB
/
Copy pathclassifier_ensemble.py
File metadata and controls
348 lines (321 loc) · 13.3 KB
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
import numpy as np
from utils import get_features_fewshot_full_library
import os, random
import torch
import torch.nn as nn
import argparse
model_names = []
parser = argparse.ArgumentParser(description='Ensemble Classifier')
parser.add_argument('data', help='path to dataset')
parser.add_argument('--soft', action='store_true', default=False,
help='set for soft bagging, otherwise hard bagging')
parser.add_argument('--nway', default=5, type=int,
help='number of classes')
parser.add_argument('--kshot', default=1, type=int,
help='number of shots (support images per class)')
parser.add_argument('--kquery', default=15, type=int,
help='number of query images per class')
parser.add_argument('--num_epochs', default=50, type=int,
help='number of epochs')
parser.add_argument('--n_problems', default=600, type=int,
help='number of test problems')
parser.add_argument('--hidden_size1', default=512, type=int,
help='hidden layer1 size')
parser.add_argument('--hidden_size2', default=32, type=int,
help='hidden layer2 size')
parser.add_argument('--learning_rate', default=0.01, type=float,
help='learning rate')
parser.add_argument('--gamma', default=0.5, type=float,
help='constant value for L2')
parser.add_argument('--nol2', default = 'False', type=str,
help='set for No L2 regularization, otherwise use L2')
parser.add_argument('--linear', default='False', type=str,
help='set for linear model, otherwise use hidden layer')
parser.add_argument('--gpu', default=0, type=int,
help='GPU id to use.')
parser.add_argument('--model_choice', default = 'resnet18', type=str,
help='set for backbone models to choose from, otherwise use resnet18')
parser.add_argument('--val_on_birds', default = 'False', type=str,
help='set for indicating if validate on birds dataset')
args = parser.parse_args()
# Device configuration
device = torch.device("cuda:"+str(args.gpu) if torch.cuda.is_available() else "cpu")
# Fully connected neural network with one hidden layer
class ClassifierNetwork(nn.Module):
def __init__(self, input_size, hidden_size1, num_classes):
super(ClassifierNetwork, self).__init__()
if not args.linear:
self.fc1 = nn.Linear(input_size, hidden_size1)
self.tanh = nn.Tanh()
self.fc2 = nn.Linear(hidden_size1, num_classes)
else:
self.fc1 = nn.Linear(input_size, num_classes)
def forward(self, x):
out = self.fc1(x)
if not args.linear:
out = self.tanh(out)
out = self.fc2(out)
return out
def train_model(model, features, labels, criterion, optimizer,
num_epochs, g):
# Train the model
x = torch.tensor(features, dtype=torch.float32, device=device)
y = torch.tensor(labels, dtype=torch.long, device=device)
for epoch in range(num_epochs):
# Forward pass
outputs = model(x)
loss = criterion(outputs, y)
if not args.nol2:
c = torch.tensor(g, device=device)
l2_reg = torch.tensor(0., device=device)
for name, param in model.named_parameters():
if 'weight' in name:
l2_reg += torch.norm(param)
loss += c * l2_reg
# Backward and optimize
optimizer.zero_grad()
loss.backward()
optimizer.step()
def test_model(models, features_list, labels):
y = torch.tensor(labels, dtype=torch.long, device=device)
with torch.no_grad():
correct = 0
total = 0
outputs_list = []
for i, model in enumerate(models):
x = torch.tensor(features_list[i], dtype=torch.float32, device=device)
outputs_list.append(model(x))
preds = torch.stack(outputs_list, dim=0)
if args.soft:
preds = torch.mean(preds, dim=0)
_, predicted = torch.max(preds, 1)
else:
_, preds = torch.max(preds, dim=-1)
predicted, _ = torch.mode(preds, dim=0)
total += y.size(0)
correct += (predicted==y).sum().item()
return 100 * correct / total
def main():
data = args.data
nway = args.nway
kshot = args.kshot
kquery = args.kquery
n_img = kshot + kquery
n_problems = args.n_problems
num_epochs = args.num_epochs
hidden_size1 = args.hidden_size1
learning_rate = args.learning_rate
gamma = args.gamma
model_choice = args.model_choice
model_names = []
if model_choice == 'All':
model_names = ['resnet18',
'resnet34',
'resnet50',
'resnet101',
'resnet152',
'densenet121',
'densenet161',
'densenet169',
'densenet201']
else:
model_names.append(model_choice)
data_path = os.path.join(data, 'transferred_features_all')
folder_0 = os.path.join(data_path, model_names[0])
metaval_labels = [label \
for label in os.listdir(folder_0) \
if os.path.isdir(os.path.join(folder_0, label)) \
]
labels = metaval_labels
accs = []
for i in range(n_problems):
sampled_labels = random.sample(labels, nway)
features_support_list, labels_support, \
features_query_list, labels_query = get_features_fewshot_full_library(kshot, data_path, model_names,
sampled_labels, range(nway), nb_samples=n_img, shuffle=True)
models = []
for model_id in range(len(model_names)):
input_size = features_support_list[model_id].shape[1]
#Change the hyper-parameters according to the model choice
if nway == 5:
if model_names[model_id] == 'densenet121':
num_epochs = 200
hidden_size1 = 1024
learning_rate = 0.001
gamma = 0.2
if model_names[model_id] == 'densenet161':
num_epochs = 100
hidden_size1 = 1024
learning_rate = 0.0005
gamma = 0.2
if model_names[model_id] == 'densenet169':
num_epochs = 300
hidden_size1 = 1024
learning_rate = 0.0005
gamma = 0.5
if model_names[model_id] == 'densenet201':
num_epochs = 100
hidden_size1 = 512
learning_rate = 0.0005
gamma = 0.5
if model_names[model_id] == 'resnet101':
num_epochs = 100
hidden_size1 = 512
learning_rate = 0.001
gamma = 0.1
if model_names[model_id] == 'resnet152':
num_epochs = 300
hidden_size1 = 512
learning_rate = 0.0005
gamma = 0.1
if model_names[model_id] == 'resnet18':
num_epochs = 200
hidden_size1 = 512
learning_rate = 0.001
gamma = 0.2
if model_names[model_id] == 'resnet34':
num_epochs = 100
hidden_size1 = 1024
learning_rate = 0.0005
gamma = 0.2
if model_names[model_id] == 'resnet50':
num_epochs = 300
hidden_size1 = 2048
learning_rate = 0.0005
gamma = 0.1
if nway == 20:
if model_names[model_id] == 'densenet121':
num_epochs = 100
hidden_size1 = 1024
learning_rate = 0.0005
gamma = 0.2
if model_names[model_id] == 'densenet161':
num_epochs = 100
hidden_size1 = 512
learning_rate = 0.001
gamma = 0.1
if model_names[model_id] == 'densenet169':
num_epochs = 300
hidden_size1 = 512
learning_rate = 0.0005
gamma = 0.1
if model_names[model_id] == 'densenet201':
num_epochs = 200
hidden_size1 = 1024
learning_rate = 0.0005
gamma = 0.1
if model_names[model_id] == 'resnet101':
num_epochs = 200
hidden_size1 = 2048
learning_rate = 0.0005
gamma = 0.2
if model_names[model_id] == 'resnet152':
num_epochs = 100
hidden_size1 = 512
learning_rate = 0.0005
gamma = 0.2
if model_names[model_id] == 'resnet18':
num_epochs = 200
hidden_size1 = 2048
learning_rate = 0.0005
gamma = 0.1
if model_names[model_id] == 'resnet34':
num_epochs = 100
hidden_size1 = 1024
learning_rate = 0.0005
gamma = 0.1
if model_names[model_id] == 'resnet50':
num_epochs = 100
hidden_size1 = 1024
learning_rate = 0.0005
gamma = 0.1
if nway == 40:
if model_names[model_id] == 'densenet121':
num_epochs = 100
hidden_size1 = 2048
learning_rate = 0.0005
gamma = 0.1
if model_names[model_id] == 'densenet161':
num_epochs = 100
hidden_size1 = 512
learning_rate = 0.0005
gamma = 0.1
if model_names[model_id] == 'densenet169':
num_epochs = 100
hidden_size1 = 512
learning_rate = 0.001
gamma = 0.2
if model_names[model_id] == 'densenet201':
num_epochs = 100
hidden_size1 = 1024
learning_rate = 0.0005
gamma = 0.1
if model_names[model_id] == 'resnet101':
num_epochs = 100
hidden_size1 = 512
learning_rate = 0.0005
gamma = 0.1
if model_names[model_id] == 'resnet152':
num_epochs = 100
hidden_size1 = 1024
learning_rate = 0.0005
gamma = 0.1
if model_names[model_id] == 'resnet18':
num_epochs = 100
hidden_size1 = 512
learning_rate = 0.001
gamma = 0.1
if model_names[model_id] == 'resnet34':
num_epochs = 100
hidden_size1 = 2048
learning_rate = 0.0005
gamma = 0.2
if model_names[model_id] == 'resnet50':
num_epochs = 100
hidden_size1 = 512
learning_rate = 0.0005
gamma = 0.1
models.append(ClassifierNetwork(input_size, hidden_size1, nway).to(device))
# Loss and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(models[model_id].parameters(), lr=learning_rate)
train_model(models[model_id], features_support_list[model_id], labels_support,
criterion, optimizer, num_epochs, gamma)
accuracy_test = test_model(models, features_query_list, labels_query)
print(round(accuracy_test, 2))
accs.append(accuracy_test)
stds = np.std(accs)
acc_avg = round(np.mean(accs), 2)
ci95 = round(1.96 * stds / np.sqrt(n_problems), 2)
# write the results to a file:
if args.val_on_birds:
if args.model_choice == 'All':
fp = open('All_val_on_birds_'+str(nway) + 'way_' + str(kshot) + 'shot_results.txt', 'a')
else:
fp = open('Single_val_on_birds_'+str(nway) + 'way_' + str(kshot) + 'shot_results.txt', 'a')
else:
if args.model_choice == 'All':
fp = open('All_test_'+str(nway) + 'way_' + str(kshot) + 'shot_'+'val_on_birds_5shot_results.txt', 'a')
else:
fp = open('Single_test_'+str(nway) + 'way_' + str(kshot) + 'shot_'+'val_on_birds_5shot_results.txt', 'a')
if args.soft:
result = 'Setting: Soft ensemble-' + 'num_epochs_' + str(num_epochs) + '-hidden_size1_' \
+ str(hidden_size1) + '-learning_rate_' + str(learning_rate) + '-reg_gamma_' \
+ str(gamma) + '-' + data + '- ' + ', '.join(map(str, model_names))
else:
result = 'Setting: Hard ensemble-' + 'num_epochs_' + str(num_epochs) + '-hidden_size1_' \
+ str(hidden_size1) + '-learning_rate_' + str(learning_rate) + '-reg_gamma_' \
+ str(gamma) + '-' + data + '- ' + ', '.join(map(str, model_names))
if args.linear:
result += ' linear'
if args.nol2:
result += ' No L2'
result += '-' + str(nway) + ' way-' + str(kshot) + ' shot'
result += ';- Accuracy: ' + str(acc_avg)
result += ', ' + str(ci95) + '\n'
fp.write(result)
fp.close()
print("Accuracy:", acc_avg)
print("CI95:", ci95)
if __name__=='__main__':
main()