-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathoptimization_engine.py
More file actions
1735 lines (1361 loc) · 64.8 KB
/
optimization_engine.py
File metadata and controls
1735 lines (1361 loc) · 64.8 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
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
# some generic logging
from warnings import simplefilter
import pickle
import multiprocessing as mp
import os
import time
import itertools
import numpy as np
from scipy import sparse
from collections import defaultdict, Counter
from autoBOTLib.optimization.optimization_metrics import *
from autoBOTLib.optimization.optimization_feature_constructors import *
from autoBOTLib.learning.scikit_based import scikit_learners
from autoBOTLib.learning.torch_sparse_nn import torch_learners
import operator
import copy
import gc
from deap import base, creator, tools
import logging
logging.basicConfig(format='%(asctime)s - %(message)s',
datefmt='%d-%b-%y %H:%M:%S')
logging.getLogger(__name__).setLevel(logging.INFO)
# evolution helpers -> this needs to be global for proper persistence handling.
# If there is as better way, please open a pull request!
global gcreator
gcreator = creator
gcreator.create("FitnessMulti", base.Fitness, weights=(1.0, ))
gcreator.create("Individual", list, fitness=creator.FitnessMulti)
# omit some redundant warnings
simplefilter(action='ignore')
# relevant for visualization purposes, otherwise can be omitted.
try:
import matplotlib.pyplot as plt
import seaborn as sns
except Exception:
pass
class GAlearner:
"""
The core GA class. It includes methods for evolution of a learner assembly.
Each instance of autoBOT must be first instantiated.
In general, the workflow for working with this class is as follows:
1.) Instantiate the class
2.) Evolve
3.) Predict
"""
def __init__(self,
train_sequences_raw,
train_targets,
time_constraint,
num_cpu="all",
device="cpu",
task_name="Super cool task.",
latent_dim=512,
sparsity=0.1,
hof_size=1,
initial_separate_spaces=True,
scoring_metric=None,
top_k_importances=15,
representation_type="neurosymbolic",
binarize_importances=False,
memory_storage="memory",
learner=None,
n_fold_cv=5,
random_seed=8954,
learner_hyperparameters=None,
use_checkpoints=True,
visualize_progress=False,
custom_transformer_pipeline=None,
combine_with_existing_representation=False,
default_importance=0.05,
learner_preset="default",
task="classification",
contextual_model="all-mpnet-base-v2",
upsample=False,
verbose=1,
framework="scikit",
normalization_norm="l2",
validation_percentage=0.2,
validation_type="cv"):
"""The object initialization method; specify the core optimization
parameter with this method.
:param list/PandasSeries train_sequences_raw: a list of texts
:param list/np.array train_targets: a list of natural numbers (targets, multiclass), a list of lists (multilabel)
:param str device: Specification of the computation backend device
:param int time_constraint: Number of hours to evolve.
:param int/str num_cpu: Number of threads to exploit
:param str task_name: Task identifier for logging
:param int latent_dim: The latent dimension of embeddings
:param float sparsity: The assumed sparsity of the induced space (see paper)
:param int hof_size: Hof many final models to consider?
:param bool initial_separate_spaces: Whether to include separate spaces as part of the initial population.
:param str scoring_metric: The type of metric to optimize (sklearn-compatible)
:param int top_k_importances: How many top importances to remember for explanations.
:param str representation_type: "symbolic", "neural", "neurosymbolic", "neurosymbolic-default", "neurosymbolic-lite" or "custom". The "symbolic" feature space will only include feature types that we humans directly comprehend. The "neural" will include the embedding-based ones. The "neurosymbolic-default" will include the ones based on the origin MLJ paper, the "neurosymbolic" is the current alpha version with some new additions (constantly updated/developed). The "neurosymbolic-lite" version includes language-agnostic features but does not consider document graphs (due to space constraints)
:param str framework: The framework used for obtaining the final models (torch, scikit)
:param bool binarize_importances: Feature selection instead of ranking as explanation
:param str memory_storage: The storage of the gzipped (TSV) triplets (SPO).
:param obj learner: custom learner. If none, linear learners are used.
:param obj learner_hyperparameters: The space to be optimized w.r.t. the learner param.
:param int random_seed: The random seed used.
:param str contextual_model: The language model string compatible with sentence-transformers library (this is in beta)
:param bool visualize_progress: Progress visualization (progress.pdf, reqires MPL).
:param str task: Either "classification" - SGDClassifier, or "regression" - SGDRegressor
:param int n_fold_cv: The number of folds to be used for model evaluation.
:param str learner_preset: Type of classification to be considered (default=paper), ""mini-l1"" or ""mini-l2" -> very lightweight regression, emphasis on space exploration.
:param float default_importance: Minimum possible initial weight.
:param bool upsample: Whether to equalize the number of instances by upsampling.
:param float validation_percentage: The percentage of data to used as test set if validation_type="train_test"
:param str validation_type: type of validation, either train_val or cv (cross validation or train-val split)
"""
# Set the random seed
self.random_seed = random_seed
self.framework = framework
self.upsample = upsample
self.visualize_progress = visualize_progress
self.validation_type = validation_type
self.device = device
self.validation_percentage = validation_percentage
self.task = task
self.use_checkpoints = use_checkpoints
self.contextual_model = contextual_model
self.multimodal_input = False
np.random.seed(random_seed)
self.verbose = verbose
self.mlc_flag = False
if self.upsample:
train_sequences_raw, train_targets = self.upsample_dataset(
train_sequences_raw, train_targets)
if isinstance(train_sequences_raw[0], str):
train_sequences_raw = [{"text_a": x.encode("utf-8")\
.decode("utf-8")} for x in train_sequences_raw]
else:
for el in train_sequences_raw:
el['text_a'] = el['text_a'].encode("utf-8").decode("utf-8")
assert isinstance(train_sequences_raw[0], dict)
if len(train_sequences_raw[0]) > 1:
if self.verbose:
logging.info(f"Considered multimodal autoBOT! Input types found: {train_sequences_raw[0].keys()}")
self.multimodal = True
logo = """
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWWM
WWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWWWM
xokKNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWWMMMMMMMMMM
l'';cdOKNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWNNMMMMMMMMMM
d'.''',;ldOXWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
x'...''''',c0MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWWMMMWXXMMMMMMMWWMMMMMMMMMM
k,....''''';kWMMMMMMMMMMMMMMMMMMMMMMMWNXWMN00NMMXk0NMMMMWXKNMMMMMMMMMM
0;......''';kWNK00000OOOOOOOOOOOKNXK0xx0WN0kONMWX00NMMMMN00XMMMMMWNNMM
K:........';OWx;;;;;;;;;;:::::ccldxxxxk0NNXXNWMMMMMMMMMMMWNWMMMMMWNNMM
Xc.........;OWx,',,,,,;;;;;:::::ccoxkOxdkKkxk0NWMMMMMMMMMMMMMMMMMMMMMM
Nl.........,OWk,''',,,,,;;;;;::::lxkkkOOKNK0KXX00NMMMWWMMMMMMMMMMMMMMM
Wd.........,OWk,''''',,,,,;;;;;::oddllx0KKNMWKxoxKMMWKKWMMMMMMMMMMMMMM
Wx.........,OMXxc;''''',,,,,;;;;:okkk0NN0xx0NN0OKWMMNkONMMWXNMMMMMMMMM
MO'........,OMMWWKkoc,''',,,,,;;cddld0N00NXOkKNNWMMMWXKNMWKk0WMMMMMMMM
M0, .......,OWOkXWMMN0ko:,,,,,,,;cox0Kxcl0XkoxOXWMMMMMMMMWNXXWMMMMMMMM
MK; .....,ONo.;dKWMMMWX0xl:,,,;oOKX0xddk00KNMMMMWWMMMMMMMMMMWNWMMMMM
MXc ...'ONl...,lONMMMMMWXOddkOxxkKX0xooONMMMWKxkNMMMMMMMMN0OXMMMMM
MNl. .'ONl.....'ckXWMMMMMMWWWNNNWWMWXXWMMMWKdcdXMMMMMMMMWNNWMMMMM
MWd. 'ONl........;dKWMMMMMMMMMMMMMMMMMMMMWKkx0WMMNKXMMMMMMMMMMMM
MMx. 'OWOoc;'......,oONMMMMMMMMMWWMW00NWMMMMMMMMW0dxKWMMMMMMMMMM
MMO. .;0MMWWNX0kxoc:,',ckXWMMMMWKdlxKOllxKWMWWMMMWXKXNWMMMMMMMMMM
MM0, .:xKWMNkdx0XWMMWNXKOxdkKWMWWXkkO0XNK00XWWOkNMMMMMMMMMMMMMMMMMM
MMX; 'cxKWN0x0WKc..';ldk0XWMMMWWWMMMMMMMMMMMMMMNk:lKMMN0kOKWMMMMMMMMMM
MMWOOXWN0d;. 'dNXo. ....,:ldkKXWWXXKO0KXNMMMMMNOxd0WMWOcoKMMMMMMMMMMM
MMMMW0d;. .:0Nx'. .......';oxc,:oxl:OXOkOOXWMWWMMMN0KWMMMMMMMMMMM
MMMW0c. 'xXO,. .........:ooloxxclkl,cxXWMN0KWMMMMMMMMMMMMMMMM
MMMMMNKxl,. .cK0:. .......:lc,.cxodOOkXWMMNkccdKWMMMMMMMMMMMMMM
MMMMMMMMMNKxl;. ,k0l. .....'okdodlcxKWWWMMMWNXK00NMMMMMMMMMMMMMM
MMMMMMMMMMMMMWKkl;. .l0d. ...:k0xclONWNkldONMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMWKkl:lkx,. ..:x0d:ckNNOdx0NWMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMN0OXO:,,,;;o0K0kocdXNNWMMMMMMMMMMMMMMMMMMMMMMMMMM
"""
if self.verbose:
print(logo)
logging.info(f"Considering preset: {representation_type}")
logging.info(f"Considering learning framework: {self.framework}")
self.default_importance = default_importance
self.learner_preset = learner_preset
self.scoring_metric = scoring_metric
self.normalization_norm = normalization_norm
self.representation_type = representation_type
self.custom_transformer_pipeline = custom_transformer_pipeline
self.combine_with_existing_representation \
= combine_with_existing_representation
self.initial_separate_spaces = initial_separate_spaces
if self.custom_transformer_pipeline is not None:
if self.verbose:
logging.info("Using custom feature transformations.")
self.binarize_importances = binarize_importances
self.latent_dim = latent_dim
self.sparsity = sparsity
# Dict of labels to int
self.label_mapping, self.inverse_label_mapping = self.get_label_map(
train_targets)
if self.verbose:
logging.info("Instantiated the evolution-based learner.")
self.summarise_dataset(train_sequences_raw, train_targets)
if not isinstance(train_targets, list):
try:
train_targets = train_targets.tolist()
except Exception as es:
logging.info(
"Please make the targets either a list or a np.array!", es)
# Encoded target space for training purposes
if self.task == "classification":
train_targets = np.array(self.apply_label_map(train_targets))
counts = np.bincount(train_targets)
self.majority_class = np.argmax(counts)
else:
train_targets = np.array(train_targets, dtype=np.float64)
self.learner = learner
self.learner_hyperparameters = learner_hyperparameters
# parallelism settings
if num_cpu == "all":
self.num_cpu = mp.cpu_count()
else:
self.num_cpu = num_cpu
if self.verbose:
logging.info(f"Using {self.num_cpu} cores.")
self.task_name = task_name
self.topk = top_k_importances
self.train_seq = self.return_dataframe_from_text(train_sequences_raw)
self.train_targets = train_targets
self.hof = [] # The hall of fame
self.memory_storage = memory_storage # Path to the memory storage
self.population = None # this object gets evolved
# establish constraints
self.max_time = time_constraint
self.unique_labels = len(set(train_targets))
self.initial_time = None
self.subspace_feature_names = None
self.ensemble_of_learners = []
self.n_fold_cv = n_fold_cv
if self.verbose:
logging.info(
"Initiating the seed vectorizer instance and initial feature \
space ..")
# hyperparameter space. Parameters correspond to weights of subspaces,
# as well as subsets + regularization of LR.
# other hyperparameters
self.hof_size = hof_size # size of the hall of fame.
if self.hof_size % 2 == 0:
if self.verbose:
logging.info(
"HOF size must be odd, adding one member ({}).".format(
self.hof_size))
self.hof_size += 1
self.fitness_container = [] # store fitness across evalution
# stats
self.feature_importances = []
self.fitness_max_trace = []
self.fitness_mean_trace = []
self.feat_min_trace = []
self.feat_mean_trace = []
self.opt_population = None
if self.verbose:
logging.info(
"Loaded a dataset of {} texts with {} unique labels.".format(
self.train_seq.shape[0], len(set(train_targets))))
if self.scoring_metric is None:
if self.unique_labels > 2:
self.scoring_metric = "f1_macro"
else:
self.scoring_metric = "f1"
def get_label_map(self, train_targets):
"""
Identify unique target labels and remember them.
:param list/np.array train_targets: The training target space (or any other for that matter)
:return label_map, inverse_label_map: Two dicts, mapping to and from encoded space suitable for autoML loopings.
"""
# Primitive MLC -> each subset is a possible label
if isinstance(train_targets[0], list):
self.mlc_flag = True
train_targets = [str(x) for x in train_targets]
unique_train_target_labels = set(train_targets)
label_map = {}
for enx, j in enumerate(unique_train_target_labels):
label_map[j] = enx
inverse_label_map = {y: x for x, y in label_map.items()}
return label_map, inverse_label_map
def apply_label_map(self, targets, inverse=False):
"""
A simple mapping back from encoded target space.
:param list/np.array targets: The target space
:param bool inverse: Boolean if map to origin space or not (default encodes into continuum)
:return list new_targets: Encoded target space
"""
if inverse:
new_targets = [self.inverse_label_mapping[x] for x in targets]
else:
if self.mlc_flag:
targets = [str(x) for x in targets]
new_targets = [self.label_mapping[x] for x in targets]
return new_targets
def update_global_feature_importances(self):
"""
Aggregate feature importances across top learners to obtain the final ranking.
"""
fdict = {}
self.sparsity_coef = []
# get an indicator of global feature space and re-map.
global_fmaps = defaultdict(list)
for enx, importance_tuple in enumerate(self.feature_importances):
subspace_features = importance_tuple[1]
coefficients = importance_tuple[0]
assert len(subspace_features) == len(coefficients)
sparsity_coef = np.count_nonzero(coefficients) / len(coefficients)
self.sparsity_coef.append(sparsity_coef)
if self.verbose:
logging.info("Importance (learner {}) sparsity of {}".format(
enx, sparsity_coef))
for fx, coef in zip(subspace_features, coefficients):
space_of_the_feature = self.global_feature_name_hash[fx]
if fx not in fdict:
fdict[fx] = np.abs(coef)
else:
fdict[fx] += np.abs(coef)
global_fmaps[space_of_the_feature].append((fx, coef))
self.global_feature_map = {}
for k, v in global_fmaps.items():
tmp = {}
for a, b in v:
tmp[a] = round(b, 2)
mask = ["x"] * self.topk
top5 = [
" : ".join([str(y) for y in x]) for x in sorted(
tmp.items(), key=operator.itemgetter(1), reverse=True)
][0:self.topk]
mask[0:len(top5)] = top5
self.global_feature_map[k] = mask
self.global_feature_map = pd.DataFrame(self.global_feature_map)
self.sparsity_coef = np.mean(self.sparsity_coef)
self._feature_importances = sorted(fdict.items(),
key=operator.itemgetter(1),
reverse=True)
if self.verbose:
logging.info(
"Feature importances can be accessed by ._feature_importances")
def compute_time_diff(self):
"""
A method for approximate time monitoring.
"""
return ((time.time() - self.initial_time) / 60) / 60
def prune_redundant_info(self):
"""
A method for removing redundant additional info which increases the final object's size.
"""
self.fitness_container = []
self.feature_importances = []
if self.verbose:
logging.info(
"Cleaned fitness and importances, the object should be smaller now."
)
def parallelize_dataframe(self, df, func):
"""
A method for parallel traversal of a given dataframe.
:param pd.DataFrame df: dataframe of text (Pandas object)
:param obj func: function to be executed (a function)
"""
if self.verbose:
logging.info("Computing the seed dataframe ..")
df = pd.concat(map(func, df))
# Do a pre-split of the data and compute in parallel.
# df_split = np.array_split(df, self.num_cpu * 10)
# pool = mp.Pool(self.num_cpu)
# df = pd.concat(
# tqdm.tqdm(pool.imap(func, df_split), total=len(df_split)))
# pool.close()
# pool.join()
return df
def upsample_dataset(self, X, Y):
"""
Perform very basic upsampling of less-present classes.
:param list X: Input list of documents
:param np.array/list Y: Targets
:return X,Y: Return upsampled data.
"""
if self.verbose:
logging.info("Performing upsampling ..")
if not isinstance(X, list):
X = X.values.tolist()
if not isinstance(Y, list):
Y = Y.values.tolist()
extra_targets = []
extra_instances = []
counter_for_classes = Counter(Y)
if self.verbose:
for k, v in counter_for_classes.items():
logging.info(f"Presence of class {k}; {v/len(Y)}")
class_counts = {
k: v
for k, v in sorted(dict(counter_for_classes).items(),
key=lambda item: item[1])
}
classes = list(class_counts.keys())[::-1]
most_frequent = classes[0]
most_frequent_count = class_counts[most_frequent]
for cname in classes[1:]:
difference = most_frequent_count - class_counts[cname]
if difference == 0:
continue
if self.verbose:
logging.info(f"Upsampling for: {cname}; samples: {difference}")
indices = [enx for enx, x in enumerate(Y) if x == cname]
random_subspace = np.random.choice(indices, difference)
for sample in random_subspace:
extra_targets.append(Y[sample])
extra_instances.append(X[sample])
if self.verbose:
logging.info(
f"Generated {len(extra_instances)} new instances to balance the data."
)
X = X + extra_instances
Y = Y + extra_targets
return X, Y
def return_dataframe_from_text(self, text):
"""
A helper method that return a given dataframe from text.
:param list/pd.Series text: list of texts.
:return parsed df: A parsed text (a DataFrame)
"""
return build_dataframe(text)
def generate_random_initial_state(self, weights_importances):
"""
The initialization method, capable of generation of individuals.
"""
weights = np.random.uniform(low=0.6, high=1,
size=self.weight_params).tolist()
weights[0:len(weights_importances)] = weights_importances
generic_individual = np.array(weights)
assert len(generic_individual) == self.weight_params
return generic_individual
def summarise_dataset(self, list_of_texts, targets):
list_of_texts = [x['text_a'] for x in list_of_texts]
if not isinstance(targets, list):
targets = targets.tolist()
lengths = []
unique_tokens = set()
targets = [str(x) for x in targets]
for x in list_of_texts:
lengths.append(len(x))
parts = x.strip().split()
for part in parts:
unique_tokens.add(part)
logging.info(f"Number of documents: {len(list_of_texts)}")
logging.info(f"Average document length: {np.mean(lengths)}")
logging.info(f"Number of unique tokens: {len(unique_tokens)}")
if len(set(targets)) < 200:
logging.info(f"Unique target values: {set(targets)}")
def custom_initialization(self):
"""
Custom initialization employs random uniform prior. See the paper for more details.
"""
if self.verbose:
logging.info(
"Performing initial screening on {} subspaces.".format(
len(self.feature_subspaces)))
performances = []
self.subspace_performance = {}
for subspace, name in zip(self.feature_subspaces, self.feature_names):
f1, _ = self.cross_val_scores(subspace)
self.subspace_performance[name] = f1
performances.append(f1)
pairs = [
" -- ".join([str(y) for y in x])
for x in list(zip(self.feature_names, performances))
]
if self.verbose:
logging.info("Initial screening report follows.")
for pair in pairs:
if self.verbose:
logging.info(pair)
weights = np.array(performances) / max(performances) if len(performances) > 0 and max(performances) > 0 else np.ones(len(performances))
generic_individual = self.generate_random_initial_state(weights)
assert len(generic_individual) == self.weight_params
for ind in self.population:
noise = np.random.uniform(low=0.95,
high=1.05,
size=self.weight_params)
generic_individual = generic_individual * noise \
+ self.default_importance
ind[:] = np.abs(generic_individual)
# Separate spaces -- each subspace massively amplified
self.separate_individual_spaces = []
# All weights set to one (this is the naive learning setting)
unweighted = copy.deepcopy(self.population[0])
unweighted[:] = np.ones(self.weight_params)
self.separate_individual_spaces.append(unweighted)
# Add separate spaces as solutions too
if self.initial_separate_spaces:
for k in range(self.weight_params):
individual = copy.deepcopy(self.population[0])
individual[:] = np.zeros(self.weight_params)
individual[k] = 1 # amplify particular subspace.
self.separate_individual_spaces.append(individual)
def apply_weights(self,
parameters,
custom_feature_space=False,
custom_feature_matrix=None):
"""
This method applies weights to individual parts of the feature space.
:param np.array parameters: a vector of real-valued parameters - solution=an individual
:param bool custom_feature_space: Custom feature space, relevant during making of predictions.
:return np.array tmp_space: Temporary weighted space (individual)
"""
# Compute cumulative sum across number of features per feature type.
indices = self.intermediary_indices
# Copy the space as it will be subsetted.
if not custom_feature_space:
# Use a more memory-efficient copy approach
tmp_space = self.train_feature_space.copy()
if sparse.issparse(tmp_space):
tmp_space = sparse.csr_matrix(tmp_space)
else:
tmp_space = sparse.csr_matrix(tmp_space)
else:
tmp_space = sparse.csr_matrix(custom_feature_matrix)
indices_pairs = []
assert len(indices) == self.weight_params + 1
for k in range(self.weight_params):
i1 = indices[k]
i2 = indices[k + 1]
indices_pairs.append((i1, i2))
# subset the core feature matrix -- only consider non-neural features for this.
for j, pair in enumerate(indices_pairs):
tmp_space[:,
pair[0]:pair[1]] = tmp_space[:,
pair[0]:pair[1]].multiply(
parameters[j])
return tmp_space
def cross_val_scores(self, tmp_feature_space, final_run=False):
"""
Compute the learnability of the representation.
:param np.array tmp_feature_space: An individual's solution space.
:param bool final_run: Last run is more extensive.
:return float performance_score, clf: F1 performance and the learned learner.
"""
# Scikit-based learners
if self.framework == "scikit":
performance_score, clf = scikit_learners(
final_run, tmp_feature_space, self.train_targets,
self.learner_hyperparameters, self.learner_preset,
self.learner, self.task, self.scoring_metric, self.n_fold_cv,
self.validation_percentage, self.random_seed, self.verbose,
self.validation_type, self.num_cpu)
elif self.framework == "torch":
performance_score, clf = torch_learners(
final_run, tmp_feature_space, self.train_targets,
self.learner_hyperparameters, self.learner_preset,
self.learner, self.task, self.scoring_metric, self.n_fold_cv,
self.validation_percentage, self.random_seed, self.verbose,
self.validation_type, self.num_cpu, self.device)
else:
raise NotImplementedError(
"Select either `torch` or `scikit` as the framework used.")
return performance_score, clf
def evaluate_fitness(self,
individual,
max_num_feat=1000,
return_clf_and_vec=False):
"""
A helper method for evaluating an individual solution. Given a real-valued vector, this constructs the representations and evaluates a given learner.
:param np.array individual: an individual (solution)
:param int max_num_feat: maximum number of features that are outputted
:param bool return_clf_and_vec: return learner and vectorizer? This is useful for deployment.
:return float score: The fitness score.
"""
individual = np.array(individual)
if self.task == "classification":
if np.sum(individual[:]) > self.weight_params:
return (0, )
if (np.array(individual) <= 0).any():
individual[(individual < 0)] = 0
else:
individual = np.abs(individual)
if self.binarize_importances:
for k in range(len(self.feature_names)):
weight = individual[k]
if weight > 0.5:
individual[k] = 1
else:
individual[k] = 0
if self.vectorizer:
tmp_feature_space = self.apply_weights(individual[:])
feature_names = self.all_feature_names
# Return the trained learner.
if return_clf_and_vec:
# fine tune final learner
if self.verbose:
logging.info("Final round of optimization.")
performance_score, clf = self.cross_val_scores(
tmp_feature_space, final_run=True)
return clf, individual[:], performance_score, feature_names
performance_score, _ = self.cross_val_scores(tmp_feature_space)
return (performance_score, )
elif return_clf_and_vec:
return (0, )
else:
return (0, )
def generate_and_update_stats(self, fits):
"""
A helper method for generating stats.
:param list fits: fitness values of the current population
:return float meanScore: The mean of the fitnesses
"""
f1_scores = []
for fit in fits:
f1_scores.append(fit)
return np.mean(f1_scores)
def report_performance(self, fits, gen=0):
"""
A helper method for performance reports.
:param np.array fits: fitness values (vector of floats)
:param int gen: generation to be reported (int)
"""
f1_top = self.generate_and_update_stats(fits)
if self.verbose:
logging.info(r"{} (gen {}) {}: {}, time: {}min".format(
self.task_name, gen, self.scoring_metric, np.round(f1_top, 3),
np.round(self.compute_time_diff(), 2) * 60))
return f1_top
def get_feature_space(self):
"""
Extract final feature space considered for learning purposes.
"""
transformed_instances, feature_indices = self.apply_weights(
self.hof[0])
assert transformed_instances.shape[0] == len(self.train_targets)
return (transformed_instances, self.train_targets)
def predict_proba(self, instances):
"""
Predict on new instances. Note that the prediction is actually a maxvote across the hall-of-fame.
:param list/pd.Series instances: predict labels for new instances=texts.
"""
if self.verbose:
logging.info("Obtaining final predictions from {} models.".format(
len(self.ensemble_of_learners)))
if not self.ensemble_of_learners:
if self.verbose:
logging.info("Please, evolve the model first!")
return None
else:
instances = self.return_dataframe_from_text(instances)
transformed_instances = self.vectorizer.transform(instances)
prediction_space = []
# transformed_instances=self.update_intermediary_feature_space(custom_space=transformed_instances)
if self.verbose:
logging.info("Representation obtained ..")
for learner_tuple in self.ensemble_of_learners:
try:
# get the solution.
learner, individual, score = learner_tuple
learner = learner.best_estimator_
# Subset the matrix.
subsetted_space = self.apply_weights(
individual,
custom_feature_space=True,
custom_feature_matrix=transformed_instances)
# obtain the predictions.
if prediction_space is not None:
prediction_space.append(
learner.predict(subsetted_space).tolist())
else:
prediction_space.append(
learner.predict(subsetted_space).tolist())
except Exception as es:
print(
es,
"Please, re-check the data you are predicting from!")
# generate the prediction matrix by maximum voting scheme.
pspace = np.matrix(prediction_space).T
np.nan_to_num(pspace, copy=False, nan=self.majority_class)
all_predictions = self.probability_extraction(
pspace) # Most common prediction is chosen.
if self.verbose:
logging.info("Predictions obtained")
return all_predictions
def probability_extraction(self, pred_matrix):
"""
Predict probabilities for individual classes. Probabilities are based as proportions of a particular label predicted with a given learner.
:param np.array pred_matrix: Matrix of predictions.
:return pd.DataFrame prob_df: A DataFrame of probabilities for each class.
"""
# identify individual class labels
pred_matrix = np.asarray(pred_matrix)
unique_values = np.unique(pred_matrix).tolist()
prediction_matrix_final = []
for k in range(pred_matrix.shape[0]):
pred_row = np.asarray(pred_matrix[k, :])
assert len(pred_row) == pred_matrix.shape[1]
counts = np.bincount(pred_row)
probability_vector = []
for p in range(len(unique_values)):
if p + 1 <= len(counts):
prob = counts[p]
else:
prob = 0
probability_vector.append(prob)
assert len(probability_vector) == len(unique_values)
prediction_matrix_final.append(probability_vector)
final_matrix = np.array(prediction_matrix_final)
prob_df = pd.DataFrame(final_matrix)
prob_df.columns = self.apply_label_map(unique_values, inverse=True)
# It's possible some labels are never predicted!
all_possible_labels = list(self.label_mapping.keys())
for i in all_possible_labels:
if i not in prob_df.columns:
prob_df[i] = 0.0
# Normalization
prob_df = prob_df.div(prob_df.sum(axis=1), axis=0)
csum = prob_df.sum(axis=1).values
zero_index = np.where(csum == 0)[0]
for j in zero_index:
# Ensure majority_class index is within bounds
if self.majority_class < prob_df.shape[1]:
prob_df.iloc[j, self.majority_class] = 1
else:
# Use the first column if majority_class is out of bounds
prob_df.iloc[j, 0] = 1
prob_df = prob_df.fillna(0)
assert len(np.where(prob_df.sum(axis=1) < 1)[0]) == 0
# Clean up temporary matrices
if 'prediction_matrix_final' in locals():
del prediction_matrix_final
if 'transformed_instances' in locals():
del transformed_instances
gc.collect()
return prob_df
def transform(self, instances):
"""
Generate only the representations (obtain a feature matrix subject to evolution in autoBOT)
:param list/pd.DataFrame instances: A collection of instances to be transformed into feature matrix.
:return sparseMatrix output_representation: Representation of the documents.
"""
if self.vectorizer is None:
if self.verbose:
logging.info(
"Please call evolution() first to learn the representation\
mappings.")
instances = self.return_dataframe_from_text(instances)
output_representation = self.vectorizer.transform(instances)
return output_representation
def predict(self, instances):
"""
Predict on new instances. Note that the prediction is actually a maxvote across the hall-of-fame.
:param list/pd.Series instances: predict labels for new instances=texts.
:return np.array all_predictions: Vector of predictions (decoded)
"""
if self.verbose:
logging.info("Obtaining final predictions from {} models.".format(
len(self.ensemble_of_learners)))
if not self.ensemble_of_learners:
if self.verbose:
logging.info("Please, evolve the model first!")
return None
else:
instances = self.return_dataframe_from_text(instances)
transformed_instances = self.vectorizer.transform(instances)
prediction_space = []
# transformed_instances=self.update_intermediary_feature_space(custom_space=transformed_instances)
if self.verbose:
logging.info("Representation obtained ..")
for learner_tuple in self.ensemble_of_learners:
try:
# get the solution.
learner, individual, score = learner_tuple
learner = learner.best_estimator_
# Subset the matrix.
subsetted_space = self.apply_weights(
individual,
custom_feature_space=True,
custom_feature_matrix=transformed_instances)
# obtain the predictions.
if prediction_space is not None:
prediction_space.append(
learner.predict(subsetted_space).tolist())
else:
prediction_space.append(
learner.predict(subsetted_space).tolist())
except Exception as es:
print(
es,
"Please, re-check the data you are predicting from!")
# generate the prediction matrix by maximum voting scheme.
pspace = np.matrix(prediction_space).T
if self.task == "classification":
converged_predictions = np.where(
~np.isnan(pspace).any(axis=0) == True)[0]
pspace = pspace[:, converged_predictions]
all_predictions = self.mode_pred(
pspace) # Most common prediction is chosen.