-
Notifications
You must be signed in to change notification settings - Fork 35
/
sepcmaes.py
188 lines (168 loc) · 9.74 KB
/
sepcmaes.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
import numpy as np # engine for numerical computing
from pypop7.optimizers.es.es import ES # abstract class of all Evolution Strategies (ES) classes
class SEPCMAES(ES):
"""Separable Covariance Matrix Adaptation Evolution Strategy (SEPCMAES).
.. note:: `SEPCMAES` learns only the **diagonal** elements of the full covariance matrix explicitly, leading
to a *linear* time complexity (w.r.t. each sampling) for large-scale black-box optimization. It is **highly
recommended** to first attempt more advanced ES variants (e.g., `LMCMA`, `LMMAES`) for large-scale black-box
optimization, since typically the performance of `SEPCMAES` deteriorates significantly on **non-separable,
ill-conditioned** fitness landscape.
Parameters
----------
problem : dict
problem arguments with the following common settings (`keys`):
* 'fitness_function' - objective function to be **minimized** (`func`),
* 'ndim_problem' - number of dimensionality (`int`),
* 'upper_boundary' - upper boundary of search range (`array_like`),
* 'lower_boundary' - lower boundary of search range (`array_like`).
options : dict
optimizer options with the following common settings (`keys`):
* 'max_function_evaluations' - maximum of function evaluations (`int`, default: `np.inf`),
* 'max_runtime' - maximal runtime to be allowed (`float`, default: `np.inf`),
* 'seed_rng' - seed for random number generation needed to be *explicitly* set (`int`);
and with the following particular settings (`keys`):
* 'sigma' - initial global step-size, aka mutation strength (`float`),
* 'mean' - initial (starting) point, aka mean of Gaussian search distribution (`array_like`),
* if not given, it will draw a random sample from the uniform distribution whose search range is
bounded by `problem['lower_boundary']` and `problem['upper_boundary']`.
* 'n_individuals' - number of offspring, aka offspring population size (`int`, default:
`4 + int(3*np.log(options['ndim_problem']))`),
* 'n_parents' - number of parents, aka parental population size (`int`, default:
`int(options['n_individuals']/2)`),
* 'c_c' - learning rate of evolution path update (`float`, default:
`4.0/(options['ndim_problem'] + 4.0)`).
Examples
--------
Use the black-box optimizer `SEPCMAES` to minimize the well-known test function
`Rosenbrock <http://en.wikipedia.org/wiki/Rosenbrock_function>`_:
.. code-block:: python
:linenos:
>>> import numpy # engine for numerical computing
>>> from pypop7.benchmarks.base_functions import rosenbrock # function to be minimized
>>> from pypop7.optimizers.es.sepcmaes import SEPCMAES
>>> problem = {'fitness_function': rosenbrock, # to define problem arguments
... 'ndim_problem': 2,
... 'lower_boundary': -5.0*numpy.ones((2,)),
... 'upper_boundary': 5.0*numpy.ones((2,))}
>>> options = {'max_function_evaluations': 5000, # to set optimizer options
... 'seed_rng': 2022,
... 'mean': 3.0*numpy.ones((2,)),
... 'sigma': 3.0} # global step-size may need to be fine-tuned for better performance
>>> sepcmaes = SEPCMAES(problem, options) # to initialize the optimizer class
>>> results = sepcmaes.optimize() # to run the optimization/evolution process
>>> print(f"SEPCMAES: {results['n_function_evaluations']}, {results['best_so_far_y']}")
SEPCMAES: 5000, 0.0093
For its correctness checking of Python coding, please refer to `this code-based repeatability report
<https://github.com/Evolutionary-Intelligence/pypop/blob/main/pypop7/optimizers/es/_repeat_sepcmaes.py>`_
for all details. For *pytest*-based automatic testing, please see `test_sepcmaes.py
<https://github.com/Evolutionary-Intelligence/pypop/blob/main/pypop7/optimizers/es/test_sepcmaes.py>`_.
Attributes
----------
c_c : `float`
learning rate of evolution path update.
mean : `array_like`
initial (starting) point, aka mean of Gaussian search distribution.
n_individuals : `int`
number of offspring, aka offspring population size.
n_parents : `int`
number of parents, aka parental population size.
sigma : `float`
final global step-size, aka mutation strength.
References
----------
Ros, R. and Hansen, N., 2008, September.
`A simple modification in CMA-ES achieving linear time and space complexity.
<https://link.springer.com/chapter/10.1007/978-3-540-87700-4_30>`_
In International Conference on Parallel Problem Solving from Nature (pp. 296-305).
Springer, Berlin, Heidelberg.
"""
def __init__(self, problem, options):
ES.__init__(self, problem, options)
self.options = options
self.c_c = options.get('c_c', 4.0/(self.ndim_problem + 4.0))
self.c_s, self.c_cov = None, None
self.d_sigma = None
self._s_1, self._s_2 = None, None
def _set_c_cov(self):
c_cov = (1.0/self._mu_eff)*(2.0/np.power(self.ndim_problem + np.sqrt(2.0), 2)) + (
(1.0 - 1.0/self._mu_eff)*np.minimum(1.0, (2.0*self._mu_eff - 1.0)/(
np.power(self.ndim_problem + 2.0, 2) + self._mu_eff)))
c_cov *= (self.ndim_problem + 2.0)/3.0 # for faster adaptation
return c_cov
def _set_d_sigma(self):
d_sigma = np.maximum((self._mu_eff - 1.0)/(self.ndim_problem + 1.0) - 1.0, 0.0)
return 1.0 + self.c_s + 2.0*np.sqrt(d_sigma)
def initialize(self, is_restart=False):
self.c_s = self.options.get('c_s', (self._mu_eff + 2.0)/(self.ndim_problem + self._mu_eff + 3.0))
self.c_cov = self.options.get('c_cov', self._set_c_cov())
self.d_sigma = self.options.get('d_sigma', self._set_d_sigma())
self._s_1 = 1.0 - self.c_s
self._s_2 = np.sqrt(self._mu_eff*self.c_s*(2.0 - self.c_s))
z = np.empty((self.n_individuals, self.ndim_problem)) # Gaussian noise for mutation
x = np.empty((self.n_individuals, self.ndim_problem)) # offspring
mean = self._initialize_mean(is_restart) # mean of Gaussian search distribution
s = np.zeros((self.ndim_problem,)) # evolution path for CSA
p = np.zeros((self.ndim_problem,)) # evolution path for CMA
c = np.ones((self.ndim_problem,)) # diagonal elements for covariance matrix
d = np.ones((self.ndim_problem,)) # diagonal elements for covariance matrix
y = np.empty((self.n_individuals,)) # fitness (no evaluation)
self._list_initial_mean.append(np.copy(mean))
self._n_generations = 0
return z, x, mean, s, p, c, d, y
def iterate(self, z=None, x=None, mean=None, d=None, y=None, args=None):
for k in range(self.n_individuals):
if self._check_terminations():
return z, x, y
z[k] = self.rng_optimization.standard_normal((self.ndim_problem,))
x[k] = mean + self.sigma*d*z[k]
y[k] = self._evaluate_fitness(x[k], args)
return z, x, y
def _update_distribution(self, z=None, x=None, s=None, p=None, c=None, d=None, y=None):
order = np.argsort(y)
zeros = np.zeros((self.ndim_problem,))
z_w, mean, dz_w = np.copy(zeros), np.copy(zeros), np.copy(zeros)
for k in range(self.n_parents):
z_w += self._w[k]*z[order[k]]
mean += self._w[k]*x[order[k]] # update distribution mean
dz = d*z[order[k]]
dz_w += self._w[k]*dz*dz
s = self._s_1*s + self._s_2*z_w
if (np.linalg.norm(s)/np.sqrt(1.0 - np.power(1.0 - self.c_s, 2.0*(self._n_generations + 1)))) < (
(1.4 + 2.0/(self.ndim_problem + 1.0))*self._e_chi):
h = np.sqrt(self.c_c*(2.0 - self.c_c))*np.sqrt(self._mu_eff)*d*z_w
else:
h = 0
p = (1.0 - self.c_c)*p + h
c = (1.0 - self.c_cov)*c + (1.0/self._mu_eff)*self.c_cov*p*p + (
self.c_cov*(1.0 - 1.0/self._mu_eff)*dz_w)
self.sigma *= np.exp(self.c_s/self.d_sigma*(np.linalg.norm(s)/self._e_chi - 1.0))
if np.any(c <= 0): # undefined in the original paper
cc = np.copy(c)
cc[cc <= 0] = 1.0
d = np.sqrt(cc)
else:
d = np.sqrt(c)
return mean, s, p, c, d
def restart_reinitialize(self, z=None, x=None, mean=None, s=None, p=None, c=None, d=None, y=None):
is_restart = ES.restart_reinitialize(self, y)
if is_restart:
z, x, mean, s, p, c, d, y = self.initialize(is_restart)
return z, x, mean, s, p, c, d, y
def optimize(self, fitness_function=None, args=None): # for all generations (iterations)
fitness = ES.optimize(self, fitness_function)
z, x, mean, s, p, c, d, y = self.initialize()
while not self.termination_signal:
# sample and evaluate offspring population
z, x, y = self.iterate(z, x, mean, d, y, args)
if self._check_terminations():
break
self._print_verbose_info(fitness, y)
mean, s, p, c, d = self._update_distribution(z, x, s, p, c, d, y)
self._n_generations += 1
if self.is_restart:
z, x, mean, s, p, c, d, y = self.restart_reinitialize(z, x, mean, s, p, c, d, y)
results = self._collect(fitness, y, mean)
results['s'] = s
results['p'] = p
results['d'] = d
return results