-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlibstop.py
1659 lines (1354 loc) · 51.3 KB
/
libstop.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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Defines active learning stopping criteria.
The standard signature for a criteria is:
```python
def stop(**metrics, **parameters) -> bool:
pass
```
Where `metrics` is a `dict` with the following keys:
* `uncertainty_average` Average of classifier uncertainty on unlabelled pool
* `uncertainty_min` Minimum of classifier uncertainty on unlabelled pool
* `n_support` Number of support vectors
* `expected_error` Expected error on unlabelled pool
* `last_accuracy` Accuracy of the last classifier on the current query set (oracle accuracy)
* `contradictory_information`
* `stop_set` Predictions on the stop set
All values are lists containing all evaluations up to the current classifier. The most recent is in the last element of the list.
---
Fundamentally all stop conditions take a metric and try to determine if the current value is:
* A minimum
* A maximum
* Constant
* At a threshold
The first three require approximation, this is implemented by:
* `__is_approx_constant`
* `__is_approx_minimum`
Which take a threshold and a number of iterations for which the value should be stable.
"""
from collections import namedtuple
import time
import datetime
import itertools
import os
import logging
from abc import ABC, abstractmethod
from dataclasses import dataclass
from functools import partial
import operator
from typing import Callable, Dict, List, Type
import dill
import numpy as np
import pandas as pd
import scipy
from joblib import Parallel, delayed
from scipy.sparse import data
from sklearn.cluster import SpectralClustering
from sklearn import metrics
from sklearn.utils import check_random_state
from sklearn.metrics.pairwise import euclidean_distances, pairwise_kernels
from sklearn.metrics import roc_auc_score, f1_score, cohen_kappa_score
from sklearn.preprocessing import LabelEncoder
from libactive import active_split, delete_from_csr
from tabulate import tabulate
from statsmodels.stats.inter_rater import fleiss_kappa
from autorank import autorank, plot_stats
from tvregdiff.tvregdiff import TVRegDiff
from modAL.uncertainty import classifier_entropy, classifier_uncertainty
import libdatasets
from libutil import out_dir, listify
from libconfig import Config
logger = logging.getLogger(__name__)
class FailedToTerminate(Exception):
def __init__(self, method):
super().__init__(f"{method} failed to determine a stopping location")
class InvalidAssumption(Exception):
def __init__(self, method, reason):
super().__init__(f"{method} could not be evaluated because: {reason}")
class Criteria(ABC):
@abstractmethod
def metric(self, **kwargs):
pass
@abstractmethod
def condition(self, x, metric):
pass
@property
def display_name(self) -> str:
return getattr(self, "display_name", type(self).__name__)
@classmethod
def all_criteria(cls) -> List[Type]:
# https://stackoverflow.com/questions/3862310/how-to-find-all-the-subclasses-of-a-class-given-its-name
return set(cls.__subclasses__()).union(
[s for c in cls.__subclasses__() for s in cls.all_criteria(c)]
)
@dataclass
class SC_entropy_mcs(Criteria):
"""
Determine a stopping point based on when *all* samples in the unlabelled pool are
below a threshold.
https://www.aclweb.org/anthology/I08-1048.pdf
"""
threshold: int = 0.01
def metric(self, entropy_max, **kwargs):
return entropy_max
def condition(self, x, metric):
if not (metric <= self.threshold).any():
raise FailedToTerminate("SC_entropy_mcs")
return x.iloc[np.argmax(metric <= self.threshold)]
@dataclass
class SC_oracle_acc_mcs(Criteria):
"""
Determine a stopping point based on when the accuracy of the current classifier on the
just-labelled samples is above a threshold.
https://www.aclweb.org/anthology/I08-1048.pdf
"""
threshold: int = 0.9
def metric(self, classifiers, **kwargs):
return acc_last(classifiers)[1]
def condition(self, x, metric):
"""
Determine a stopping point based on when the accuracy of the current classifier on the
just-labelled samples is above a threshold.
https://www.aclweb.org/anthology/I08-1048.pdf
"""
try:
return x[1:][np.argmax(np.array(metric)[1:] >= self.threshold) + 1]
except IndexError:
raise FailedToTerminate("SC_oracle_acc_mcs")
@dataclass
class SC_mes(Criteria):
"""
Determine a stopping point based on the expected error of the classifier is below a
threshold.
https://www.aclweb.org/anthology/I08-1048.pdf
"""
threshold: int = 1e-2
def metric(self, classifiers, **kwargs):
out = []
rand = np.random.default_rng(42)
for i, clf in enumerate(classifiers):
subsample = rand.choice(
clf.X_unlabelled.shape[0],
min(1000, clf.X_unlabelled.shape[0]),
replace=False,
)
max_pred = np.max(clf.predict_proba(clf.X_unlabelled[subsample]), axis=1)
out.append((1 / subsample.shape[0]) * np.sum(1 - max_pred))
return np.array(out)
def condition(self, x, metric):
if (metric <= self.threshold).any():
return x.iloc[np.argmax(metric <= self.threshold)]
raise FailedToTerminate("SC_mes")
class EVM(Criteria):
"""
Determine a stopping point based on the variance of the uncertainty in the unlabelled pool.
* `selected` determines if the variance is calculated accross the entire pool or only the instances
to be selected.
* `n` the number of values for which the variance must decrease sequentially, paper used `2`.
* `m` the threshold for which the variance must decrease by to be considered decreasing, paper
used `0.5`.
https://www.aclweb.org/anthology/W10-0101.pdf
"""
selected: bool = True
n: int = 2
m: float = 1e-3
def metric(self, uncertainty_variance, uncertainty_variance_selected, **kwargs):
return uncertainty_variance_selected if self.selected else uncertainty_variance
def condition(self, x, metric):
current = 0
last = metric[0]
for i, value in enumerate(metric[1:]):
if current == self.n:
# This used to be -1, which was a bug I think?
return x[i + 1]
if value < last - self.m:
current += 1
last = value
raise FailedToTerminate("EVM")
class VM(EVM):
m: float = 0
@dataclass
class SSNCut(Criteria):
"""
NOTES:
* They used an RBF svm to match the RBF affinity measure for SpectralClustering
* As we carry out experiments on a linear svm we also use a ~~linear~~ *cosine* affinity matrix (by default)
* Cosine is used as our features are not necessarilly normalized
file:///F:/Documents/Zotero/storage/DJGRDXSK/Fu%20and%20Yang%20-%202015%20-%20Low%20density%20separation%20as%20a%20stopping%20criterion%20for.pdf
"""
m: float = 0.2
verbose: bool = False
def metric(
self,
classifiers,
**kwargs,
):
if self.verbose:
print("SSNCut metric start")
if any(
getattr(clf.estimator, "kernel", None) != "linear" for clf in classifiers
):
raise InvalidAssumption("SSNCut", "model is not a linear SVM")
unique_y = np.unique(classifiers[0].y_training)
if len(unique_y) > 2:
raise InvalidAssumption("SSNCut", "dataset is not binary")
clustering = SpectralClustering(
n_clusters=unique_y.shape[0], affinity="precomputed"
)
out = []
if self.verbose:
print(f"0/{len(classifiers)}")
for i, clf in enumerate(classifiers):
t0 = time.monotonic()
# Note: With non-binary classification the value of the decision function is a transformation of the distance...
order = np.argsort(
np.abs(clf.estimator.decision_function(clf.X_unlabelled))
)
M = clf.X_unlabelled[order[: min(1000, clf.X_unlabelled.shape[0])]]
y0 = clf.predict(M)
# We use cos+1 as our affinity matrix as we want something that:
# * Is linear, to fit the rbf svm/rbf affinity pattern in the paper
# * Handles non-normalized samples (rules out linear)
# * Is non-negative (condition of scikit-learn's implementation)
affinity = pairwise_kernels(M, metric="cosine") + 1
assert np.all(affinity >= 0)
y1 = clustering.fit_predict(affinity)
y0 = LabelEncoder().fit_transform(y0)
diff = np.sum(y0 == y1) / clf.X_unlabelled.shape[0]
if diff > 0.5:
diff = 1 - diff
out.append(diff)
if self.verbose:
print(f"{time.monotonic()-t0:.2f},")
return out
def condition(self, x, metric):
smallest = np.infty
x0 = 0
for i, v in enumerate(metric):
if v < smallest:
smallest = v
x0 = 0
else:
x0 += 1
if x0 == 10:
return x.iloc[i - 10] # return to the point of lowest value
raise FailedToTerminate("SSNCut")
@dataclass
class ContradictoryInformation(Criteria):
"""
Stop when contradictory information drops for `rounds` consecutive rounds.
https://www-sciencedirect-com.ezproxy.auckland.ac.nz/science/article/pii/S088523080700068X
"""
rounds: int = 3
def metric(self, contradictory_information, **kwargs):
return contradictory_information
def condition(self, x, metric):
current = 0
last = metric[0]
for i, value in enumerate(metric[1:]):
if current == self.rounds:
return x[i + 1]
if value < last:
current += 1
last = value
raise FailedToTerminate("contradictory_information")
@dataclass
class PerformanceConvergence(Criteria):
"""
We use k=10 instead of 100 because batch size is 10 for us, 1 for them
multiple thresholds tested by authors (1e-2, 5e-5)
https://www.aclweb.org/anthology/C08-1059.pdf
"""
k: int = 10
threshold: float = 5e-5
average: Callable = np.mean
weak_threshold: float = 0.8
@listify
def metric(self, classifiers, **kwargs):
for clf in classifiers:
X_subsampled = clf.X_unlabelled[
np.random.choice(
clf.X_unlabelled.shape[0],
min(clf.X_unlabelled.shape[0], 1000),
replace=False,
)
]
p = clf.predict_proba(X_subsampled)
# d indicates if a particular prediction is from the winning (max probability) class
d = (p.T == np.max(p, axis=1)).T * 1
def tp(p, d):
"Sum of the probabilities of the winning predictions"
return np.sum(p * d)
def fp(p, d):
"Sum of (1-prob) for the winning prediction"
return np.sum((1 - p) * d)
def fn(p, d):
return np.sum(p * (1 - d))
yield 2 * tp(p, d) / (2 * tp(p, d) + fp(p, d) + fn(p, d))
def weak_determine_start(self, metric):
return np.argmax(np.array(metric) >= self.weak_threshold)
def condition(self, x, metric):
windows = np.lib.stride_tricks.sliding_window_view(metric, self.k)
for i in range(1, len(windows)):
w2 = self.average(windows[i])
w1 = self.average(windows[i - 1])
g = w2 - w1
if (
windows[i][-1] > np.max(metric[: i + self.k - 1])
and g > 0
and g < self.threshold
):
return x.iloc[i + self.k - 1]
raise FailedToTerminate("performance_convergence")
@dataclass
class SecondDiffZeroPerformanceConvergence(PerformanceConvergence):
alpha: float = 1e-1
diffkernel: str = "sq"
wait_iters: int = 5
start_threshold: float = 0.1
start_method: str = "1"
def metric(self, **kwargs):
met = super().metric(**kwargs)
grad = np.array(
no_ahead_tvregdiff(
met,
1,
self.alpha,
diffkernel=self.diffkernel,
plotflag=False,
diagflag=False,
)
)
sec = np.array(
no_ahead_tvregdiff(
grad,
1,
self.alpha,
diffkernel=self.diffkernel,
plotflag=False,
diagflag=False,
)
)
return met, grad, sec
def determine_start(self, sec):
return np.argmax(sec >= self.start_threshold)
def condition(self, x, metric):
met, grad, sec = metric
if self.start_method == "1":
start = self.determine_start(sec)
else:
start = self.weak_determine_start(met)
if not (sec[start:] <= 0).any():
raise FailedToTerminate("SecondDiffZeroPerformanceConvergence")
# stop when we hit zero
return x.iloc[np.argmax(sec[start:] <= 0) + start]
@dataclass
class FirstDiffZeroPerformanceConvergence(PerformanceConvergence):
alpha: float = 1e-1
diffkernel: str = "sq"
wait_iters: int = 5
start_threshold: float = 1e-1
start_iters: int = 5
start_method: str = "1"
def metric(self, **kwargs):
met = super().metric(**kwargs)
grad = np.array(
no_ahead_tvregdiff(
met,
1,
self.alpha,
diffkernel=self.diffkernel,
plotflag=False,
diagflag=False,
)
)
return met, grad
def determine_start(self, grad):
# Find nth value where the threshold is exceeded
if np.count_nonzero(grad >= self.start_threshold) < self.start_iters:
raise FailedToTerminate("FirstDiffZeroPerformanceConvergence")
return np.searchsorted(
np.cumsum(grad >= self.start_threshold), self.start_iters
)
def condition(self, x, metric):
met, grad = metric
if self.start_method == "1":
start = self.determine_start(grad)
else:
start = self.weak_determine_start(met)
if not (grad[start:] >= 0).any():
raise FailedToTerminate("FirstDiffZeroPerformanceConvergence")
# stop when we hit zero
return x.iloc[np.argmax(grad[start:] <= 0) + start]
@dataclass
class UncertaintyConvergence(Criteria):
"""
Stop based on the gradient of the last selected instance. The last selected instance supposedly has maximum uncertainty
and is hence the most informative.
We use k=10 instead of 100 because batch size is 10 for us, 1 for them
multiple thresholds tested by authors (1e-2, 5e-5)
Metrics:
* classifier_entropy
* classifier_margin
* classifier_minmax
Threshold:
* 0.00005
https://www.aclweb.org/anthology/C08-1059.pdf
"""
threshold: float = 5e-5
k: int = 10
average: Callable = np.median
def metric(self, classifiers, **kwargs):
# Maximum entropy in the selected batch of instances
return metric_selected(classifiers, classifier_uncertainty, aggregator=np.max)
def condition(self, x, metric):
metric = 1 - np.array(metric)
windows = np.lib.stride_tricks.sliding_window_view(metric, self.k)
for i in range(1, len(windows)):
w2 = self.average(windows[i])
w1 = self.average(windows[i - 1])
g = w2 - w1
if (
windows[i][-1] > np.max(metric[: i + self.k - 1])
and g > 0
and g < self.threshold
):
return x.iloc[i + self.k - 1]
raise FailedToTerminate("UncertaintyConvergence")
@dataclass
class OverallUncertainty(Criteria):
"""
Stop if the overall uncertainty on the unlabelled pool is less than a threshold.
https://www.aclweb.org/anthology/C08-1142.pdf
"""
threshold: float = 1e-2
weak_threshold: float = 1.5e-1
def metric(self, uncertainty_average, **kwargs):
return uncertainty_average
def threshold_determine_start(self, metric):
"Determine a point safe to start evaluating unstable conditions"
return np.argmax(metric < self.weak_threshold)
def condition(self, x, metric):
if not (metric < self.threshold).any():
raise FailedToTerminate("overall_uncertainty")
return x.iloc[np.argmax(metric < self.threshold)]
@dataclass
class FirstDiffMinOverallUncertainty(OverallUncertainty):
"""
Modified OverallUncertainty which stops when the first derivative hits an (estimated) global
minimum.
* eps, diffkernel control the regularlization of the differentiation algorithm
* stop_iters determines how many rounds we check to see if we have a minimum
"""
alpha: float = 1e-1
diffkernel: str = "sq"
stop_iters: int = 5
start_method: str = "1"
start_threshold: float = -1e-1
start_iters: int = 5
def metric(self, **kwargs):
met = super().metric(**kwargs)
grad = np.array(
no_ahead_tvregdiff(
met,
1,
self.alpha,
diffkernel=self.diffkernel,
plotflag=False,
diagflag=False,
)
)
return met, grad
def determine_start(self, grad):
# Find nth value where the threshold is exceeded
if np.count_nonzero(grad <= self.start_threshold) < self.start_iters:
raise FailedToTerminate("FirstDiffMinOverallUncertainty")
return np.searchsorted(
np.cumsum(grad <= self.start_threshold), self.start_iters
)
def condition(self, x, metric):
met, grad = metric
if self.start_method == "1":
start = self.determine_start(grad)
else:
start = self.threshold_determine_start(met)
minimum = 1e-1
iters = self.stop_iters + 1 # Will not terminate until min set
for i, v in enumerate(grad[start:]):
if iters == self.stop_iters:
return x.iloc[i + start]
if v < minimum:
minimum = v
iters = 0
else:
iters += 1
raise FailedToTerminate("FirstDiffMinOverallUncertainty")
@dataclass
class FirstDiffZeroOverallUncertainty(OverallUncertainty):
alpha: float = 1e-1
diffkernel: str = "sq"
wait_iters: int = 5
start_method: str = "1"
start_threshold: float = -1e-1
start_iters: int = 5
def metric(self, **kwargs):
met = super().metric(**kwargs)
grad = np.array(
no_ahead_tvregdiff(
met,
1,
self.alpha,
diffkernel=self.diffkernel,
plotflag=False,
diagflag=False,
)
)
return met, grad
def determine_start(self, grad):
# Find nth value where the threshold is exceeded
if np.count_nonzero(grad <= self.start_threshold) < self.start_iters:
raise FailedToTerminate("FirstDiffZeroOverallUncertainty")
return np.searchsorted(
np.cumsum(grad <= self.start_threshold), self.start_iters
)
def condition(self, x, metric):
met, grad = metric
if self.start_method == "1":
start = self.determine_start(grad)
else:
start = self.threshold_determine_start(met)
if not (grad[start:] >= 0).any():
raise FailedToTerminate("FirstDiffZeroOverallUncertainty")
# stop when we hit zero
return x.iloc[np.argmax(grad[start:] >= 0) + start]
@dataclass
class SecondDiffZeroOverallUncertainty(OverallUncertainty):
alpha: float = 1e-1
diffkernel: str = "sq"
wait_iters: int = 5
start_method: str = "1"
start_threshold: float = -1e-1
start_iters: int = 5
def metric(self, **kwargs):
met = super().metric(**kwargs)
grad = np.array(
no_ahead_tvregdiff(
met,
1,
self.alpha,
diffkernel=self.diffkernel,
plotflag=False,
diagflag=False,
)
)
sec = np.array(
no_ahead_tvregdiff(
grad,
1,
self.alpha,
diffkernel=self.diffkernel,
plotflag=False,
diagflag=False,
)
)
return met, grad, sec
def determine_start(self, sec):
# Find nth value where the threshold is exceeded
if np.count_nonzero(sec <= self.start_threshold) < self.start_iters:
raise FailedToTerminate("FirstDiffZeroOverallUncertainty")
start = np.searchsorted(
np.cumsum(sec <= self.start_threshold), self.start_iters
)
def condition(self, x, metric):
met, grad, sec = metric
if self.start_method == "1":
start = self.determine_start(sec)
else:
start = self.threshold_determine_start(met)
if not (sec[start:] >= 0).any():
raise FailedToTerminate("FirstDiffZeroOverallUncertainty")
# stop when we hit zero
return x.iloc[np.argmax(sec[start:] >= 0) + start]
@dataclass
class ClassificationChange(Criteria):
"""
Stop if the predictions on the unlabelled pool does not change between two rounds.
https://www.aclweb.org/anthology/C08-1142.pdf
"""
@listify
def metric(self, classifiers, **kwargs):
yield np.nan
rand = np.random.default_rng(42)
for i in range(1, len(classifiers)):
X_subsampled = classifiers[i].X_unlabelled[
rand.choice(
classifiers[i].X_unlabelled.shape[0],
min(1000, classifiers[i].X_unlabelled.shape[0]),
replace=False,
)
]
yield np.count_nonzero(
classifiers[i - 1].predict(X_subsampled)
== classifiers[i].predict(X_subsampled)
) / X_subsampled.shape[0]
def condition(self, x, metric):
if not any(np.isclose(x, 1) for x in metric):
raise FailedToTerminate("classification_change")
return x.iloc[np.argmax(np.isclose(metric[1:], 1)) + 1]
def reconstruct_unlabelled(clfs, X_unlabelled, Y_oracle, dense_atol=1e-6):
"""
Reconstruct the unlabelled pool from stored information. We do not directly store the unlabelled pool,
but we store enough information to reproduce it. This was used to compute stopping conditions implemented
after some experiments had been started.
"""
# Defensive asserts
assert clfs is not None, "Classifiers must be non-none"
assert X_unlabelled is not None, "X_unlabelled must be non-none"
assert Y_oracle is not None, "Y_oracle must be non-none"
assert (
X_unlabelled.shape[0] == Y_oracle.shape[0]
), "unlabelled and oracle pools have a different shape"
# TODO: This check is probably a bit slow, instead we could just check if the store is
# version 2?
if all(hasattr(clf, "X_unlabelled") for clf in clfs):
yield from (clf.X_unlabelled for clf in clfs)
# Fast row-wise compare function
def compare(A, B, sparse):
"https://stackoverflow.com/questions/23124403/how-to-compare-2-sparse-matrix-stored-using-scikit-learn-library-load-svmlight-f"
if sparse:
pairs = np.where(
np.isclose(
(np.array(A.multiply(A).sum(1)) + np.array(B.multiply(B).sum(1)).T)
- 2 * A.dot(B.T).toarray(),
0,
)
)
# TODO: Assert A[A_idx] == B[B_idx] for all pairs? Harder with sparse matrices.
else:
dists = euclidean_distances(A, B, squared=True)
pairs = np.where(np.isclose(dists, 0, atol=dense_atol))
for A_idx, B_idx in zip(*pairs):
try:
assert (A[A_idx] == B[B_idx]).all()
except AssertionError as e:
print(A[A_idx])
print(B[A_idx])
raise e
return pairs
# Yield the initial unlabelled pool
yield X_unlabelled.copy()
for clf in clfs[1:]:
assert X_unlabelled.shape[0] == Y_oracle.shape[0]
# make sure we're only checking for values from the 10 most recently added points
# otherwise we might think a duplicate is a new point and try to add it, making the
# count wrong!
equal_rows = list(
compare(
X_unlabelled,
clf.X_training[-10:],
sparse=isinstance(X_unlabelled, scipy.sparse.csr_matrix),
)
)
# Index fixing?
equal_rows[1] = equal_rows[1] + (clf.X_training.shape[0] - 10)
# Some datasets (rcv1) contain duplicates. These were only queried once, so we
# make sure we only remove a single copy from the unlabelled pool.
if len(equal_rows[0]) > 10:
logger.debug(f"Found {len(equal_rows[0])} equal rows")
really_equal_rows = []
for clf_idx in np.unique(equal_rows[1]):
dupes = equal_rows[0][equal_rows[1] == clf_idx]
# some datasets have duplicates with differing labels (rcv1)
dupes_correct_label = dupes[
(Y_oracle[dupes] == clf.y_training[clf_idx])
&
# this check is necessary so we don't mark an instance for removal twice
# when we want to mark another duplicate
np.logical_not(np.isin(dupes, really_equal_rows))
][0]
really_equal_rows.append(dupes_correct_label)
logger.debug(f"Found {len(really_equal_rows)} really equal rows")
elif len(equal_rows[0]) == 10:
# Fast path with no duplicates
assert (Y_oracle[equal_rows[0]] == clf.y_training[equal_rows[1]]).all()
really_equal_rows = equal_rows[0]
else:
raise Exception(
f"Less than 10 ({len(equal_rows[0])}) equal rows were found."
+ " This could indicate an issue with the row-wise compare"
+ " function."
)
assert len(really_equal_rows) == 10, f"{len(really_equal_rows)}==10"
n_before = X_unlabelled.shape[0]
if isinstance(X_unlabelled, scipy.sparse.csr_matrix):
X_unlabelled = delete_from_csr(X_unlabelled, really_equal_rows)
else:
X_unlabelled = np.delete(X_unlabelled, really_equal_rows, axis=0)
Y_oracle = np.delete(Y_oracle, really_equal_rows, axis=0)
assert (
X_unlabelled.shape[0] == n_before - 10
), f"We found 10 equal rows but {n_before-X_unlabelled.shape[0]} were removed"
yield X_unlabelled.copy()
class NSupport(Criteria):
"""
Determine a stopping point based on when the number of support vectors saturates.
https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.31.6090&rep=rep1&type=pdf
"""
threshold: float = 0
stable_iters: int = 2
def metric(self, classifiers, n_support, **kwargs):
if any(
getattr(clf.estimator, "kernel", None) != "linear" for clf in classifiers
):
raise InvalidAssumption("n_support only supports linear SVMs")
return n_support
def condition(self, x, metric):
return x.iloc[
__is_approx_constant(
metric, threshold=self.threshold, stable_iters=self.stable_iters
)
]
@dataclass
class StabilizingPredictions(Criteria):
"""
Determine a stopping point based on agreement between past classifiers on a stopping
set.
This implementation uses a subsampled pool of 1000 instances, like all other methods we
evaluate, as supposed to the 2000 suggested in the paper.
* `k` determines how many classifiers are checked for agreement
* `threshold` determines the kappa level that must be reached to halt
https://arxiv.org/pdf/1409.5165.pdf
"""
threshold: float = 0.99
k: int = 3
weak_threshold: float = 0.9
def metric(self, x, classifiers, **kwargs):
return kappa_metric(x, classifiers, k=self.k)
def weak_determine_start(self, metric):
return np.argmax(metric >= self.weak_threshold)
def condition(self, x, metric):
if not (metric >= self.threshold).any():
raise FailedToTerminate("stabilizing_predictions")
return x[np.argmax(metric >= self.threshold)]
@dataclass
class StabilizingPredictionsPlusX(Criteria):
add_x: int = 100
def condition(self, x, metric):
return super().condition(x, metric) + self.add_x
@dataclass
class FirstDiffZeroStabilizingPredictions(StabilizingPredictions):
alpha: float = 1e-1
diffkernel: str = "sq"
start_method: str = "1"
def metric(self, **kwargs):
met = super().metric(**kwargs)
grad = np.array(
no_ahead_tvregdiff(
met,
1,
self.alpha,
diffkernel=self.diffkernel,
plotflag=False,
diagflag=False,
)
)
return met, grad
def determine_start(self, grad):
# Find first point > 0; TODO: This might need to be more rigorous.
return np.argmax(grad > 0)
def condition(self, x, metric):
met, grad = metric
if self.start_method == "1":
start = self.determine_start(grad)
else:
start = self.weak_determine_start(met)
# Find first point after that <= 0
if not (grad[start:] <= 0).any():
raise FailedToTerminate("FirstDiffZeroStabilizingPredictions")
return x.iloc[np.argmax(grad[start:] <= 0)]
@listify
def metric_selected(classifiers, metric, aggregator=np.min, **kwargs):
"""
Generator that produces the values of `metric` evaluated on the selected instances in each round of AL.
The metric is then aggregated across the batch by the `aggregator` to produce a single value per round.
"""
for i in range(1, len(classifiers)):
yield aggregator(
metric(classifiers[i - 1].estimator, classifiers[i].X_training[-10:])
)
yield np.nan
@dataclass
class MaxConfidence(Criteria):
"""
This strategy is based on uncertainty measurement, considering whether the entropy of each selected unlabelled
example is less than a very small predefined threshold close to zero, such as 0.001.
Note: The original authors only considered non-batch mode AL. We stop based on the min of the entropy.
https://www.aclweb.org/anthology/D07-1082.pdf
"""
threshold: float = 0.001