-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathcluster_gp_sklearn.py
1669 lines (1469 loc) · 61.6 KB
/
cluster_gp_sklearn.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
import builtins
import operator
import sys
import time
import traceback
from collections import deque, defaultdict
from itertools import compress
import pyximport
from deap import creator, base, tools, gp
from deap.algorithms import varAnd
from deap.base import Fitness
from deap.gp import Terminal, MetaEphemeral
from deap.tools import selNSGA2, selRandom, selSPEA2, selLexicase, selNSGA3
from glmnet import ElasticNet
from icecream import ic
from scipy.stats import pearsonr
from sklearn.base import BaseEstimator, RegressorMixin, TransformerMixin
from sklearn.cluster import KMeans
from sklearn.dummy import DummyRegressor
from sklearn.ensemble import BaggingRegressor, RandomForestClassifier
from sklearn.linear_model import LinearRegression, LassoCV, LogisticRegression
from sklearn.linear_model import RidgeCV, ElasticNetCV
from sklearn.linear_model._coordinate_descent import _alpha_grid
from sklearn.mixture import BayesianGaussianMixture
from sklearn.model_selection import cross_validate
from sklearn.naive_bayes import GaussianNB
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import LinearSVR
from sklearn.tree import DecisionTreeRegressor, DecisionTreeClassifier, _tree
from sympy import parse_expr, Piecewise, srepr
from pstree import cluster_gp_tools
from pstree.cluster_gp_tools import (
add_pset_function,
selAutomaticEpsilonLexicase,
selBestSum,
selMOEAD,
selIBEA,
c_deepcopy,
)
from pstree.common_utils import gene_to_string, reset_random
from pstree.custom_sklearn_tools import LassoRidge, RFERegressor
from pstree.gp_function import *
from pstree.gp_visualization_utils import multigene_gp_to_string
from pstree.multigene_gp import *
pyximport.install(setup_args={"include_dirs": np.get_include()})
class FeatureTransformer(TransformerMixin, BaseEstimator):
def __init__(self, compiled_individuals):
self.compiled_individuals = compiled_individuals
def fit(self, X, y=None):
return self
def transform(self, X, copy=None):
all_features = []
for func in self.compiled_individuals:
yp = func(*X.T)
if not isinstance(yp, np.ndarray) or yp.size == 1:
yp = np.full(len(X), yp)
all_features.append(np.squeeze(yp).reshape(-1, 1))
all_features = np.concatenate(all_features, axis=1)
return all_features
def train_normalization(func):
def call(self, X, y, *param, **dict_param):
if self.normalize:
X = self.x_scaler.fit_transform(X)
y = self.y_scaler.fit_transform(y.reshape(-1, 1)).squeeze()
result = func(self, X, y, *param, **dict_param)
return result
return call
def get_labels(tree, X, soft_tree=False):
if (
isinstance(tree, DecisionTreeClassifier)
or isinstance(tree, KMeans)
or isinstance(tree, BayesianGaussianMixture)
or isinstance(tree, GaussianNB)
or isinstance(tree, RandomForestClassifier)
or isinstance(tree, LogisticRegression)
):
if soft_tree:
if hasattr(tree, "predict_proba"):
tree.labels_ = tree.predict_proba(X)
else:
tree.labels_ = tree.predict(X).astype(int)
else:
tree.labels_ = tree.predict(X).astype(int)
elif isinstance(tree, DecisionTreeRegressor) or isinstance(tree, PseudoPartition):
tree.labels_ = tree.apply(X)
else:
print(type(tree))
raise Exception
return tree.labels_
def predict_normalization(func):
def call(self, X, y=None, *param, **dict_param):
if self.normalize:
X = self.x_scaler.transform(X)
y_predict = func(self, X, y, *param, **dict_param)
if self.normalize:
y_predict = np.reshape(y_predict, (-1, 1))
assert len(y_predict) == len(X)
y_predict = self.y_scaler.inverse_transform(y_predict)
return y_predict
return call
class NormalizationRegressor(BaseEstimator, RegressorMixin):
def __init__(self, normalize=True, **params):
self.normalize = normalize
if normalize:
self.x_scaler = StandardScaler()
self.y_scaler = StandardScaler()
def represents_int(s):
try:
int(s)
return True
except ValueError:
return False
class FastMeasure(Fitness):
def __init__(self, values=()):
super().__init__(values)
self._values = None
def getValues(self):
if self._values is None:
self._values = tuple(map(operator.truediv, self.wvalues, self.weights))
return self._values
def setValues(self, values):
try:
self.wvalues = tuple(map(operator.mul, values, self.weights))
self._values = tuple(map(operator.truediv, self.wvalues, self.weights))
except TypeError:
_, _, traceback = sys.exc_info()
raise TypeError(
"Both weights and assigned values must be a "
"sequence of numbers when assigning to values of "
"%r. Currently assigning value(s) %r of %r to a "
"fitness with weights %s."
% (self.__class__, values, type(values), self.weights)
).with_traceback(traceback)
def delValues(self):
self.wvalues = ()
self._values = ()
values = property(
getValues,
setValues,
delValues,
(
"Fitness values. Use directly ``individual.fitness.values = values`` "
"in order to set the fitness and ``del individual.fitness.values`` "
"in order to clear (invalidate) the fitness. The (unweighted) fitness "
"can be directly accessed via ``individual.fitness.values``."
),
)
class EnsembleRidge(RidgeCV):
def __init__(self, alphas=None):
super().__init__()
self.model = BaggingRegressor(RidgeCV(alphas=alphas), n_estimators=3)
def fit(self, X, y, sample_weight=None):
self.model.fit(X, y)
self.coef_ = np.mean([m.coef_ for m in self.model.estimators_], axis=0)
self.best_score_ = np.mean(
[m.best_score_ for m in self.model.estimators_], axis=0
)
return self
def predict(self, X):
return self.model.predict(X)
def get_terminal_order(node, context=None):
if (
isinstance(node, gp.MetaEphemeral)
or isinstance(node.value, float)
or isinstance(node.value, int)
or context is not None
and node.value in context
):
return 0
return 1
def calculate_order(ind, context=None):
# calculate the complexity of model as a regularization term
order_stack = []
for node in reversed(ind):
if isinstance(node, gp.Terminal):
terminal_order = get_terminal_order(node, context)
order_stack.append(terminal_order)
elif node.arity == 1:
# sin, cos, tanh
arg_order = order_stack.pop()
order_stack.append(2 * arg_order)
else: # node.arity == 2:
args_order = [order_stack.pop() for _ in range(node.arity)]
if node.name.startswith("add") or node.name.startswith("sub"):
order_stack.append(max(args_order))
else:
order_stack.append(sum(args_order))
return order_stack.pop()
class GPRegressor(NormalizationRegressor):
def __init__(
self,
input_names=None,
n_pop=50,
n_gen=200,
max_arity=2,
height_limit=6,
constant_range=2,
cross_rate=0.9,
mutate_rate=0.1,
verbose=False,
basic_primitive=True,
gene_num=1,
random_float=False,
log_dict_size=int(1e9),
archive_size=None,
category_num=1,
cluster_gp=True,
select=selRandom,
test_fun=None,
train_test_fun=None,
samples=20,
min_samples_leaf=1,
max_depth=None,
linear_scale=False,
regression_type=None,
regression_regularization=0,
score_function=None,
validation_selection=True,
ridge_alpha="np.logspace(0, 4)",
survival_selection="NSGA2",
feature_normalization=True,
structure_diversity=True,
space_partition_fun=None,
adaptive_tree=True,
original_features=True,
new_surrogate_function=True,
advanced_elimination=True,
super_object=None,
final_prune="Lasso",
correlation_elimination=False,
tree_shrinkage=False,
size_objective=True,
soft_label=False,
initial_height=None,
afp=False,
complexity_measure=False,
parsimonious_variable=False,
**params,
):
"""
:param n_pop: size of population
:param n_gen: number of generations
"""
super().__init__(**params)
self.initial_height = initial_height
self.soft_label = soft_label
self.average_size = sys.maxsize
self.advanced_elimination = advanced_elimination
self.new_surrogate_function = new_surrogate_function
self.structure_diversity = structure_diversity
self.adaptive_tree = adaptive_tree
self.validation_selection = validation_selection
self.ridge_alpha = ridge_alpha
self.score_function = score_function
self.regression_type = regression_type
self.regression_regularization = regression_regularization
self.afp = afp
self.complexity_measure = complexity_measure
self.parsimonious_variable = parsimonious_variable
if hasattr(creator, "FitnessMin"):
del creator.FitnessMin
if hasattr(creator, "Individual"):
del creator.Individual
self.toolbox = None
self.category_num = category_num
# "cluster_gp" is the decisive control parameter
self.cluster_gp = cluster_gp
self.test_fun = test_fun
self.train_test_fun = train_test_fun
self.samples = samples
self.best_distribution_test = None
self.linear_scale = linear_scale
self.min_samples_leaf = min_samples_leaf
self.max_depth = max_depth
self.accuracy_list = []
self.select = select
self.pipelines = []
self.best_cv = np.inf
self.best_pop = None
self.best_leaf_node_num = None
self.best_tree = None
self.survival_selection = survival_selection
self.archive_size = archive_size
self.input_names = input_names
self.n_pop = n_pop
self.n_gen = n_gen
self.max_arity = max_arity
self.verbose = verbose
self.basic_primitive = basic_primitive
self.params = params
self.height_limit = height_limit
self.constant_range = constant_range
self.cross_rate = cross_rate
self.mutate_rate = mutate_rate
self.gene_num = gene_num
self.random_float = random_float
self.log_dict_size = log_dict_size
self.feature_normalization = feature_normalization
self.space_partition_fun = space_partition_fun
self.original_features = original_features
self.update_iteration = []
self.current_gen = 0
self.better_pop_flag = False
self.super_object: PSTreeRegressor = super_object
self.last_loss = None
self.final_prune = final_prune
self.size_objective = size_objective
self.tree_shrinkage = tree_shrinkage
self.correlation_elimination = correlation_elimination
def get_predicted_list(self, pop):
predicted_list = []
for ind in pop:
predicted_list.append(ind.predicted_value)
return predicted_list
def evaluate(self, individuals, final_model=None):
compiled_individuals = [
self.toolbox.compile(individual) for individual in individuals
]
all_features = self.feature_construction(compiled_individuals, self.train_data)
fitness, pipelines, score = self.model_construction(all_features, final_model)
if self.verbose:
print("score", score / len(self.Y))
# correlation = np.corrcoef(np.array([p['Ridge'].coef_ for p in pipelines]))
self.adaptive_tree_generation(
self.feature_construction(
compiled_individuals, self.train_data, self.original_features
),
pipelines,
)
if (
(self.validation_selection and score < self.best_cv)
or (not self.validation_selection)
or (final_model != None)
):
# record the best individual in the training process
self.update_iteration.append((self.current_gen, score / len(self.Y)))
self.best_cv = score
self.pipelines = pipelines
self.best_pop = individuals[:]
self.better_pop_flag = True
if self.adaptive_tree:
self.best_features = all_features
self.best_label = self.category
self.best_leaf_node_num = self.super_object.max_leaf_nodes
# assert len(pipelines) == category_num + 1, f"{category_num + 1},{len(pipelines)}"
fitness = np.array(fitness)
assert len(fitness.shape) == 2, fitness.shape
fitness_dimension = len(pipelines)
for i, ind in enumerate(individuals):
target_dimension = fitness_dimension
fitness_values = tuple(np.abs(fitness[:, i]))
if self.size_objective:
target_dimension += 1
fitness_values = fitness_values + (
-0.01 * max(len(ind), self.average_size) / self.average_size,
)
if self.afp:
target_dimension += 1
fitness_values = fitness_values + (ind.age,)
ind.age -= 1
if self.complexity_measure:
target_dimension += 1
fitness_values = fitness_values + (-1 * calculate_order(ind),)
if self.parsimonious_variable:
target_dimension += 1
variable_length = len(
set(
map(
lambda x: x.name,
filter(
lambda x: isinstance(x, Terminal)
and not isinstance(x, MetaEphemeral),
ind,
),
)
)
)
fitness_values = fitness_values + (-1 * variable_length,)
ind.fitness.weights = tuple([1 for _ in range(target_dimension)])
ind.fitness.values = fitness_values
assert len(ind.fitness.values) == target_dimension
assert len(ind.fitness.wvalues) == target_dimension
return tuple(fitness)
def model_construction(self, all_features, final_model):
fitness = []
pipelines = []
score = 0
if len(self.category.shape) == 1:
category_num = np.max(self.category)
else:
category_num = self.category.shape[1] - 1
def dummy_regressor_construction(x, y):
coef = np.zeros(x.shape[1])
constant = np.mean(y)
regr = Pipeline(
[
("Scaler", StandardScaler()),
("Ridge", DummyRegressor(strategy="constant", constant=constant)),
]
)
regr.fit(features, y)
regr["Ridge"].coef_ = coef
regr["Ridge"].intercept_ = constant
# append coefficients and pipelines to the archive
fitness.append(coef)
pipelines.append(regr)
return coef, regr
for i in range(category_num + 1):
def check_rule(x):
# if number of samples <2 :unable to execute leave-one CV
# if number of samples <10 :unable to execute 5-fold CV
if x < 2 or (
x < 10
and not (self.ridge_alpha == "RidgeCV" and final_model == None)
):
return True
else:
return False
if len(self.category.shape) == 1:
category = self.category == i
Y_true = self.Y[category]
features = all_features[category]
if check_rule(np.sum(category)):
dummy_regressor_construction(features, Y_true)
continue
else:
# soft decision tree
Y_true = self.Y
features = all_features
if check_rule(np.count_nonzero(self.category[:, i])):
dummy_regressor_construction(features, Y_true)
continue
# if (np.sum(category) < all_features.shape[1] and self.adaptive_tree) or (np.sum(category) < 5):
# warnings.simplefilter("ignore", category=ConvergenceWarning)
def get_lasso():
alphas = _alpha_grid(features, Y_true)
ridge_model = ElasticNet(
alpha=1, lambda_path=alphas, n_splits=5, tol=1e-4, random_state=0
)
return ridge_model
def get_elastic_net(ratio):
alphas = _alpha_grid(features, Y_true, l1_ratio=ratio)
ridge_model = ElasticNet(
alpha=ratio,
lambda_path=alphas,
n_splits=5,
tol=1e-4,
random_state=0,
)
return ridge_model
# determine the evaluation model
if self.ridge_alpha == "Lasso":
ridge_model = get_lasso()
elif self.ridge_alpha == "Linear":
ridge_model = LinearRegression()
elif "ElasticNet" in self.ridge_alpha:
ratio = float(self.ridge_alpha.split("-")[1])
ridge_model = get_elastic_net(ratio)
elif self.ridge_alpha == "LinearSVR":
ridge_model = LinearSVR()
elif self.ridge_alpha == "EnsembleRidge":
ridge_model = EnsembleRidge(np.logspace(0, 4))
else:
# default use this option
ridge_model = RidgeCV(alphas=eval(self.ridge_alpha))
# determine the final model
if final_model == "Lasso":
# default use this option
ridge_model = get_lasso()
elif final_model == "ElasticNet":
ridge_model = get_elastic_net(0.5)
elif final_model == "LassoRidge":
ridge_model = LassoRidge(get_lasso(), ridge_model)
elif final_model == "RFE":
ridge_model = RFERegressor(get_lasso(), n_features_to_select=10, step=5)
if self.feature_normalization:
steps = [
("Scaler", StandardScaler()),
("Ridge", ridge_model),
]
pipe = Pipeline(steps)
else:
pipe = Pipeline(
[
("Ridge", ridge_model),
]
)
if self.validation_selection:
# record the best individual in the training process
ridge: RidgeCV = pipe["Ridge"]
try:
if len(self.category.shape) == 1:
pipe.fit(features, Y_true)
else:
weight = np.nan_to_num(self.category[:, i], posinf=0, neginf=0)
pipe.fit(features, Y_true, Ridge__sample_weight=weight)
except Exception as e:
traceback.print_exc()
ic(e, features.shape, Y_true.shape)
# not converge
dummy_regressor_construction(features, Y_true)
continue
if isinstance(ridge, RidgeCV):
if len(self.category.shape) == 1:
score += abs(len(Y_true) * ridge.best_score_)
else:
score += abs(np.sum(self.category[:, i]) * ridge.best_score_)
elif isinstance(ridge, ElasticNet):
if len(self.category.shape) == 1:
score += -1 * abs(len(Y_true) * np.max(ridge.cv_mean_score_))
else:
score += -1 * abs(
np.sum(self.category[:, i]) * np.max(ridge.cv_mean_score_)
)
elif isinstance(ridge, LassoCV):
score += abs(len(Y_true) * np.min(np.sum(ridge.mse_path_, axis=1)))
elif isinstance(ridge, ElasticNetCV):
score += abs(len(Y_true) * np.min(np.sum(ridge.mse_path_, axis=1)))
elif isinstance(ridge, RFERegressor):
score += 0
elif isinstance(ridge, LassoRidge):
score += 0
else:
raise Exception
if isinstance(ridge, ElasticNet):
feature_importances = np.mean(np.abs(ridge.coef_path_), axis=1)
else:
feature_importances = np.abs(ridge.coef_)
else:
pipe.fit(features, np.squeeze(Y_true))
feature_importances = np.abs(pipe["Ridge"].coef_)
fitness.append(feature_importances)
pipelines.append(pipe)
return fitness, pipelines, score
def feature_construction(self, compiled_individuals, x, original_features=False):
# construct all features
if original_features:
all_features = [x]
else:
all_features = []
for func in compiled_individuals:
yp = func(*x.T)
if not isinstance(yp, np.ndarray) or yp.size == 1:
yp = np.full(len(x), yp)
all_features.append(np.squeeze(yp).reshape(-1, 1))
all_features = np.concatenate(all_features, axis=1)
all_features = np.nan_to_num(all_features, posinf=0, neginf=0)
return all_features
def adaptive_tree_generation(self, all_features, pipelines):
# adaptively generate new partition scheme
if self.adaptive_tree:
if self.soft_label:
original_all_features = all_features
prob = softmax(
np.array(
[
(
p.predict(all_features[:, self.train_data.shape[1] :])
- self.Y
)
** 2
* -1
for p in pipelines
]
),
axis=0,
)
sample = np.random.rand(len(pipelines), all_features.shape[0])
matrix = prob > sample
features = np.concatenate([all_features[s] for s in matrix], axis=0)
label = np.concatenate(
[np.full(np.sum(s == True), i) for i, s in enumerate(matrix)],
axis=0,
)
all_features = features
_, decision_tree = self.space_partition_fun(all_features, label)
self.category = decision_tree.predict_proba(original_all_features)
# decision_tree.labels_ = self.category
else:
# assign data point to new partitions
label = np.zeros(len(self.Y))
best_fitness = np.full(len(self.Y), np.inf)
for i, p in enumerate(pipelines):
# np.array([(p.predict(all_features[:, self.train_data.shape[1]:]) - self.Y) ** 2 for p in pipelines])
if self.original_features:
loss = (
p.predict(all_features[:, self.train_data.shape[1] :])
- self.Y
) ** 2
else:
loss = (p.predict(all_features) - self.Y) ** 2
label[loss < best_fitness] = i
best_fitness[loss < best_fitness] = loss[loss < best_fitness]
self.category, decision_tree = self.space_partition_fun(
all_features, label
)
def statistic_fun(self, ind):
# return loss and time
if self.test_fun is not None:
if not self.better_pop_flag:
return self.last_loss
self.better_pop_flag = False
train_test_loss = self.train_test_fun.predict_loss()
test_loss = self.test_fun.predict_loss()
self.last_loss = (train_test_loss, time.time(), test_loss)
return self.last_loss
return (time.time(),)
def fit(self, X, y=None, category=None):
if not hasattr(self, "fit_function"):
raise Exception("Fit function must be specified!")
if (not hasattr(self, "input_names")) or (self.input_names is None):
self.input_names = [f"X{i}" for i in range(X.shape[1])]
self.train_data = X
self.Y = y
verbose = self.verbose
if verbose:
self.stats = tools.Statistics(key=lambda ind: ind.fitness.values)
self.stats.register("avg", np.mean, axis=0)
self.stats.register("std", np.std, axis=0)
self.stats.register("min", np.min, axis=0)
self.stats.register("max", np.max, axis=0)
else:
self.stats = tools.Statistics(key=self.statistic_fun)
self.stats.register("min", np.min, axis=0)
self.stats.register("max", np.max, axis=0)
backup_X = X.copy()
backup_y = y.copy()
self.lazy_init(self.input_names)
if category is None:
category = np.full([y.shape[0]], 0)
self.category = category
self.fit_function()
assert np.all(backup_X == X), "Data has been changed unexpected!"
assert np.all(backup_y == y), "Data has been changed unexpected!"
return self
def feature_synthesis(self, x, pop, original_features=False):
compiled_pop = [self.toolbox.compile(individual) for individual in pop]
return self.feature_construction(compiled_pop, x, original_features)
def predict(self, X, y=None, category=None):
# save_object([str(x) for x in self.hof.items], 'model.pkl')
if (category is None) or (not self.cluster_gp):
category = np.full([X.shape[0]], 0)
Yp = np.zeros(X.shape[0])
if len(category.shape) == 1:
category_num = np.max(category)
else:
category_num = category.shape[1] - 1
X = self.feature_synthesis(X, self.best_pop)
for i in range(category_num + 1):
if len(category.shape) == 1:
loc = np.where(category == i)
current_c = category == i
if np.sum(current_c) == -0:
continue
features = X[current_c]
else:
features = X
if len(features.shape) == 1:
features = features.reshape(1, len(features))
assert features.shape[1] >= len(self.best_pop), features.shape[1]
if len(category.shape) == 1:
Yp.put(loc, self.pipelines[i].predict(features))
else:
Yp += np.multiply(self.pipelines[i].predict(features), category[:, i])
return Yp
def __deepcopy__(self, memodict={}):
return c_deepcopy(self)
def lazy_init(self, input_names):
pset = gp.PrimitiveSet("MAIN", len(input_names), prefix="X")
toolbox = base.Toolbox()
toolbox.register("evaluate", self.evaluate)
toolbox.register("select", self.select)
self.pset = pset
self.toolbox = toolbox
add_pset_function(pset, self.max_arity, self.basic_primitive)
if hasattr(gp, "rand101"):
# delete existing constant generator
delattr(gp, "rand101")
if self.random_float:
pset.addEphemeralConstant(
"rand101",
lambda: random.uniform(-self.constant_range, self.constant_range),
)
else:
pset.addEphemeralConstant(
"rand101",
lambda: random.randint(-self.constant_range, self.constant_range),
)
number_of_objective = self.category_num
creator.create(
"FitnessMin",
FastMeasure,
weights=tuple([1 for _ in range(number_of_objective)]),
)
creator.create(
"Individual", gp.PrimitiveTree, fitness=creator.FitnessMin, age=0
)
if self.initial_height is None:
toolbox.register("expr", gp.genHalfAndHalf, pset=pset, min_=0, max_=2)
else:
a, b = self.initial_height.split("-")
a, b = int(a), int(b)
toolbox.register("expr", gp.genHalfAndHalf, pset=pset, min_=a, max_=b)
toolbox.register(
"individual", tools.initIterate, creator.Individual, toolbox.expr
)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
toolbox.register("compile", gp.compile, pset=pset)
toolbox.register("expr_mut", gp.genFull, min_=0, max_=2)
toolbox.register("mate", gp.cxOnePoint)
toolbox.register("mutate", gp.mutUniform, expr=toolbox.expr_mut, pset=pset)
toolbox.decorate(
"mate",
gp.staticLimit(
key=operator.attrgetter("height"), max_value=self.height_limit
),
)
toolbox.decorate(
"mutate",
gp.staticLimit(
key=operator.attrgetter("height"), max_value=self.height_limit
),
)
if self.n_gen == 0:
self.pop = self.generation_original_features()
else:
self.pop = toolbox.population(n=self.n_pop)
def generation_original_features(self):
pop = []
for x in self.pset.terminals[object]:
if type(x) is Terminal:
tree = gp.PrimitiveTree([x])
tree.fitness = creator.FitnessMin()
pop.append(tree)
assert len(pop) == self.train_data.shape[1]
return pop
def fit_function(self):
self.pop, self.log_book = self.moea(
self.pop,
self.toolbox,
self.cross_rate,
self.mutate_rate,
self.n_gen,
stats=self.stats,
halloffame=None,
verbose=self.verbose,
params=self.params,
)
def moea(
self,
population,
toolbox,
cxpb,
mutpb,
ngen,
stats=None,
halloffame=None,
verbose=__debug__,
params=None,
):
if self.new_surrogate_function is True:
def individual_to_tuple(ind):
return tuple(
self.feature_synthesis(self.train_data[:20], [ind])
.flatten()
.tolist()
)
elif str(self.new_surrogate_function).startswith("First"):
sample_count = int(self.new_surrogate_function.split("-")[1])
def individual_to_tuple(ind):
return tuple(
self.feature_synthesis(self.train_data[:sample_count], [ind])
.flatten()
.tolist()
)
else:
individual_to_tuple = cluster_gp_tools.individual_to_tuple
logbook = tools.Logbook()
logbook.header = ["gen", "nevals"] + (stats.fields if stats else [])
# Evaluate the individuals with an invalid fitness
toolbox.evaluate(population)
if halloffame is not None:
halloffame.update(population)
record = stats.compile(population) if stats else {}
logbook.record(gen=0, nevals=len(population), **record)
if verbose:
print(logbook.stream)
diversity_list = []
pop_size_list = []
log_dict = LogDict(self.log_dict_size * len(population))
for p in population:
ind_tuple = individual_to_tuple(p)
p.ind_tuple = ind_tuple
log_dict.insert(ind_tuple, p.fitness.values)
pop_size = len(population)
# assigning the crowding distance to each individual
if self.select == selTournamentDCD and self.survival_selection == "NSGA2":
population = selNSGA2(population, pop_size)
# Begin the generational process
for gen in range(1, ngen + 1):
if self.basic_primitive == "dynamic" and self.current_gen > (
self.n_gen // 2
):
self.pset.addPrimitive(np.sin, 1)
self.pset.addPrimitive(np.cos, 1)
if self.tree_shrinkage and (gen % 50) == 0:
self.super_object.max_leaf_nodes = max(
self.super_object.max_leaf_nodes // 2, 1
)
self.current_gen = gen
if self.structure_diversity:
count = 0
new_offspring = []
while len(new_offspring) < pop_size:
count += 1
# Select the next generation individuals
# if self.survival_selection == 'Random':
# offspring = selRandom(population, 2)
# else:
offspring = toolbox.select(population, 2)
offspring = offspring[:]
parent_tuple = [o.ind_tuple for o in offspring]
# Vary the pool of individuals
offspring = varAnd(offspring, toolbox, cxpb, mutpb)
for o in offspring:
if len(new_offspring) < pop_size:
ind_tuple = individual_to_tuple(o)
if count > pop_size * 50:
# if too many trials failed, then we just allow to use repetitive individuals
o.ind_tuple = ind_tuple
log_dict.insert(ind_tuple, -1)
new_offspring.append(o)
continue
if not log_dict.exist(ind_tuple):
if self.advanced_elimination and (
np.abs(pearsonr(ind_tuple, parent_tuple[0])[0])
>= 0.95
or np.abs(pearsonr(ind_tuple, parent_tuple[1])[0])
>= 0.95
):
log_dict.insert(ind_tuple, -1)
continue
o.ind_tuple = ind_tuple
log_dict.insert(ind_tuple, -1)
new_offspring.append(o)
offspring = new_offspring
else:
offspring = toolbox.select(population, len(population))
# Vary the pool of individuals
offspring = varAnd(offspring, toolbox, cxpb, mutpb)
assert len(offspring) == pop_size, print(len(offspring), pop_size)
self.average_size = np.mean([len(p) for p in population])
if self.afp:
# reset the age of new individuals
for o in offspring:
o.age = 0
# Evaluate the individuals with an invalid fitness
if self.correlation_elimination:
corr_matrix = np.abs(
np.corrcoef(np.array([p.ind_tuple for p in population + offspring]))
)
# Select upper triangle of correlation matrix
upper = np.triu(corr_matrix, k=1)
# Find index of feature columns with correlation greater than 0.95
to_drop = [any(upper[i] > 0.95) for i in range(0, upper.shape[0])]
parent = list(compress(population + offspring, np.invert(to_drop)))
toolbox.evaluate(parent)
else:
toolbox.evaluate(offspring + population)
# diversity = diversity_measure(offspring) / pop_size
# diversity_list.append(diversity)
pop_size_list.append(len(offspring))
log_dict.gc()
# Update the hall of fame with the generated individuals
if halloffame is not None:
halloffame.update(offspring)
# Replace the current population by the offspring
if self.survival_selection == "NSGA2":
# if len(offspring[0].fitness.wvalues) > 2:
# high_dimensional = True
# self.random_objectives = np.random.uniform(0, 1, size=(len(offspring[0].fitness.wvalues), 2))
# for ind in offspring + population:
# setattr(ind, 'original_fitness', ind.fitness.values)
# setattr(ind, 'original_weights', ind.fitness.weights)
# fitness = np.array(ind.fitness.wvalues) @ self.random_objectives
# ind.fitness.weights = (1,) * len(fitness)
# ind.fitness.values = list(fitness)
# else:
# high_dimensional = False
if self.correlation_elimination:
population[:] = selNSGA2(parent, pop_size)
else:
population[:] = selNSGA2(population + offspring, pop_size)
# population = list(filter(lambda x: np.sum(x.fitness.wvalues) > 0, population))
# if high_dimensional: