-
Notifications
You must be signed in to change notification settings - Fork 15
/
de.py
810 lines (711 loc) · 34.6 KB
/
de.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
import os
import numpy as np
import ConfigSpace
import ConfigSpace.util
from typing import List
from distributed import Client
class DEBase():
'''Base class for Differential Evolution
'''
def __init__(self, cs=None, f=None, dimensions=None, pop_size=None, max_age=None,
mutation_factor=None, crossover_prob=None, strategy=None, budget=None,
boundary_fix_type='random', **kwargs):
# Benchmark related variables
self.cs = cs
self.f = f
if dimensions is None and self.cs is not None:
self.dimensions = len(self.cs.get_hyperparameters())
else:
self.dimensions = dimensions
# DE related variables
self.pop_size = pop_size
self.max_age = max_age
self.mutation_factor = mutation_factor
self.crossover_prob = crossover_prob
self.strategy = strategy
self.budget = budget
self.fix_type = boundary_fix_type
# Miscellaneous
self.configspace = True if isinstance(self.cs, ConfigSpace.ConfigurationSpace) else False
self.hps = dict()
if self.configspace:
for i, hp in enumerate(cs.get_hyperparameters()):
# maps hyperparameter name to positional index in vector form
self.hps[hp.name] = i
self.output_path = kwargs['output_path'] if 'output_path' in kwargs else './'
os.makedirs(self.output_path, exist_ok=True)
# Global trackers
self.inc_score = np.inf
self.inc_config = None
self.population = None
self.fitness = None
self.age = None
self.history = []
def reset(self):
self.inc_score = np.inf
self.inc_config = None
self.population = None
self.fitness = None
self.age = None
self.history = []
def _shuffle_pop(self):
pop_order = np.arange(len(self.population))
np.random.shuffle(pop_order)
self.population = self.population[pop_order]
self.fitness = self.fitness[pop_order]
self.age = self.age[pop_order]
def _sort_pop(self):
pop_order = np.argsort(self.fitness)
np.random.shuffle(pop_order)
self.population = self.population[pop_order]
self.fitness = self.fitness[pop_order]
self.age = self.age[pop_order]
def _set_min_pop_size(self):
if self.mutation_strategy in ['rand1', 'rand2dir', 'randtobest1']:
self._min_pop_size = 3
elif self.mutation_strategy in ['currenttobest1', 'best1']:
self._min_pop_size = 2
elif self.mutation_strategy in ['best2']:
self._min_pop_size = 4
elif self.mutation_strategy in ['rand2']:
self._min_pop_size = 5
else:
self._min_pop_size = 1
return self._min_pop_size
def init_population(self, pop_size: int) -> List:
if self.configspace:
# sample from ConfigSpace s.t. conditional constraints (if any) are maintained
population = self.cs.sample_configuration(size=pop_size)
if not isinstance(population, List):
population = [population]
# the population is maintained in a list-of-vector form where each ConfigSpace
# configuration is scaled to a unit hypercube, i.e., all dimensions scaled to [0,1]
population = [self.configspace_to_vector(individual) for individual in population]
else:
# if no ConfigSpace representation available, uniformly sample from [0, 1]
population = np.random.uniform(low=0.0, high=1.0, size=(pop_size, self.dimensions))
return np.array(population)
def sample_population(self, size: int = 3, alt_pop: List = None) -> List:
'''Samples 'size' individuals
If alt_pop is None or a list/array of None, sample from own population
Else sample from the specified alternate population (alt_pop)
'''
if isinstance(alt_pop, list) or isinstance(alt_pop, np.ndarray):
idx = [indv is None for indv in alt_pop]
if any(idx):
selection = np.random.choice(np.arange(len(self.population)), size, replace=False)
return self.population[selection]
else:
if len(alt_pop) < 3:
alt_pop = np.vstack((alt_pop, self.population))
selection = np.random.choice(np.arange(len(alt_pop)), size, replace=False)
alt_pop = np.stack(alt_pop)
return alt_pop[selection]
else:
selection = np.random.choice(np.arange(len(self.population)), size, replace=False)
return self.population[selection]
def boundary_check(self, vector: np.array) -> np.array:
'''
Checks whether each of the dimensions of the input vector are within [0, 1].
If not, values of those dimensions are replaced with the type of fix selected.
if fix_type == 'random', the values are replaced with a random sampling from (0,1)
if fix_type == 'clip', the values are clipped to the closest limit from {0, 1}
Parameters
----------
vector : array
Returns
-------
array
'''
violations = np.where((vector > 1) | (vector < 0))[0]
if len(violations) == 0:
return vector
if self.fix_type == 'random':
vector[violations] = np.random.uniform(low=0.0, high=1.0, size=len(violations))
else:
vector[violations] = np.clip(vector[violations], a_min=0, a_max=1)
return vector
def vector_to_configspace(self, vector: np.array) -> ConfigSpace.Configuration:
'''Converts numpy array to ConfigSpace object
Works when self.cs is a ConfigSpace object and the input vector is in the domain [0, 1].
'''
# creates a ConfigSpace object dict with all hyperparameters present, the inactive too
new_config = ConfigSpace.util.impute_inactive_values(
self.cs.sample_configuration()
).get_dictionary()
# iterates over all hyperparameters and normalizes each based on its type
for i, hyper in enumerate(self.cs.get_hyperparameters()):
if type(hyper) == ConfigSpace.OrdinalHyperparameter:
ranges = np.arange(start=0, stop=1, step=1/len(hyper.sequence))
param_value = hyper.sequence[np.where((vector[i] < ranges) == False)[0][-1]]
elif type(hyper) == ConfigSpace.CategoricalHyperparameter:
ranges = np.arange(start=0, stop=1, step=1/len(hyper.choices))
param_value = hyper.choices[np.where((vector[i] < ranges) == False)[0][-1]]
else: # handles UniformFloatHyperparameter & UniformIntegerHyperparameter
# rescaling continuous values
if hyper.log:
log_range = np.log(hyper.upper) - np.log(hyper.lower)
param_value = np.exp(np.log(hyper.lower) + vector[i] * log_range)
else:
param_value = hyper.lower + (hyper.upper - hyper.lower) * vector[i]
if type(hyper) == ConfigSpace.UniformIntegerHyperparameter:
param_value = int(np.round(param_value)) # converting to discrete (int)
else:
param_value = float(param_value)
new_config[hyper.name] = param_value
# the mapping from unit hypercube to the actual config space may lead to illegal
# configurations based on conditions defined, which need to be deactivated/removed
new_config = ConfigSpace.util.deactivate_inactive_hyperparameters(
configuration = new_config, configuration_space=self.cs
)
return new_config
def configspace_to_vector(self, config: ConfigSpace.Configuration) -> np.array:
'''Converts ConfigSpace object to numpy array scaled to [0,1]
Works when self.cs is a ConfigSpace object and the input config is a ConfigSpace object.
Handles conditional spaces implicitly by replacing illegal parameters with default values
to maintain the dimensionality of the vector.
'''
# the imputation replaces illegal parameter values with their default
config = ConfigSpace.util.impute_inactive_values(config)
dimensions = len(self.cs.get_hyperparameters())
vector = [np.nan for i in range(dimensions)]
for name in config:
i = self.hps[name]
hyper = self.cs.get_hyperparameter(name)
if type(hyper) == ConfigSpace.OrdinalHyperparameter:
nlevels = len(hyper.sequence)
vector[i] = hyper.sequence.index(config[name]) / nlevels
elif type(hyper) == ConfigSpace.CategoricalHyperparameter:
nlevels = len(hyper.choices)
vector[i] = hyper.choices.index(config[name]) / nlevels
else:
bounds = (hyper.lower, hyper.upper)
param_value = config[name]
if hyper.log:
vector[i] = np.log(param_value / bounds[0]) / np.log(bounds[1] / bounds[0])
else:
vector[i] = (config[name] - bounds[0]) / (bounds[1] - bounds[0])
return np.array(vector)
def f_objective(self):
raise NotImplementedError("The function needs to be defined in the sub class.")
def mutation(self):
raise NotImplementedError("The function needs to be defined in the sub class.")
def crossover(self):
raise NotImplementedError("The function needs to be defined in the sub class.")
def evolve(self):
raise NotImplementedError("The function needs to be defined in the sub class.")
def run(self):
raise NotImplementedError("The function needs to be defined in the sub class.")
class DE(DEBase):
def __init__(self, cs=None, f=None, dimensions=None, pop_size=20, max_age=np.inf,
mutation_factor=None, crossover_prob=None, strategy='rand1_bin',
budget=None, encoding=False, dim_map=None, **kwargs):
super().__init__(cs=cs, f=f, dimensions=dimensions, pop_size=pop_size, max_age=max_age,
mutation_factor=mutation_factor, crossover_prob=crossover_prob,
strategy=strategy, budget=budget, **kwargs)
if self.strategy is not None:
self.mutation_strategy = self.strategy.split('_')[0]
self.crossover_strategy = self.strategy.split('_')[1]
else:
self.mutation_strategy = self.crossover_strategy = None
self.encoding = encoding
self.dim_map = dim_map
self._set_min_pop_size()
def __getstate__(self):
""" Allows the object to picklable while having Dask client as a class attribute.
"""
d = dict(self.__dict__)
d["client"] = None # hack to allow Dask client to be a class attribute
d["logger"] = None # hack to allow logger object to be a class attribute
return d
def __del__(self):
""" Ensures a clean kill of the Dask client and frees up a port.
"""
if hasattr(self, "client") and isinstance(self, Client):
self.client.close()
def reset(self):
super().reset()
self.traj = []
self.runtime = []
self.history = []
def _set_min_pop_size(self):
if self.mutation_strategy in ['rand1', 'rand2dir', 'randtobest1']:
self._min_pop_size = 3
elif self.mutation_strategy in ['currenttobest1', 'best1']:
self._min_pop_size = 2
elif self.mutation_strategy in ['best2']:
self._min_pop_size = 4
elif self.mutation_strategy in ['rand2']:
self._min_pop_size = 5
else:
self._min_pop_size = 1
return self._min_pop_size
def map_to_original(self, vector):
dimensions = len(self.dim_map.keys())
new_vector = np.random.uniform(size=dimensions)
for i in range(dimensions):
new_vector[i] = np.max(np.array(vector)[self.dim_map[i]])
return new_vector
def f_objective(self, x, budget=None, **kwargs):
if self.f is None:
raise NotImplementedError("An objective function needs to be passed.")
if self.encoding:
x = self.map_to_original(x)
if self.configspace:
# converts [0, 1] vector to a ConfigSpace object
config = self.vector_to_configspace(x)
else:
# can insert custom scaling/transform function here
config = x.copy()
if budget is not None: # to be used when called by multi-fidelity based optimizers
res = self.f(config, budget=budget, **kwargs)
else:
res = self.f(config, **kwargs)
assert "fitness" in res
assert "cost" in res
return res
def init_eval_pop(self, budget=None, eval=True, **kwargs):
'''Creates new population of 'pop_size' and evaluates individuals.
'''
self.population = self.init_population(self.pop_size)
self.fitness = np.array([np.inf for i in range(self.pop_size)])
self.age = np.array([self.max_age] * self.pop_size)
traj = []
runtime = []
history = []
if not eval:
return traj, runtime, history
for i in range(self.pop_size):
config = self.population[i]
res = self.f_objective(config, budget, **kwargs)
self.fitness[i], cost = res["fitness"], res["cost"]
info = res["info"] if "info" in res else dict()
if self.fitness[i] < self.inc_score:
self.inc_score = self.fitness[i]
self.inc_config = config
traj.append(self.inc_score)
runtime.append(cost)
history.append((config.tolist(), float(self.fitness[i]), float(budget or 0), info))
return traj, runtime, history
def eval_pop(self, population=None, budget=None, **kwargs):
'''Evaluates a population
If population=None, the current population's fitness will be evaluated
If population!=None, this population will be evaluated
'''
pop = self.population if population is None else population
pop_size = self.pop_size if population is None else len(pop)
traj = []
runtime = []
history = []
fitnesses = []
costs = []
ages = []
for i in range(pop_size):
res = self.f_objective(pop[i], budget, **kwargs)
fitness, cost = res["fitness"], res["cost"]
info = res["info"] if "info" in res else dict()
if population is None:
self.fitness[i] = fitness
if fitness <= self.inc_score:
self.inc_score = fitness
self.inc_config = pop[i]
traj.append(self.inc_score)
runtime.append(cost)
history.append((pop[i].tolist(), float(fitness), float(budget or 0), info))
fitnesses.append(fitness)
costs.append(cost)
ages.append(self.max_age)
if population is None:
self.fitness = np.array(fitnesses)
return traj, runtime, history
else:
return traj, runtime, history, np.array(fitnesses), np.array(ages)
def mutation_rand1(self, r1, r2, r3):
'''Performs the 'rand1' type of DE mutation
'''
diff = r2 - r3
mutant = r1 + self.mutation_factor * diff
return mutant
def mutation_rand2(self, r1, r2, r3, r4, r5):
'''Performs the 'rand2' type of DE mutation
'''
diff1 = r2 - r3
diff2 = r4 - r5
mutant = r1 + self.mutation_factor * diff1 + self.mutation_factor * diff2
return mutant
def mutation_currenttobest1(self, current, best, r1, r2):
diff1 = best - current
diff2 = r1 - r2
mutant = current + self.mutation_factor * diff1 + self.mutation_factor * diff2
return mutant
def mutation_rand2dir(self, r1, r2, r3):
diff = r1 - r2 - r3
mutant = r1 + self.mutation_factor * diff / 2
return mutant
def mutation(self, current=None, best=None, alt_pop=None):
'''Performs DE mutation
'''
if self.mutation_strategy == 'rand1':
r1, r2, r3 = self.sample_population(size=3, alt_pop=alt_pop)
mutant = self.mutation_rand1(r1, r2, r3)
elif self.mutation_strategy == 'rand2':
r1, r2, r3, r4, r5 = self.sample_population(size=5, alt_pop=alt_pop)
mutant = self.mutation_rand2(r1, r2, r3, r4, r5)
elif self.mutation_strategy == 'rand2dir':
r1, r2, r3 = self.sample_population(size=3, alt_pop=alt_pop)
mutant = self.mutation_rand2dir(r1, r2, r3)
elif self.mutation_strategy == 'best1':
r1, r2 = self.sample_population(size=2, alt_pop=alt_pop)
if best is None:
best = self.population[np.argmin(self.fitness)]
mutant = self.mutation_rand1(best, r1, r2)
elif self.mutation_strategy == 'best2':
r1, r2, r3, r4 = self.sample_population(size=4, alt_pop=alt_pop)
if best is None:
best = self.population[np.argmin(self.fitness)]
mutant = self.mutation_rand2(best, r1, r2, r3, r4)
elif self.mutation_strategy == 'currenttobest1':
r1, r2 = self.sample_population(size=2, alt_pop=alt_pop)
if best is None:
best = self.population[np.argmin(self.fitness)]
mutant = self.mutation_currenttobest1(current, best, r1, r2)
elif self.mutation_strategy == 'randtobest1':
r1, r2, r3 = self.sample_population(size=3, alt_pop=alt_pop)
if best is None:
best = self.population[np.argmin(self.fitness)]
mutant = self.mutation_currenttobest1(r1, best, r2, r3)
return mutant
def crossover_bin(self, target, mutant):
'''Performs the binomial crossover of DE
'''
cross_points = np.random.rand(self.dimensions) < self.crossover_prob
if not np.any(cross_points):
cross_points[np.random.randint(0, self.dimensions)] = True
offspring = np.where(cross_points, mutant, target)
return offspring
def crossover_exp(self, target, mutant):
'''Performs the exponential crossover of DE
'''
n = np.random.randint(0, self.dimensions)
L = 0
while ((np.random.rand() < self.crossover_prob) and L < self.dimensions):
idx = (n+L) % self.dimensions
target[idx] = mutant[idx]
L = L + 1
return target
def crossover(self, target, mutant):
'''Performs DE crossover
'''
if self.crossover_strategy == 'bin':
offspring = self.crossover_bin(target, mutant)
elif self.crossover_strategy == 'exp':
offspring = self.crossover_exp(target, mutant)
return offspring
def selection(self, trials, budget=None, **kwargs):
'''Carries out a parent-offspring competition given a set of trial population
'''
traj = []
runtime = []
history = []
for i in range(len(trials)):
# evaluation of the newly created individuals
res = self.f_objective(trials[i], budget, **kwargs)
fitness, cost = res["fitness"], res["cost"]
info = res["info"] if "info" in res else dict()
# selection -- competition between parent[i] -- child[i]
## equality is important for landscape exploration
if fitness <= self.fitness[i]:
self.population[i] = trials[i]
self.fitness[i] = fitness
# resetting age since new individual in the population
self.age[i] = self.max_age
else:
# decreasing age by 1 of parent who is better than offspring/trial
self.age[i] -= 1
# updation of global incumbent for trajectory
if self.fitness[i] < self.inc_score:
self.inc_score = self.fitness[i]
self.inc_config = self.population[i]
traj.append(self.inc_score)
runtime.append(cost)
history.append((trials[i].tolist(), float(fitness), float(budget or 0), info))
return traj, runtime, history
def evolve_generation(self, budget=None, best=None, alt_pop=None, **kwargs):
'''Performs a complete DE evolution: mutation -> crossover -> selection
'''
trials = []
for j in range(self.pop_size):
target = self.population[j]
donor = self.mutation(current=target, best=best, alt_pop=alt_pop)
trial = self.crossover(target, donor)
trial = self.boundary_check(trial)
trials.append(trial)
trials = np.array(trials)
traj, runtime, history = self.selection(trials, budget, **kwargs)
return traj, runtime, history
def sample_mutants(self, size, population=None):
'''Generates 'size' mutants from the population using rand1
'''
if population is None:
population = self.population
elif len(population) < 3:
population = np.vstack((self.population, population))
old_strategy = self.mutation_strategy
self.mutation_strategy = 'rand1'
mutants = np.random.uniform(low=0.0, high=1.0, size=(size, self.dimensions))
for i in range(size):
mutant = self.mutation(current=None, best=None, alt_pop=population)
mutants[i] = self.boundary_check(mutant)
self.mutation_strategy = old_strategy
return mutants
def run(self, generations=1, verbose=False, budget=None, reset=True, **kwargs):
# checking if a run exists
if not hasattr(self, 'traj') or reset:
self.reset()
if verbose:
print("Initializing and evaluating new population...")
self.traj, self.runtime, self.history = self.init_eval_pop(budget=budget, **kwargs)
if verbose:
print("Running evolutionary search...")
for i in range(generations):
if verbose:
print("Generation {:<2}/{:<2} -- {:<0.7}".format(i+1, generations, self.inc_score))
traj, runtime, history = self.evolve_generation(budget=budget, **kwargs)
self.traj.extend(traj)
self.runtime.extend(runtime)
self.history.extend(history)
if verbose:
print("\nRun complete!")
return np.array(self.traj), np.array(self.runtime), np.array(self.history, dtype=object)
class AsyncDE(DE):
def __init__(self, cs=None, f=None, dimensions=None, pop_size=None, max_age=np.inf,
mutation_factor=None, crossover_prob=None, strategy='rand1_bin',
budget=None, async_strategy='immediate', **kwargs):
'''Extends DE to be Asynchronous with variations
Parameters
----------
async_strategy : str
'deferred' - target will be chosen sequentially from the population
the winner of the selection step will be included in the population only after
the entire population has had a selection step in that generation
'immediate' - target will be chosen sequentially from the population
the winner of the selection step is included in the population right away
'random' - target will be chosen randomly from the population for mutation-crossover
the winner of the selection step is included in the population right away
'worst' - the worst individual will be chosen as the target
the winner of the selection step is included in the population right away
{immediate, worst, random} implement Asynchronous-DE
'''
super().__init__(cs=cs, f=f, dimensions=dimensions, pop_size=pop_size, max_age=max_age,
mutation_factor=mutation_factor, crossover_prob=crossover_prob,
strategy=strategy, budget=budget, **kwargs)
if self.strategy is not None:
self.mutation_strategy = self.strategy.split('_')[0]
self.crossover_strategy = self.strategy.split('_')[1]
else:
self.mutation_strategy = self.crossover_strategy = None
self.async_strategy = async_strategy
assert self.async_strategy in ['immediate', 'random', 'worst', 'deferred'], \
"{} is not a valid choice for type of DE".format(self.async_strategy)
def _add_random_population(self, pop_size, population=None, fitness=[], age=[]):
'''Adds random individuals to the population
'''
new_pop = self.init_population(pop_size=pop_size)
new_fitness = np.array([np.inf] * pop_size)
new_age = np.array([self.max_age] * pop_size)
if population is None:
population = self.population
fitness = self.fitness
age = self.age
population = np.concatenate((population, new_pop))
fitness = np.concatenate((fitness, new_fitness))
age = np.concatenate((age, new_age))
return population, fitness, age
def _init_mutant_population(self, pop_size, population, target=None, best=None):
'''Generates pop_size mutants from the passed population
'''
mutants = np.random.uniform(low=0.0, high=1.0, size=(pop_size, self.dimensions))
for i in range(pop_size):
mutants[i] = self.mutation(current=target, best=best, alt_pop=population)
return mutants
def _sample_population(self, size=3, alt_pop=None, target=None):
'''Samples 'size' individuals for mutation step
If alt_pop is None or a list/array of None, sample from own population
Else sample from the specified alternate population
'''
population = None
if isinstance(alt_pop, list) or isinstance(alt_pop, np.ndarray):
idx = [indv is None for indv in alt_pop] # checks if all individuals are valid
if any(idx):
# default to the object's initialized population
population = self.population
else:
# choose the passed population
population = alt_pop
else:
# default to the object's initialized population
population = self.population
if target is not None and len(population) > 1:
# eliminating target from mutation sampling pool
# the target individual should not be a part of the candidates for mutation
for i, pop in enumerate(population):
if all(target == pop):
population = np.concatenate((population[:i], population[i + 1:]))
break
if len(population) < self._min_pop_size:
# compensate if target was part of the population and deleted earlier
filler = self._min_pop_size - len(population)
new_pop = self.init_population(pop_size=filler) # chosen in a uniformly random manner
population = np.concatenate((population, new_pop))
selection = np.random.choice(np.arange(len(population)), size, replace=False)
return population[selection]
def eval_pop(self, population=None, budget=None, **kwargs):
pop = self.population if population is None else population
pop_size = self.pop_size if population is None else len(pop)
traj = []
runtime = []
history = []
fitnesses = []
costs = []
ages = []
for i in range(pop_size):
res = self.f_objective(pop[i], budget, **kwargs)
fitness, cost = res["fitness"], res["cost"]
info = res["info"] if "info" in res else dict()
if population is None:
self.fitness[i] = fitness
if fitness <= self.inc_score:
self.inc_score = fitness
self.inc_config = pop[i]
traj.append(self.inc_score)
runtime.append(cost)
history.append((pop[i].tolist(), float(fitness), float(budget or 0), info))
fitnesses.append(fitness)
costs.append(cost)
ages.append(self.max_age)
return traj, runtime, history, np.array(fitnesses), np.array(ages)
def mutation(self, current=None, best=None, alt_pop=None):
'''Performs DE mutation
'''
if self.mutation_strategy == 'rand1':
r1, r2, r3 = self._sample_population(size=3, alt_pop=alt_pop, target=current)
mutant = self.mutation_rand1(r1, r2, r3)
elif self.mutation_strategy == 'rand2':
r1, r2, r3, r4, r5 = self._sample_population(size=5, alt_pop=alt_pop, target=current)
mutant = self.mutation_rand2(r1, r2, r3, r4, r5)
elif self.mutation_strategy == 'rand2dir':
r1, r2, r3 = self._sample_population(size=3, alt_pop=alt_pop, target=current)
mutant = self.mutation_rand2dir(r1, r2, r3)
elif self.mutation_strategy == 'best1':
r1, r2 = self._sample_population(size=2, alt_pop=alt_pop, target=current)
if best is None:
best = self.population[np.argmin(self.fitness)]
mutant = self.mutation_rand1(best, r1, r2)
elif self.mutation_strategy == 'best2':
r1, r2, r3, r4 = self._sample_population(size=4, alt_pop=alt_pop, target=current)
if best is None:
best = self.population[np.argmin(self.fitness)]
mutant = self.mutation_rand2(best, r1, r2, r3, r4)
elif self.mutation_strategy == 'currenttobest1':
r1, r2 = self._sample_population(size=2, alt_pop=alt_pop, target=current)
if best is None:
best = self.population[np.argmin(self.fitness)]
mutant = self.mutation_currenttobest1(current, best, r1, r2)
elif self.mutation_strategy == 'randtobest1':
r1, r2, r3 = self._sample_population(size=3, alt_pop=alt_pop, target=current)
if best is None:
best = self.population[np.argmin(self.fitness)]
mutant = self.mutation_currenttobest1(r1, best, r2, r3)
return mutant
def sample_mutants(self, size, population=None):
'''Samples 'size' mutants from the population
'''
if population is None:
population = self.population
mutants = np.random.uniform(low=0.0, high=1.0, size=(size, self.dimensions))
for i in range(size):
j = np.random.choice(np.arange(len(population)))
mutant = self.mutation(current=population[j], best=self.inc_config, alt_pop=population)
mutants[i] = self.boundary_check(mutant)
return mutants
def evolve_generation(self, budget=None, best=None, alt_pop=None, **kwargs):
'''Performs a complete DE evolution, mutation -> crossover -> selection
'''
traj = []
runtime = []
history = []
if self.async_strategy == 'deferred':
trials = []
for j in range(self.pop_size):
target = self.population[j]
donor = self.mutation(current=target, best=best, alt_pop=alt_pop)
trial = self.crossover(target, donor)
trial = self.boundary_check(trial)
trials.append(trial)
# selection takes place on a separate trial population only after
# one iteration through the population has taken place
trials = np.array(trials)
traj, runtime, history = self.selection(trials, budget, **kwargs)
return traj, runtime, history
elif self.async_strategy == 'immediate':
for i in range(self.pop_size):
target = self.population[i]
donor = self.mutation(current=target, best=best, alt_pop=alt_pop)
trial = self.crossover(target, donor)
trial = self.boundary_check(trial)
# evaluating a single trial population for the i-th individual
de_traj, de_runtime, de_history, fitnesses, costs = \
self.eval_pop(trial.reshape(1, self.dimensions), budget=budget, **kwargs)
# one-vs-one selection
## can replace the i-the population despite not completing one iteration
if fitnesses[0] <= self.fitness[i]:
self.population[i] = trial
self.fitness[i] = fitnesses[0]
traj.extend(de_traj)
runtime.extend(de_runtime)
history.extend(de_history)
return traj, runtime, history
else: # async_strategy == 'random' or async_strategy == 'worst':
for count in range(self.pop_size):
# choosing target individual
if self.async_strategy == 'random':
i = np.random.choice(np.arange(self.pop_size))
else: # async_strategy == 'worst'
i = np.argsort(-self.fitness)[0]
target = self.population[i]
mutant = self.mutation(current=target, best=best, alt_pop=alt_pop)
trial = self.crossover(target, mutant)
trial = self.boundary_check(trial)
# evaluating a single trial population for the i-th individual
de_traj, de_runtime, de_history, fitnesses, costs = \
self.eval_pop(trial.reshape(1, self.dimensions), budget=budget, **kwargs)
# one-vs-one selection
## can replace the i-the population despite not completing one iteration
if fitnesses[0] <= self.fitness[i]:
self.population[i] = trial
self.fitness[i] = fitnesses[0]
traj.extend(de_traj)
runtime.extend(de_runtime)
history.extend(de_history)
return traj, runtime, history
def run(self, generations=1, verbose=False, budget=None, reset=True, **kwargs):
# checking if a run exists
if not hasattr(self, 'traj') or reset:
self.reset()
if verbose:
print("Initializing and evaluating new population...")
self.traj, self.runtime, self.history = self.init_eval_pop(budget=budget, **kwargs)
if verbose:
print("Running evolutionary search...")
for i in range(generations):
if verbose:
print("Generation {:<2}/{:<2} -- {:<0.7}".format(i+1, generations, self.inc_score))
traj, runtime, history = self.evolve_generation(
budget=budget, best=self.inc_config, **kwargs
)
self.traj.extend(traj)
self.runtime.extend(runtime)
self.history.extend(history)
if verbose:
print("\nRun complete!")
return np.array(self.traj), np.array(self.runtime), np.array(self.history, dtype=object)