|
1
|
|
|
# Author: Simon Blanke |
|
2
|
|
|
# Email: [email protected] |
|
3
|
|
|
# License: MIT License |
|
4
|
|
|
|
|
5
|
|
|
|
|
6
|
|
|
import numpy as np |
|
7
|
|
|
from .dictionary import DictClass |
|
8
|
|
|
|
|
9
|
|
|
|
|
10
|
|
|
def gfo2hyper(search_space, para): |
|
11
|
|
|
values_dict = {} |
|
12
|
|
|
for i, key in enumerate(search_space.keys()): |
|
13
|
|
|
pos_ = int(para[key]) |
|
14
|
|
|
values_dict[key] = search_space[key][pos_] |
|
15
|
|
|
|
|
16
|
|
|
return values_dict |
|
17
|
|
|
|
|
18
|
|
|
|
|
19
|
|
|
class ObjectiveFunction(DictClass): |
|
20
|
|
|
def __init__(self, objective_function, optimizer, nth_process): |
|
21
|
|
|
super().__init__() |
|
22
|
|
|
|
|
23
|
|
|
self.objective_function = objective_function |
|
24
|
|
|
self.optimizer = optimizer |
|
25
|
|
|
self.nth_process = nth_process |
|
26
|
|
|
|
|
27
|
|
|
self.best = 0 |
|
28
|
|
|
self.nth_iter = -1 |
|
29
|
|
|
self.best_para = None |
|
30
|
|
|
self.best_score = -np.inf |
|
31
|
|
|
|
|
32
|
|
|
def get_best(self, score, para): |
|
33
|
|
|
self.nth_iter += 1 |
|
34
|
|
|
|
|
35
|
|
|
if score > self.best_score: |
|
36
|
|
|
self.best_score = score |
|
37
|
|
|
self.best_para = para |
|
38
|
|
|
self.best = 1 |
|
39
|
|
|
else: |
|
40
|
|
|
self.best = 0 |
|
41
|
|
|
|
|
42
|
|
|
def __call__(self, search_space, progress_collector): |
|
43
|
|
|
# wrapper for GFOs |
|
44
|
|
|
def _model(para): |
|
45
|
|
|
para = gfo2hyper(search_space, para) |
|
46
|
|
|
self.para_dict = para |
|
47
|
|
|
results = self.objective_function(self) |
|
48
|
|
|
|
|
49
|
|
|
if progress_collector: |
|
50
|
|
|
progress_dict = para |
|
51
|
|
|
|
|
52
|
|
|
if isinstance(results, tuple): |
|
53
|
|
|
score = results[0] |
|
54
|
|
|
results_dict = results[1] |
|
55
|
|
|
else: |
|
56
|
|
|
score = results |
|
57
|
|
|
results_dict = {} |
|
58
|
|
|
|
|
59
|
|
|
# keep track on best score and para |
|
60
|
|
|
self.get_best(score, para) |
|
61
|
|
|
|
|
62
|
|
|
results_dict["score"] = score |
|
63
|
|
|
|
|
64
|
|
|
progress_dict.update(results_dict) |
|
65
|
|
|
progress_dict["score_best"] = self.best_score |
|
66
|
|
|
progress_dict["nth_iter"] = self.nth_iter |
|
67
|
|
|
progress_dict["best"] = self.best |
|
68
|
|
|
|
|
69
|
|
|
progress_dict["nth_process"] = self.optimizer.nth_process |
|
70
|
|
|
|
|
71
|
|
|
progress_collector.append(progress_dict) |
|
72
|
|
|
|
|
73
|
|
|
# ltm save after iteration |
|
74
|
|
|
# self.ltm.ltm_obj_func_wrapper(results, para, nth_process) |
|
75
|
|
|
|
|
76
|
|
|
return results |
|
77
|
|
|
|
|
78
|
|
|
_model.__name__ = self.objective_function.__name__ |
|
79
|
|
|
return _model |
|
80
|
|
|
|