forked from rmunro/pytorch_active_learning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadvanced_active_learning.py
469 lines (327 loc) · 18.8 KB
/
advanced_active_learning.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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
#!/usr/bin/env python
"""Diversity Sampling
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import random
import math
import datetime
import csv
import re
import os
import getopt, sys
import copy
from random import shuffle
from collections import defaultdict
from diversity_sampling import DiversitySampling
from uncertainty_sampling import UncertaintySampling
from pytorch_clusters import CosineClusters
from pytorch_clusters import Cluster
if sys.argv[0] == "advanced_active_learning.py":
import active_learning
__author__ = "Robert Munro"
__license__ = "MIT"
__version__ = "1.0.1"
class AdvancedActiveLearning():
def __init__(self, verbose=False):
self.verbose = verbose
self.uncertainty_sampling = UncertaintySampling(self.verbose)
self.diversity_sampling = DiversitySampling(self.verbose)
def get_clustered_uncertainty_samples(self, model, unlabeled_data, method, feature_method,
perc_uncertain = 0.1, num_clusters=20, max_epochs=10, limit=10000):
"""Gets the most uncertain items and then clusters the, sampling from each cluster
Keyword arguments:
model -- machine learning model to get predictions from to determine uncertainty
unlabeled_data -- data that does not yet have a label
method -- method for uncertainty sampling (eg: least_confidence())
feature_method -- the method for extracting features from your data
perc_uncertain -- percentage of items through uncertainty sampling to cluster
num_clusters -- the number of clusters to create
max_epochs -- maximum number of epochs to create clusters
limit -- sample from only this many predictions for faster sampling (-1 = no limit)
"""
if limit > 0:
shuffle(unlabeled_data)
unlabeled_data = unlabeled_data[:limit]
uncertain_count = math.ceil(len(unlabeled_data) * perc_uncertain)
uncertain_samples = self.uncertainty_sampling.get_samples(model, unlabeled_data, method,
feature_method, uncertain_count, limit=limit)
samples = self.diversity_sampling.get_cluster_samples(uncertain_samples,
num_clusters=num_clusters)
for item in samples:
item[3] = method.__name__+"_"+item[3]
return samples
def get_uncertain_model_outlier_samples(self, model, outlier_model, unlabeled_data, validation_data, method, feature_method,
perc_uncertain = 0.1, number=10, limit=10000):
"""Gets the most uncertain items and samples the biggest model outliers among them
Keyword arguments:
model -- machine learning model to get predictions from to determine uncertainty
outlier_model -- machine learning model for outlier prediction
validation_data -- data not used for the outlier_model but from the same distribution
unlabeled_data -- data that does not yet have a label
method -- method for uncertainty sampling (eg: least_confidence())
feature_method -- the method for extracting features from your data
perc_uncertain -- percentage of items through uncertainty sampling to cluster
number -- the final number of items to sample
limit -- sample from only this many predictions for faster sampling (-1 = no limit)
"""
if limit > 0:
shuffle(unlabeled_data)
unlabeled_data = unlabeled_data[:limit]
uncertain_count = math.ceil(len(unlabeled_data) * perc_uncertain)
uncertain_samples = self.uncertainty_sampling.get_samples(model, unlabeled_data, method,
feature_method, uncertain_count, limit=limit)
samples = self.diversity_sampling.get_model_outliers(outlier_model, uncertain_samples, validation_data,
feature_method, number=number, limit=limit)
for item in samples:
item[3] = method.__name__+"_"+item[3]
return samples
def get_representative_cluster_samples(self, training_data, unlabeled_data, number=10, num_clusters=20, max_epochs=10, limit=10000):
"""Gets the most representative unlabeled items, compared to training data, across multiple clusters
Keyword arguments:
training_data -- data with a label, that the current model is trained on
unlabeled_data -- data that does not yet have a label
number -- number of items to sample
limit -- sample from only this many items for faster sampling (-1 = no limit)
num_clusters -- the number of clusters to create
max_epochs -- maximum number of epochs to create clusters
"""
if limit > 0:
shuffle(training_data)
training_data = training_data[:limit]
shuffle(unlabeled_data)
unlabeled_data = unlabeled_data[:limit]
# Create clusters for training data
training_clusters = CosineClusters(num_clusters)
training_clusters.add_random_training_items(training_data)
for i in range(0, max_epochs):
print("Epoch "+str(i))
added = training_clusters.add_items_to_best_cluster(training_data)
if added == 0:
break
# Create clusters for unlabeled data
unlabeled_clusters = CosineClusters(num_clusters)
unlabeled_clusters.add_random_training_items(unlabeled_data)
for i in range(0, max_epochs):
print("Epoch "+str(i))
added = unlabeled_clusters.add_items_to_best_cluster(unlabeled_data)
if added == 0:
break
# get scores
most_representative_items = []
# for each cluster of unlabeled data
for cluster in unlabeled_clusters.clusters:
most_representative = None
representativeness = float("-inf")
# find the item in that cluster most like the unlabeled data
item_keys = list(cluster.members.keys())
for key in item_keys:
item = cluster.members[key]
_r, unlabeled_score = unlabeled_clusters.get_best_cluster(item)
_, training_score = training_clusters.get_best_cluster(item)
cluster_representativeness = unlabeled_score - training_score
if cluster_representativeness > representativeness:
representativeness = cluster_representativeness
most_representative = item
most_representative[3] = "representative_clusters"
most_representative[4] = representativeness
most_representative_items.append(most_representative)
most_representative_items.sort(reverse=True, key=lambda x: x[4])
return most_representative_items[:number:]
def get_high_uncertainty_cluster(self, model, unlabeled_data, method, feature_method,
number=10, num_clusters=20, max_epochs=10, limit=10000):
"""Gets items from the cluster with the highest average uncertainty
Keyword arguments:
model -- machine learning model to get predictions from to determine uncertainty
unlabeled_data -- data that does not yet have a label
method -- method for uncertainty sampling (eg: least_confidence())
feature_method -- the method for extracting features from your data
number -- number of items to sample
num_clusters -- the number of clusters to create
max_epochs -- maximum number of epochs to create clusters
limit -- sample from only this many items for faster sampling (-1 = no limit)
"""
if limit > 0:
shuffle(unlabeled_data)
unlabeled_data = unlabeled_data[:limit]
unlabeled_clusters = CosineClusters(num_clusters)
unlabeled_clusters.add_random_training_items(unlabeled_data)
for i in range(0, max_epochs):
print("Epoch "+str(i))
added = unlabeled_clusters.add_items_to_best_cluster(unlabeled_data)
if added == 0:
break
# get scores
most_uncertain_cluster = None
highest_average_uncertainty = 0.0
# for each cluster of unlabeled data
for cluster in unlabeled_clusters.clusters:
total_uncertainty = 0.0
count = 0
item_keys = list(cluster.members.keys())
for key in item_keys:
item = cluster.members[key]
text = item[1]
feature_vector = feature_method(text)
hidden, logits, log_probs = model(feature_vector, return_all_layers=True)
prob_dist = torch.exp(log_probs) # the probability distribution of our prediction
score = method(prob_dist.data[0]) # get the specific type of uncertainty sampling
total_uncertainty += score
count += 1
average_uncertainty = total_uncertainty / count
if average_uncertainty > highest_average_uncertainty:
highest_average_uncertainty = average_uncertainty
most_uncertain_cluster = cluster
samples = most_uncertain_cluster.get_random_members(number)
return samples
def get_deep_active_transfer_learning_uncertainty_samples(self, model, unlabeled_data, validation_data, feature_method,
number=100, limit=10000, epochs=10, select_per_epoch=100):
"""Uses transfer learning to predict uncertainty within the model
Keyword arguments:
model -- machine learning model to get predictions from to determine uncertainty
unlabeled_data -- data that does not yet have a label
validation_data -- data with a label that is not in the training set, to be used for transfer learning
feature_method -- the method for extracting features from your data
number -- number of items to sample
epochs -- number of epochs to train transfer-learning model
select_per_epoch -- number of items to train on per epoch of training
limit -- sample from only this many items for faster sampling (-1 = no limit)
"""
correct_predictions = [] # validation items predicted correctly
incorrect_predictions = [] # validation items predicted incorrectly
item_hidden_layers = {} # hidden layer of each item, by id
# 1 GET PREDICTIONS ON VALIDATION DATA FROM MODEL
for item in validation_data:
id = item[0]
text = item[1]
label = item[2]
feature_vector = feature_method(text)
hidden, logits, log_probs = model(feature_vector, return_all_layers=True)
item_hidden_layers[id] = hidden
# get confidence that item is disaster-related
prob_related = math.exp(log_probs.data.tolist()[0][1])
if item[3] == "seen":
correct_predictions.append(item)
elif (label == "1" and prob_related > 0.5) or (label == "0" and prob_related <= 0.5):
correct_predictions.append(item)
else:
incorrect_predictions.append(item)
# item.append(hidden) # the hidden layer will be the input to our new model
# 2 BUILD A NEW MODEL TO PREDICT WHETHER VALIDATION ITEMS WERE CORRECT OR INCORRECT
correct_model = SimpleUncertaintyPredictor(128)
loss_function = nn.NLLLoss()
optimizer = optim.SGD(correct_model.parameters(), lr=0.01)
# print(correct_predictions)
for epoch in range(epochs):
if self.verbose:
print("Epoch: "+str(epoch))
current = 0
# make a subset of data to use in this epoch
# with an equal number of items from each label
shuffle(correct_predictions) #randomize the order of the validation data
shuffle(incorrect_predictions) #randomize the order of the validation data
correct_ids = {}
for item in correct_predictions:
correct_ids[item[0]] = True
epoch_data = correct_predictions[:select_per_epoch]
epoch_data += incorrect_predictions[:select_per_epoch]
shuffle(epoch_data)
# train the final layers model
for item in epoch_data:
id = item[0]
label = 0
if id in correct_ids:
label = 1
correct_model.zero_grad()
# print(item)
feature_vec = item_hidden_layers[id]
target = torch.LongTensor([label])
log_probs = correct_model(feature_vec)
# compute loss function, do backward pass, and update the gradient
loss = loss_function(log_probs, target)
loss.backward(retain_graph=True)
optimizer.step()
# 3 PREDICT WHETHER UNLABELED ITEMS ARE CORRECT
if limit > 0:
shuffle(unlabeled_data)
unlabeled_data = unlabeled_data[:limit]
deep_active_transfer_preds = []
with torch.no_grad():
v=0
for item in unlabeled_data:
text = item[1]
# get prediction from main model
feature_vector = feature_method(text)
hidden, logits, log_probs = model(feature_vector, return_all_layers=True)
# use hidden layer from main model as input to model predicting correct/errors
logits, log_probs = correct_model(hidden, return_all_layers=True)
# get confidence that item is correctly labeled
prob_correct = 1 - math.exp(log_probs.data.tolist()[0][1])
if(label == "0"):
prob_correct = 1 - prob_correct
item[3] = "predicted_error"
item[4] = 1 - prob_correct
deep_active_transfer_preds.append(item)
deep_active_transfer_preds.sort(reverse=True, key=lambda x: x[4])
return deep_active_transfer_preds[:number:]
def get_atlas_samples(self, model, unlabeled_data, validation_data, feature_method,
number=100, limit=10000, number_per_iteration=10, epochs=10, select_per_epoch=100):
"""Uses transfer learning to predict uncertainty within the model
Keyword arguments:
model -- machine learning model to get predictions from to determine uncertainty
unlabeled_data -- data that does not yet have a label
validation_data -- data with a label that is not in the training set, to be used for transfer learning
feature_method -- the method for extracting features from your data
number -- number of items to sample
number_per_iteration -- number of items to sample per iteration
limit -- sample from only this many items for faster sampling (-1 = no limit)
"""
if(len(unlabeled_data) < number):
raise Exception('More samples requested than the number of unlabeled items')
atlas_samples = [] # all items sampled by atlas
print(number)
while(len(atlas_samples) < number):
samples = self.get_deep_active_transfer_learning_uncertainty_samples(model, unlabeled_data, validation_data,
feature_method, number_per_iteration, limit, epochs, select_per_epoch)
for item in samples:
atlas_samples.append(item)
unlabeled_data.remove(item)
item = copy.deepcopy(item)
item[3] = "seen" # mark this item as already seen
validation_data.append(item) # append so that it is in the next iteration
print("DONE!")
return atlas_samples
class SimpleUncertaintyPredictor(nn.Module): # inherit pytorch's nn.Module
"""Simple model to predict whether an item will be classified correctly
"""
def __init__(self, vocab_size):
super(SimpleUncertaintyPredictor, self).__init__() # call parent init
# Define single layer model predicting 2 classes
self.linear = nn.Linear(vocab_size, 2)
def forward(self, feature_vec, return_all_layers=False):
# Define how data is passed through the model and what gets returned
output = self.linear(feature_vec).clamp(min=-1) # ReLU
log_softmax = F.log_softmax(output, dim=1)
if return_all_layers:
return [output, log_softmax]
else:
return log_softmax
class AdvancedUncertaintyPredictor(nn.Module): # inherit pytorch's nn.Module
"""Simple model to predict whether an item will be classified correctly
"""
def __init__(self, vocab_size):
super(AdvancedUncertaintyPredictor, self).__init__() # call parent init
# Define model with one hidden layer with 128 neurons
self.linear1 = nn.Linear(vocab_size, 128)
self.linear2 = nn.Linear(128, num_labels)
def forward(self, feature_vec, return_all_layers=False):
# Define how data is passed through the model and what gets returned
hidden1 = self.linear1(feature_vec).clamp(min=0) # ReLU
output = self.linear2(hidden1)
log_softmax = F.log_softmax(output, dim=1)
if return_all_layers:
return [hidden1, output, log_softmax]
else:
return log_softmax