-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathSampling.py
363 lines (321 loc) · 16 KB
/
Sampling.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
import numpy as np
from sklearn.mixture import GaussianMixture
import torch
import torch.nn as nn
import torch.nn.functional as F
from better_vae import kl_divergence
def random_sampling(args, unlabeledloader, Len_labeled_ind_train, model, use_gpu):
model.eval()
queryIndex = []
labelArr = []
precision, recall = 0, 0
for batch_idx, (index, (_, labels)) in enumerate(unlabeledloader):
queryIndex += index
labelArr += list(np.array(labels.data))
tmp_data = np.vstack((queryIndex, labelArr)).T
np.random.shuffle(tmp_data)
tmp_data = tmp_data.T
queryIndex = tmp_data[0][:args.query_batch]
labelArr = tmp_data[1]
queryLabelArr = tmp_data[1][:args.query_batch]
precision = len(np.where(queryLabelArr < args.known_class)[0]) / len(queryLabelArr)
recall = (len(np.where(queryLabelArr < args.known_class)[0]) + Len_labeled_ind_train) / (len(np.where(labelArr < args.known_class)[0]) + Len_labeled_ind_train)
return queryIndex[np.where(queryLabelArr < args.known_class)[0]], queryIndex[np.where(queryLabelArr >= args.known_class)[0]], precision, recall
def uncertainty_sampling(args, unlabeledloader, Len_labeled_ind_train, model, use_gpu):
model.eval()
queryIndex = []
labelArr = []
uncertaintyArr = []
precision, recall = 0, 0
for batch_idx, (index, (data, labels)) in enumerate(unlabeledloader):
if use_gpu:
data, labels = data.cuda(), labels.cuda()
features, outputs = model(data)
uncertaintyArr += list(np.array((-torch.softmax(outputs,1)*torch.log(torch.softmax(outputs,1))).sum(1).cpu().data))
queryIndex += index
labelArr += list(np.array(labels.cpu().data))
tmp_data = np.vstack((uncertaintyArr, queryIndex, labelArr)).T
tmp_data = tmp_data[np.argsort(tmp_data[:,0])]
tmp_data = tmp_data.T
queryIndex = tmp_data[1][-args.query_batch:].astype(int)
labelArr = tmp_data[2].astype(int)
queryLabelArr = tmp_data[2][-args.query_batch:]
precision = len(np.where(queryLabelArr < args.known_class)[0]) / len(queryLabelArr)
recall = (len(np.where(queryLabelArr < args.known_class)[0]) + Len_labeled_ind_train) / (
len(np.where(labelArr < args.known_class)[0]) + Len_labeled_ind_train)
return queryIndex[np.where(queryLabelArr < args.known_class)[0]], queryIndex[np.where(queryLabelArr >= args.known_class)[0]], precision, recall
def Max_AV_sampling(args, unlabeledloader, Len_labeled_ind_train, model, use_gpu):
model.eval()
queryIndex = []
labelArr = []
uncertaintyArr = []
All_Arr = []
for batch_idx, (index, (data, labels)) in enumerate(unlabeledloader):
if use_gpu:
data, labels = data.cuda(), labels.cuda()
_, outputs = model(data)
queryIndex += index
labelArr += list(np.array(labels.cpu().data))
# activation value based
v_ij, predicted = outputs.max(1)
for i in range(len(predicted.data)):
tmp_class = np.array(predicted.data.cpu())[i]
tmp_index = index[i]
tmp_label = np.array(labels.data.cpu())[i]
tmp_value = np.array(v_ij.data.cpu())[i]
All_Arr.append([tmp_value, tmp_index, tmp_label])
tmp_data = np.array(All_Arr)
tmp_data = tmp_data[np.argsort(tmp_data[:, 0])]
tmp_data = tmp_data.T
queryIndex = tmp_data[1][-args.query_batch:].astype(int)
labelArr = tmp_data[2].astype(int)
queryLabelArr = tmp_data[2][-args.query_batch:]
precision = len(np.where(queryLabelArr < args.known_class)[0]) / len(queryLabelArr)
recall = (len(np.where(queryLabelArr < args.known_class)[0]) + Len_labeled_ind_train) / (
len(np.where(labelArr < args.known_class)[0]) + Len_labeled_ind_train)
return queryIndex[np.where(queryLabelArr < args.known_class)[0]], queryIndex[np.where(queryLabelArr >= args.known_class)[0]], precision, recall
def AV_sampling(args, unlabeledloader, Len_labeled_ind_train, model, use_gpu):
model.eval()
queryIndex = []
labelArr = []
uncertaintyArr = []
S_ij = {}
for batch_idx, (index, (data, labels)) in enumerate(unlabeledloader):
if use_gpu:
data, labels = data.cuda(), labels.cuda()
_, outputs = model(data)
queryIndex += index
labelArr += list(np.array(labels.cpu().data))
# activation value based
v_ij, predicted = outputs.max(1)
for i in range(len(predicted.data)):
tmp_class = np.array(predicted.data.cpu())[i]
tmp_index = index[i]
tmp_label = np.array(labels.data.cpu())[i]
tmp_value = np.array(v_ij.data.cpu())[i]
if tmp_class not in S_ij:
S_ij[tmp_class] = []
S_ij[tmp_class].append([tmp_value, tmp_index, tmp_label])
# fit a two-component GMM for each class
tmp_data = []
for tmp_class in S_ij:
S_ij[tmp_class] = np.array(S_ij[tmp_class])
activation_value = S_ij[tmp_class][:, 0]
if len(activation_value) < 2:
continue
gmm = GaussianMixture(n_components=2, max_iter=10, tol=1e-2, reg_covar=5e-4)
gmm.fit(np.array(activation_value).reshape(-1, 1))
prob = gmm.predict_proba(np.array(activation_value).reshape(-1, 1))
# 得到为known类别的概率
prob = prob[:, gmm.means_.argmax()]
if len(tmp_data) == 0:
tmp_data = np.hstack((prob.reshape(-1, 1), S_ij[tmp_class]))
else:
tmp_data = np.vstack((tmp_data, np.hstack((prob.reshape(-1, 1), S_ij[tmp_class]))))
tmp_data = tmp_data[np.argsort(tmp_data[:, 0])]
tmp_data = tmp_data.T
queryIndex = tmp_data[2][-args.query_batch:].astype(int)
labelArr = tmp_data[3].astype(int)
queryLabelArr = tmp_data[3][-args.query_batch:]
precision = len(np.where(queryLabelArr < args.known_class)[0]) / len(queryLabelArr)
recall = (len(np.where(queryLabelArr < args.known_class)[0]) + Len_labeled_ind_train) / (
len(np.where(labelArr < args.known_class)[0]) + Len_labeled_ind_train)
return queryIndex[np.where(queryLabelArr < args.known_class)[0]], queryIndex[np.where(queryLabelArr >= args.known_class)[0]], precision, recall
def AV_uncertainty_sampling(args, unlabeledloader, Len_labeled_ind_train, model, use_gpu):
model.eval()
queryIndex = []
labelArr = []
uncertaintyArr = []
S_ij = {}
for batch_idx, (index, (data, labels)) in enumerate(unlabeledloader):
if use_gpu:
data, labels = data.cuda(), labels.cuda()
_, outputs = model(data)
queryIndex += index
labelArr += list(np.array(labels.cpu().data))
# activation value based
v_ij, predicted = outputs.max(1)
uncertainty = -(F.softmax(outputs) * F.log_softmax(outputs)).sum(1)
for i in range(len(predicted.data)):
tmp_class = np.array(predicted.data.cpu())[i]
tmp_index = index[i]
tmp_label = np.array(labels.data.cpu())[i]
tmp_uncertainty = np.array(uncertainty.data.cpu())[i]
tmp_value = np.array(v_ij.data.cpu())[i]*tmp_uncertainty
if tmp_class not in S_ij:
S_ij[tmp_class] = []
S_ij[tmp_class].append([tmp_value, tmp_index, tmp_label])
# fit a two-component GMM for each class
tmp_data = []
for tmp_class in S_ij:
S_ij[tmp_class] = np.array(S_ij[tmp_class])
activation_value = S_ij[tmp_class][:, 0]
gmm = GaussianMixture(n_components=2, max_iter=10, tol=1e-2, reg_covar=5e-4)
gmm.fit(np.array(activation_value).reshape(-1, 1))
prob = gmm.predict_proba(np.array(activation_value).reshape(-1, 1))
# 得到为known类别的概率
prob = prob[:, gmm.means_.argmax()]
if len(tmp_data) == 0:
tmp_data = np.hstack((prob.reshape(-1, 1), S_ij[tmp_class]))
else:
tmp_data = np.vstack((tmp_data, np.hstack((prob.reshape(-1, 1), S_ij[tmp_class]))))
tmp_data = tmp_data[np.argsort(tmp_data[:, 0])]
tmp_data = tmp_data.T
queryIndex = tmp_data[2][-args.query_batch:].astype(int)
labelArr = tmp_data[3].astype(int)
queryLabelArr = tmp_data[3][-args.query_batch:]
precision = len(np.where(queryLabelArr < args.known_class)[0]) / len(queryLabelArr)
recall = (len(np.where(queryLabelArr < args.known_class)[0]) + Len_labeled_ind_train) / (
len(np.where(labelArr < args.known_class)[0]) + Len_labeled_ind_train)
return queryIndex[np.where(queryLabelArr < args.known_class)[0]], queryIndex[np.where(queryLabelArr >= args.known_class)[0]], precision, recall
def AV_sampling2(args, labeledloader, unlabeledloader, Len_labeled_ind_train, model, use_gpu):
model.eval()
queryIndex = []
labelArr = []
uncertaintyArr = []
S_ij = {}
S_ij_unlabeled = {}
for batch_idx, (index, (data, labels)) in enumerate(labeledloader):
if use_gpu:
data, labels = data.cuda(), labels.cuda()
_, outputs = model(data)
# activation value based
v_ij, predicted = outputs.max(1)
for i in range(len(predicted.data)):
tmp_class = np.array(predicted.data.cpu())[i]
tmp_index = index[i]
tmp_label = np.array(labels.data.cpu())[i]
tmp_value = np.array(v_ij.data.cpu())[i]
if tmp_class not in S_ij:
S_ij[tmp_class] = []
S_ij[tmp_class].append([tmp_value, tmp_index, tmp_label])
for batch_idx, (index, (data, labels)) in enumerate(unlabeledloader):
if use_gpu:
data, labels = data.cuda(), labels.cuda()
_, outputs = model(data)
queryIndex += index
labelArr += list(np.array(labels.cpu().data))
# activation value based
v_ij, predicted = outputs.max(1)
for i in range(len(predicted.data)):
tmp_class = np.array(predicted.data.cpu())[i]
tmp_index = index[i]
tmp_label = np.array(labels.data.cpu())[i]
tmp_value = np.array(v_ij.data.cpu())[i]
if tmp_class not in S_ij_unlabeled:
S_ij_unlabeled[tmp_class] = []
S_ij_unlabeled[tmp_class].append([tmp_value, tmp_index, tmp_label])
if batch_idx > 10: break
# fit a one-component GMM for each class
tmp_data = []
for tmp_class in S_ij_unlabeled:
if tmp_class not in S_ij:
continue
S_ij[tmp_class] = np.array(S_ij[tmp_class])
S_ij_unlabeled[tmp_class] = np.array(S_ij_unlabeled[tmp_class])
activation_value = S_ij[tmp_class][:, 0]
# print(tmp_class)
activation_value_unlabeled = S_ij_unlabeled[tmp_class][:, 0]
gmm = GaussianMixture(n_components=1, max_iter=10, tol=1e-2, reg_covar=5e-4)
gmm.fit(np.array(activation_value).reshape(-1, 1))
# 预测unlabeledloader为known类别的概率
prob = gmm.predict_proba(np.array(activation_value_unlabeled).reshape(-1, 1))
if len(tmp_data) == 0:
tmp_data = np.hstack((prob.reshape(-1, 1), S_ij_unlabeled[tmp_class]))
else:
tmp_data = np.vstack((tmp_data, np.hstack((prob.reshape(-1, 1), S_ij_unlabeled[tmp_class]))))
tmp_data = tmp_data[np.argsort(tmp_data[:, 0])]
tmp_data = tmp_data.T
queryIndex = tmp_data[2][-args.query_batch:].astype(int)
labelArr = tmp_data[3].astype(int)
queryLabelArr = tmp_data[3][-args.query_batch:]
precision = len(np.where(queryLabelArr < args.known_class)[0]) / len(queryLabelArr)
recall = (len(np.where(queryLabelArr < args.known_class)[0]) + Len_labeled_ind_train) / (
len(np.where(labelArr < args.known_class)[0]) + Len_labeled_ind_train)
return queryIndex[np.where(queryLabelArr < args.known_class)[0]], queryIndex[np.where(queryLabelArr >= args.known_class)[0]], precision, recall
def VAE_sampling(args, unlabeledloader, Len_labeled_ind_train, model, use_gpu):
model.eval()
queryIndex = []
labelArr = []
uncertaintyArr = []
All_Arr = []
for batch_idx, (index, (data, labels)) in enumerate(unlabeledloader):
if use_gpu:
data, labels = data.cuda(), labels.cuda()
queryIndex += index
labelArr += list(np.array(labels.cpu().data))
dec, _ = model(data.view(-1, 3*32*32))
# define normal distribution
p = torch.distributions.Normal(torch.zeros_like(model.z_mean), torch.ones_like(model.z_sigma))
log_pz = p.log_prob(model.z)
# get prob
pz = np.exp(log_pz.sum(1).detach().cpu())
# print(pz)
# print(pz.shape)
# print(ca)
for i in range(len(labels.data.cpu())):
tmp_index = index[i]
tmp_label = np.array(labels.data.cpu())[i]
tmp_value = np.array(pz)[i]
All_Arr.append([tmp_value, tmp_index, tmp_label])
tmp_data = np.array(All_Arr)
tmp_data = tmp_data[np.argsort(tmp_data[:, 0])]
tmp_data = tmp_data.T
queryIndex = tmp_data[1][-args.query_batch:].astype(int)
labelArr = tmp_data[2].astype(int)
queryLabelArr = tmp_data[2][-args.query_batch:]
precision = len(np.where(queryLabelArr < args.known_class)[0]) / len(queryLabelArr)
recall = (len(np.where(queryLabelArr < args.known_class)[0]) + Len_labeled_ind_train) / (
len(np.where(labelArr < args.known_class)[0]) + Len_labeled_ind_train)
return queryIndex[np.where(queryLabelArr < args.known_class)[0]], queryIndex[np.where(queryLabelArr >= args.known_class)[0]], precision, recall
def AV_sampling_temperature(args, unlabeledloader, Len_labeled_ind_train, model, use_gpu):
model.eval()
queryIndex = []
labelArr = []
uncertaintyArr = []
S_ij = {}
for batch_idx, (index, (data, labels)) in enumerate(unlabeledloader):
if use_gpu:
data, labels = data.cuda(), labels.cuda()
_, outputs = model(data)
queryIndex += index
labelArr += list(np.array(labels.cpu().data))
# activation value based
v_ij, predicted = outputs.max(1)
for i in range(len(predicted.data)):
tmp_class = np.array(predicted.data.cpu())[i]
tmp_index = index[i]
tmp_label = np.array(labels.data.cpu())[i]
tmp_value = np.array(v_ij.data.cpu())[i]
if tmp_class not in S_ij:
S_ij[tmp_class] = []
S_ij[tmp_class].append([tmp_value, tmp_index, tmp_label])
# fit a two-component GMM for each class
tmp_data = []
for tmp_class in S_ij:
S_ij[tmp_class] = np.array(S_ij[tmp_class])
activation_value = S_ij[tmp_class][:, 0]
if len(activation_value) < 2:
continue
gmm = GaussianMixture(n_components=2, max_iter=10, tol=1e-2, reg_covar=5e-4)
gmm.fit(np.array(activation_value).reshape(-1, 1))
prob = gmm.predict_proba(np.array(activation_value).reshape(-1, 1))
# 得到为known类别的概率
prob = prob[:, gmm.means_.argmax()]
# 如果为unknown类别直接为0
if tmp_class == args.known_class:
prob = [0]*len(prob)
prob = np.array(prob)
if len(tmp_data) == 0:
tmp_data = np.hstack((prob.reshape(-1, 1), S_ij[tmp_class]))
else:
tmp_data = np.vstack((tmp_data, np.hstack((prob.reshape(-1, 1), S_ij[tmp_class]))))
tmp_data = tmp_data[np.argsort(tmp_data[:, 0])]
tmp_data = tmp_data.T
queryIndex = tmp_data[2][-args.query_batch:].astype(int)
labelArr = tmp_data[3].astype(int)
queryLabelArr = tmp_data[3][-args.query_batch:]
precision = len(np.where(queryLabelArr < args.known_class)[0]) / len(queryLabelArr)
recall = (len(np.where(queryLabelArr < args.known_class)[0]) + Len_labeled_ind_train) / (
len(np.where(labelArr < args.known_class)[0]) + Len_labeled_ind_train)
return queryIndex[np.where(queryLabelArr < args.known_class)[0]], queryIndex[np.where(queryLabelArr >= args.known_class)[0]], precision, recall