1
|
|
|
# Author: Simon Blanke |
2
|
|
|
# Email: [email protected] |
3
|
|
|
# License: MIT License |
4
|
|
|
|
5
|
|
|
import random |
6
|
|
|
import numpy as np |
7
|
|
|
from .search_tracker import SearchTracker |
8
|
|
|
from ..converter import Converter |
9
|
|
|
from ..results_manager import ResultsManager |
10
|
|
|
|
11
|
|
|
|
12
|
|
|
class BaseOptimizer(SearchTracker): |
13
|
|
|
def __init__( |
14
|
|
|
self, |
15
|
|
|
search_space, |
16
|
|
|
initialize={"grid": 4, "random": 2, "vertices": 4}, |
17
|
|
|
): |
18
|
|
|
super().__init__() |
19
|
|
|
self.conv = Converter(search_space) |
20
|
|
|
self.results_mang = ResultsManager(self.conv) |
21
|
|
|
self.initialize = initialize |
22
|
|
|
|
23
|
|
|
self.optimizers = [self] |
24
|
|
|
|
25
|
|
|
def move_random(self): |
26
|
|
|
position = [] |
27
|
|
|
for search_space_pos in self.conv.search_space_positions: |
28
|
|
|
pos_ = random.choice(search_space_pos) |
29
|
|
|
position.append(pos_) |
30
|
|
|
|
31
|
|
|
return np.array(position) |
32
|
|
|
|
33
|
|
|
def track_nth_iter(func): |
34
|
|
|
def wrapper(self, *args, **kwargs): |
35
|
|
|
self.nth_iter = len(self.pos_new_list) |
36
|
|
|
pos = func(self, *args, **kwargs) |
37
|
|
|
self.pos_new = pos |
38
|
|
|
return pos |
39
|
|
|
|
40
|
|
|
return wrapper |
41
|
|
|
|
42
|
|
|
def random_restart(func): |
43
|
|
|
def wrapper(self, *args, **kwargs): |
44
|
|
|
if self.rand_rest_p > random.uniform(0, 1): |
45
|
|
|
return self.move_random() |
46
|
|
|
else: |
47
|
|
|
return func(self, *args, **kwargs) |
48
|
|
|
|
49
|
|
|
return wrapper |
50
|
|
|
|
51
|
|
|
def conv2pos(self, pos): |
52
|
|
|
# position to int |
53
|
|
|
r_pos = np.rint(pos) |
54
|
|
|
n_zeros = [0] * len(self.conv.max_positions) |
55
|
|
|
# clip into search space boundaries |
56
|
|
|
return np.clip(r_pos, n_zeros, self.conv.max_positions).astype(int) |
57
|
|
|
|
58
|
|
|
def init_pos(self, pos): |
59
|
|
|
self.pos_new = pos |
60
|
|
|
self.nth_iter = len(self.pos_new_list) |
61
|
|
|
|
62
|
|
|
def finish_initialization(self): |
63
|
|
|
pass |
64
|
|
|
|
65
|
|
|
def evaluate(self, score_new): |
66
|
|
|
self.score_new = score_new |
67
|
|
|
|
68
|
|
|
if self.pos_best is None: |
69
|
|
|
self.pos_best = self.pos_new |
70
|
|
|
self.pos_current = self.pos_new |
71
|
|
|
|
72
|
|
|
self.score_best = score_new |
73
|
|
|
self.score_current = score_new |
74
|
|
|
|
75
|
|
|
# self._evaluate_new2current(score_new) |
76
|
|
|
# self._evaluate_current2best() |
77
|
|
|
|