1
|
|
|
# Author: Simon Blanke |
2
|
|
|
# Email: [email protected] |
3
|
|
|
# License: MIT License |
4
|
|
|
|
5
|
|
|
|
6
|
|
|
import numpy as np |
7
|
|
|
from scipy.stats import norm |
8
|
|
|
from scipy.spatial.distance import cdist |
9
|
|
|
|
10
|
|
|
|
11
|
|
|
from .sbom import SBOM |
12
|
|
|
|
13
|
|
|
|
14
|
|
|
class ExpectedImprovementBasedOptimization(SBOM): |
15
|
|
|
def __init__(self, search_space, xi=0.01, **kwargs): |
16
|
|
|
super().__init__(search_space, **kwargs) |
17
|
|
|
self.new_positions = [] |
18
|
|
|
self.xi = xi |
19
|
|
|
|
20
|
|
|
def _expected_improvement(self): |
21
|
|
|
all_pos_comb_sampled = self.get_random_sample() |
22
|
|
|
|
23
|
|
|
mu, sigma = self.regr.predict(all_pos_comb_sampled, return_std=True) |
24
|
|
|
mu_sample = self.regr.predict(self.X_sample) |
25
|
|
|
|
26
|
|
|
mu = mu.reshape(-1, 1) |
27
|
|
|
sigma = sigma.reshape(-1, 1) |
28
|
|
|
mu_sample = mu_sample.reshape(-1, 1) |
29
|
|
|
|
30
|
|
|
mu_sample_opt = np.max(mu_sample) |
31
|
|
|
imp = mu - mu_sample_opt - self.xi |
32
|
|
|
|
33
|
|
|
Z = np.divide(imp, sigma, out=np.zeros_like(sigma), where=sigma != 0) |
34
|
|
|
exp_imp = imp * norm.cdf(Z) + sigma * norm.pdf(Z) |
35
|
|
|
exp_imp[sigma == 0.0] = 0.0 |
36
|
|
|
|
37
|
|
|
return exp_imp |
38
|
|
|
|
39
|
|
|
def _propose_location(self): |
40
|
|
|
self.regr.fit(self.X_sample, self.Y_sample) |
41
|
|
|
|
42
|
|
|
exp_imp = self._expected_improvement() |
43
|
|
|
exp_imp = exp_imp[:, 0] |
44
|
|
|
|
45
|
|
|
index_best = list(exp_imp.argsort()[::-1]) |
46
|
|
|
all_pos_comb_sorted = self.all_pos_comb[index_best] |
47
|
|
|
|
48
|
|
|
pos_best = [all_pos_comb_sorted[0]] |
49
|
|
|
|
50
|
|
|
while len(pos_best) < self.skip_retrain(len(self.pos_new)): |
51
|
|
|
if all_pos_comb_sorted.shape[0] == 0: |
52
|
|
|
break |
53
|
|
|
|
54
|
|
|
dists = cdist(all_pos_comb_sorted, [pos_best[-1]], metric="cityblock") |
55
|
|
|
dists_norm = dists / dists.max() |
56
|
|
|
bool = np.squeeze(dists_norm > 0.25) |
57
|
|
|
all_pos_comb_sorted = all_pos_comb_sorted[bool] |
58
|
|
|
|
59
|
|
|
if len(all_pos_comb_sorted) > 0: |
60
|
|
|
pos_best.append(all_pos_comb_sorted[0]) |
61
|
|
|
|
62
|
|
|
return pos_best |
63
|
|
|
|
64
|
|
|
def iterate(self): |
65
|
|
|
if len(self.new_positions) == 0: |
66
|
|
|
self.new_positions = self._propose_location() |
67
|
|
|
|
68
|
|
|
pos = self.new_positions[0] |
69
|
|
|
self.pos_new = pos |
70
|
|
|
|
71
|
|
|
self.new_positions.pop(0) |
72
|
|
|
self.X_sample.append(pos) |
73
|
|
|
self.pos = pos |
74
|
|
|
|
75
|
|
|
return pos |
76
|
|
|
|
77
|
|
|
def evaluate(self, score_new): |
78
|
|
|
self.score_new = score_new |
79
|
|
|
|
80
|
|
|
self._evaluate_new2current(score_new) |
81
|
|
|
self._evaluate_current2best() |
82
|
|
|
|
83
|
|
|
self.Y_sample.append(score_new) |
84
|
|
|
|