Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

test.py 11 KB

You have to be logged in to leave a comment. Sign In
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
  1. import torch
  2. import numpy as np
  3. from torch.autograd import Variable
  4. import torch.nn as nn
  5. import torch.optim
  6. import json
  7. import torch.utils.data.sampler
  8. import os
  9. import glob
  10. import random
  11. import time
  12. import config.configs as configs
  13. import models.backbone as backbone
  14. import data.feature_loader as feat_loader
  15. # from data.datamgr import SetDataManager
  16. # from methods.baselinetrain import BaselineTrain
  17. # from methods.baselinefinetune import BaselineFinetune
  18. # from methods.protonet import ProtoNet
  19. # from methods.matchingnet import MatchingNet
  20. # from methods.relationnet import RelationNet
  21. # from methods.maml import MAML
  22. from utils.io_utils import model_dict, parse_args, get_resume_file, get_best_file , get_assigned_file
  23. def feature_evaluation(cl_data_file, model, n_way = 5, n_support = 5, n_query = 15, adaptation = False, semi_inputs=None):
  24. class_list = cl_data_file.keys()
  25. select_class = random.sample(class_list,n_way)
  26. z_all = []
  27. for cl in select_class:
  28. img_feat = cl_data_file[cl]
  29. perm_ids = np.random.permutation(len(img_feat)).tolist()
  30. # print(len(img_feat),n_support+n_query)
  31. z_all.append( [ np.squeeze( img_feat[perm_ids[i]]) for i in range(n_support+n_query) ] ) # stack each batch
  32. z_all = torch.from_numpy(np.array(z_all) )
  33. model.n_query = n_query
  34. if adaptation:
  35. scores = model.set_forward_adaptation(z_all, is_feature = True, semi_inputs=semi_inputs)
  36. else:
  37. scores = model.set_forward_test(z_all, is_feature = True, semi_inputs=semi_inputs)
  38. pred = scores.data.cpu().numpy().argmax(axis = 1)
  39. y = np.repeat(range( n_way ), n_query )
  40. acc = np.mean(pred == y)*100
  41. return acc
  42. def feature_evaluation_depth(cl_data_file, model, n_way = 5, n_support = 5, n_query = 15, adaptation = False):
  43. class_list = cl_data_file.keys()
  44. select_class = random.sample(class_list,n_way)
  45. z_all = []
  46. # import ipdb; ipdb.set_trace()
  47. for cl in select_class:
  48. img_feat = cl_data_file[cl]
  49. perm_ids = np.random.permutation(len(img_feat)).tolist()
  50. # print(len(img_feat),n_support+n_query)
  51. z_all.append( [ np.squeeze( np.concatenate((img_feat[perm_ids[i]][0],img_feat[perm_ids[i]][1])) ) for i in range(n_support+n_query) ] ) # stack each batch
  52. z_all = torch.from_numpy(np.array(z_all) )
  53. model.n_query = n_query
  54. if adaptation:
  55. ## not implemented yet
  56. scores = model.set_forward_adaptation(z_all, is_feature = True)
  57. else:
  58. scores = model.set_forward_depth(z_all, is_feature = True)
  59. pred = scores.data.cpu().numpy().argmax(axis = 1)
  60. y = np.repeat(range( n_way ), n_query )
  61. acc = np.mean(pred == y)*100
  62. return acc
  63. if __name__ == '__main__':
  64. params = parse_args('test')
  65. isAircraft = (params.dataset == 'aircrafts')
  66. acc_all = []
  67. iter_num = 600
  68. few_shot_params = dict(n_way = params.test_n_way , n_support = params.n_shot)
  69. if params.dataset in ['omniglot', 'cross_char']:
  70. assert params.model == 'Conv4' and not params.train_aug ,'omniglot only support Conv4 without augmentation'
  71. params.model = 'Conv4S'
  72. if params.method == 'baseline':
  73. model = BaselineFinetune( model_dict[params.model], **few_shot_params )
  74. elif params.method == 'baseline++':
  75. model = BaselineFinetune( model_dict[params.model], loss_type = 'dist', **few_shot_params )
  76. elif params.method == 'protonet':
  77. model = ProtoNet( model_dict[params.model], **few_shot_params )
  78. elif params.method == 'matchingnet':
  79. model = MatchingNet( model_dict[params.model], **few_shot_params )
  80. elif params.method in ['relationnet', 'relationnet_softmax']:
  81. if params.model == 'Conv4':
  82. feature_model = backbone.Conv4NP
  83. elif params.model == 'Conv6':
  84. feature_model = backbone.Conv6NP
  85. elif params.model == 'Conv4S':
  86. feature_model = backbone.Conv4SNP
  87. else:
  88. feature_model = lambda: model_dict[params.model]( flatten = False )
  89. loss_type = 'mse' if params.method == 'relationnet' else 'softmax'
  90. model = RelationNet( feature_model, loss_type = loss_type , **few_shot_params )
  91. elif params.method in ['maml' , 'maml_approx']:
  92. backbone.ConvBlock.maml = True
  93. backbone.SimpleBlock.maml = True
  94. backbone.BottleneckBlock.maml = True
  95. backbone.ResNet.maml = True
  96. model = MAML( model_dict[params.model], approx = (params.method == 'maml_approx') , **few_shot_params )
  97. if params.dataset in ['omniglot', 'cross_char']: #maml use different parameter in omniglot
  98. model.n_task = 32
  99. model.task_update_num = 1
  100. model.train_lr = 0.1
  101. else:
  102. raise ValueError('Unknown method')
  103. model = model.cuda()
  104. model.feature = model.feature.cuda()
  105. if params.json_seed is not None:
  106. checkpoint_dir = '%s/checkpoints/%s_%s/%s_%s_%s' %(configs.save_dir, params.dataset, params.json_seed, params.date, params.model, params.method)
  107. else:
  108. checkpoint_dir = '%s/checkpoints/%s/%s_%s_%s' %(configs.save_dir, params.dataset, params.date, params.model, params.method)
  109. if params.train_aug:
  110. checkpoint_dir += '_aug'
  111. if not params.method in ['baseline', 'baseline++'] :
  112. checkpoint_dir += '_%dway_%dshot_%dquery' %( params.train_n_way, params.n_shot, params.n_query)
  113. checkpoint_dir += '_%d'%params.image_size
  114. ## Use another dataset (dataloader) for unlabeled data
  115. if params.dataset_unlabel is not None:
  116. checkpoint_dir += params.dataset_unlabel
  117. checkpoint_dir += str(params.bs)
  118. ## Use grey image
  119. if params.grey:
  120. checkpoint_dir += '_grey'
  121. ## Add jigsaw
  122. if params.jigsaw:
  123. checkpoint_dir += '_jigsawonly_alldata_lbda%.2f'%(params.lbda)
  124. checkpoint_dir += params.optimization
  125. ## Add rotation
  126. if params.rotation:
  127. checkpoint_dir += '_rotation_lbda%.2f'%(params.lbda)
  128. checkpoint_dir += params.optimization
  129. checkpoint_dir += '_lr%.4f'%(params.lr)
  130. if params.finetune:
  131. checkpoint_dir += '_finetune'
  132. if params.random:
  133. checkpoint_dir = 'checkpoints/CUB/random'
  134. #modelfile = get_resume_file(checkpoint_dir)
  135. if params.loadfile != '':
  136. # modelfile = params.loadfile
  137. checkpoint_dir = params.loadfile
  138. else:
  139. if not params.method in ['baseline', 'baseline++'] :
  140. if params.save_iter != -1:
  141. modelfile = get_assigned_file(checkpoint_dir,params.save_iter)
  142. else:
  143. modelfile = get_best_file(checkpoint_dir)
  144. # if modelfile is not None:
  145. # tmp = torch.load(modelfile)
  146. # model.load_state_dict(tmp['state'], strict=False)
  147. # if not params.method in ['baseline', 'baseline++'] :
  148. if params.method in ['maml', 'maml_approx']:
  149. if modelfile is not None:
  150. tmp = torch.load(modelfile)
  151. state = tmp['state']
  152. state_keys = list(state.keys())
  153. for i, key in enumerate(state_keys):
  154. if "feature." in key:
  155. newkey = key.replace("feature.","") # an architecture model has attribute 'feature', load architecture feature to backbone by casting name from 'feature.trunk.xx' to 'trunk.xx'
  156. state[newkey] = state.pop(key)
  157. else:
  158. state.pop(key)
  159. # model.load_state_dict(tmp['state'], strict=False)
  160. # import ipdb; ipdb.set_trace()
  161. # model.feature.load_state_dict(tmp['state'])
  162. model.feature.load_state_dict(tmp['state'], strict=False)##added 0912
  163. print('modelfile:',modelfile)
  164. split = params.split
  165. if params.save_iter != -1:
  166. split_str = split + "_" +str(params.save_iter)
  167. else:
  168. split_str = split
  169. if params.method in ['maml', 'maml_approx']: #maml do not support testing with feature
  170. if 'Conv' in params.model:
  171. if params.dataset in ['omniglot', 'cross_char']:
  172. image_size = 28
  173. else:
  174. image_size = 84
  175. else:
  176. image_size = 224
  177. datamgr = SetDataManager(image_size, n_eposide = iter_num, n_query = 15 , **few_shot_params, isAircraft=isAircraft, grey=params.grey)
  178. if params.dataset == 'cross':
  179. if split == 'base':
  180. loadfile = configs.data_dir['miniImagenet'] + 'all.json'
  181. else:
  182. loadfile = configs.data_dir['CUB'] + split +'.json'
  183. elif params.dataset == 'cross_char':
  184. if split == 'base':
  185. loadfile = configs.data_dir['omniglot'] + 'noLatin.json'
  186. else:
  187. loadfile = configs.data_dir['emnist'] + split +'.json'
  188. else:
  189. if params.json_seed is not None:
  190. loadfile = configs.data_dir[params.dataset] + split + params.json_seed + '.json'
  191. else:
  192. if '_' in params.dataset:
  193. loadfile = configs.data_dir[params.dataset.split('_')[0]] + split + '.json'
  194. else:
  195. loadfile = configs.data_dir[params.dataset] + split + '.json'
  196. novel_loader = datamgr.get_data_loader( loadfile, aug = False)
  197. if params.adaptation:
  198. model.task_update_num = 100 #We perform adaptation on MAML simply by updating more times.
  199. model.eval()
  200. acc_mean, acc_std = model.test_loop( novel_loader, return_std = True)
  201. else:
  202. novel_file = os.path.join( checkpoint_dir.replace("checkpoints","features"), split_str +".hdf5") #defaut split = novel, but you can also test base or val classes
  203. print('novel_file',novel_file)
  204. cl_data_file = feat_loader.init_loader(novel_file)
  205. for i in range(iter_num):
  206. # import ipdb; ipdb.set_trace()
  207. # acc = feature_evaluation(cl_data_file, model, n_query = 15, adaptation = params.adaptation, **few_shot_params)
  208. acc = feature_evaluation(cl_data_file, model, n_query = params.n_query, adaptation = params.adaptation, **few_shot_params)
  209. acc_all.append(acc)
  210. acc_all = np.asarray(acc_all)
  211. acc_mean = np.mean(acc_all)
  212. acc_std = np.std(acc_all)
  213. print('%d Test Acc = %4.2f%% +- %4.2f%%' %(iter_num, acc_mean, 1.96* acc_std/np.sqrt(iter_num)))
  214. #with open('./record/results.txt' , 'a') as f:
  215. if params.method in ['maml', 'maml_approx']:
  216. if not os.path.isdir(checkpoint_dir.replace("checkpoints","features")):
  217. os.mkdir(checkpoint_dir.replace("checkpoints","features"))
  218. with open(os.path.join( checkpoint_dir.replace("checkpoints","features"), split_str +"_test.txt") , 'a') as f:
  219. timestamp = time.strftime("%Y%m%d-%H%M%S", time.localtime())
  220. aug_str = '-aug' if params.train_aug else ''
  221. aug_str += '-adapted' if params.adaptation else ''
  222. if params.method in ['baseline', 'baseline++'] :
  223. exp_setting = '%s-%s-%s-%s%s %sshot %sway_test' %(params.dataset, split_str, params.model, params.method, aug_str, params.n_shot, params.test_n_way )
  224. else:
  225. exp_setting = '%s-%s-%s-%s%s %sshot %sway_train %sway_test' %(params.dataset, split_str, params.model, params.method, aug_str , params.n_shot , params.train_n_way, params.test_n_way )
  226. acc_str = '%d Test Acc = %4.2f%% +- %4.2f%%' %(iter_num, acc_mean, 1.96* acc_std/np.sqrt(iter_num))
  227. f.write( 'Time: %s, Setting: %s, Acc: %s \n' %(timestamp,exp_setting,acc_str) )
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...