-
Notifications
You must be signed in to change notification settings - Fork 36
/
algorithms.py
executable file
·730 lines (613 loc) · 20.2 KB
/
algorithms.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
"""
Collection of (optimization) algorithms. All entries share a common signature with
optional arguments.
"""
from scipy.optimize import minimize as minimize
import cma.evolution_strategy as cma
import numpy as np
from typing import Callable
import adaptive
import copy
from scipy.optimize import OptimizeResult
import tensorflow as tf
algorithms = dict()
def algo_reg_deco(func):
"""
Decorator for making registry of functions
"""
algorithms[str(func.__name__)] = func
return func
@algo_reg_deco
def single_eval(x_init, fun=None, fun_grad=None, grad_lookup=None, options={}):
"""
Return the function value at given point.
Parameters
----------
x_init : float
Initial point
fun : callable
Goal function
fun_grad : callable
Function that computes the gradient of the goal function
grad_lookup : callable
Lookup a previously computed gradient
options : dict
Algorithm specific options
"""
fun(x_init)
@algo_reg_deco
def grid2D(x_init, fun=None, fun_grad=None, grad_lookup=None, options={}):
"""
Two dimensional scan of the function values around the initial point.
Parameters
----------
x_init : float
Initial point
fun : callable
Goal function
fun_grad : callable
Function that computes the gradient of the goal function
grad_lookup : callable
Lookup a previously computed gradient
options : dict
Options include
points : int
The number of samples
bounds : list
Range of the scan for both dimensions
"""
# TODO generalize grid to take any number of dimensions
if "points" in options:
points = options["points"]
else:
points = 100
# probe_list = []
# if 'probe_list' in options:
# for x in options['probe_list']:
# probe_list.append(eval(x))
# if 'init_point' in options:
# init_point = bool(options.pop('init_point'))
# if init_point:
# probe_list.append(x_init)
bounds = options["bounds"][0]
bound_min = bounds[0]
bound_max = bounds[1]
# probe_list_min = np.min(np.array(probe_list)[:,0])
# probe_list_max = np.max(np.array(probe_list)[:,0])
# bound_min = min(bound_min, probe_list_min)
# bound_max = max(bound_max, probe_list_max)
xs = np.linspace(bound_min, bound_max, points)
bounds = options["bounds"][1]
bound_min = bounds[0]
bound_max = bounds[1]
# probe_list_min = np.min(np.array(probe_list)[:,1])
# probe_list_max = np.max(np.array(probe_list)[:,1])
# bound_min = min(bound_min, probe_list_min)
# bound_max = max(bound_max, probe_list_max)
ys = np.linspace(bound_min, bound_max, points)
# for p in probe_list:
# fun(p)
for x in xs:
for y in ys:
if "wrapper" in options:
val = copy.deepcopy(options["wrapper"])
val[val.index("x")] = x
val[val.index("y")] = y
fun([val])
else:
fun([x, y])
@algo_reg_deco
def sweep(x_init, fun=None, fun_grad=None, grad_lookup=None, options={}):
"""
One dimensional scan of the function values around the initial point.
Parameters
----------
x_init : float
Initial point
fun : callable
Goal function
fun_grad : callable
Function that computes the gradient of the goal function
grad_lookup : callable
Lookup a previously computed gradient
options : dict
Options include
points : int
The number of samples
bounds : list
Range of the scan
"""
if "points" in options:
points = options["points"]
else:
points = 100
if "init_point" in options:
init_point = bool(options["init_point"])
if init_point:
fun([x_init[0].numpy()])
bounds = options["bounds"][0]
bound_min = bounds[0]
bound_max = bounds[1]
probe_list = []
if "probe_list" in options:
for x in options["probe_list"]:
probe_list.append(x)
probe_list_min = min(probe_list)
probe_list_max = max(probe_list)
bound_min = min(bound_min, probe_list_min)
bound_max = max(bound_max, probe_list_max)
for p in probe_list:
if "wrapper" in options:
val = copy.deepcopy(options["wrapper"])
val[val.index("x")] = p
fun([val])
else:
fun([p])
xs = np.linspace(bound_min, bound_max, points)
for x in xs:
if "wrapper" in options:
val = copy.deepcopy(options["wrapper"])
val[val.index("x")] = x
fun([val])
else:
fun([x])
@algo_reg_deco
def adaptive_scan(x_init, fun=None, fun_grad=None, grad_lookup=None, options={}):
"""
One dimensional scan of the function values around the initial point, using
adaptive sampling
Parameters
----------
x_init : float
Initial point
fun : callable
Goal function
fun_grad : callable
Function that computes the gradient of the goal function
grad_lookup : callable
Lookup a previously computed gradient
options : dict
Options include
accuracy_goal: float
Targeted accuracy for the sampling algorithm
probe_list : list
Points to definitely include in the sampling
init_point : boolean
Include the initial point in the sampling
"""
if "accuracy_goal" in options:
accuracy_goal = options["accuracy_goal"]
else:
accuracy_goal = 0.5
print("accuracy_goal: " + str(accuracy_goal))
probe_list = []
if "probe_list" in options:
for x in options["probe_list"]:
probe_list.append(eval(x))
if "init_point" in options:
init_point = bool(options.pop("init_point"))
if init_point:
probe_list.append(x_init)
# TODO make adaptive scan be able to do multidimensional scan
bounds = options["bounds"][0]
bound_min = bounds[0]
bound_max = bounds[1]
probe_list_min = min(probe_list)
probe_list_max = max(probe_list)
bound_min = min(bound_min, probe_list_min)
bound_max = max(bound_max, probe_list_max)
print(" ")
print("bound_min: " + str((bound_min) / (2e9 * np.pi)))
print("bound_max: " + str((bound_max) / (2e9 * np.pi)))
print(" ")
def fun1d(x):
return fun([x])
learner = adaptive.Learner1D(fun1d, bounds=(bound_min, bound_max))
if probe_list:
for x in probe_list:
print("from probe_list: " + str(x))
tmp = learner.function(x)
print("done\n")
learner.tell(x, tmp)
adaptive.runner.simple(
learner, goal=lambda learner_: learner_.loss() < accuracy_goal
)
@algo_reg_deco
def tf_sgd(
x_init: np.array,
fun: Callable = None,
fun_grad: Callable = None,
grad_lookup: Callable = None,
options: dict = {},
) -> OptimizeResult:
"""Optimize using TensorFlow Stochastic Gradient Descent with Momentum
https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/SGD
Parameters
----------
x_init : np.array
starting value of parameter(s)
fun : Callable, optional
function to minimize, by default None
fun_grad : Callable, optional
gradient of function to minimize, by default None
grad_lookup : Callable, optional
lookup stored gradients, by default None
options : dict, optional
optional parameters for optimizer, by default {}
Returns
-------
OptimizeResult
SciPy OptimizeResult type object with final parameters
"""
iters = options["maxfun"]
var = tf.Variable(x_init)
def tf_fun():
return fun(var)
opt_sgd = tf.keras.optimizers.SGD(learning_rate=0.1, momentum=0.9)
for step in range(iters):
step_count = opt_sgd.minimize(tf_fun, [var])
print(f"epoch {step_count.numpy()}: func_value: {tf_fun()}")
result = OptimizeResult(x=var.numpy(), success=True)
return result
@algo_reg_deco
def tf_adam(
x_init: np.array,
fun: Callable = None,
fun_grad: Callable = None,
grad_lookup: Callable = None,
options: dict = {},
) -> OptimizeResult:
"""Optimize using TensorFlow ADAM
https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/Adam
Parameters
----------
x_init : np.array
starting value of parameter(s)
fun : Callable, optional
function to minimize, by default None
fun_grad : Callable, optional
gradient of function to minimize, by default None
grad_lookup : Callable, optional
lookup stored gradients, by default None
options : dict, optional
optional parameters for optimizer, by default {}
Returns
-------
OptimizeResult
SciPy OptimizeResult type object with final parameters
"""
iters = options["maxfun"]
var = tf.Variable(x_init)
def tf_fun():
return fun(var)
opt_adam = tf.keras.optimizers.Adam(learning_rate=0.001, epsilon=0.1)
for step in range(iters):
step_count = opt_adam.minimize(tf_fun, [var])
print(f"epoch {step_count.numpy()}: func_value: {tf_fun()}")
result = OptimizeResult(x=var.numpy(), success=True)
return result
def tf_rmsprop(
x_init: np.array,
fun: Callable = None,
fun_grad: Callable = None,
grad_lookup: Callable = None,
options: dict = {},
) -> OptimizeResult:
"""Optimize using TensorFlow RMSProp
https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/RMSprop
Parameters
----------
x_init : np.array
starting value of parameter(s)
fun : Callable, optional
function to minimize, by default None
fun_grad : Callable, optional
gradient of function to minimize, by default None
grad_lookup : Callable, optional
lookup stored gradients, by default None
options : dict, optional
optional parameters for optimizer, by default {}
Returns
-------
OptimizeResult
SciPy OptimizeResult type object with final parameters
"""
iters = options["maxfun"]
var = tf.Variable(x_init)
def tf_fun():
return fun(var)
opt_rmsprop = tf.keras.optimizers.RMSprop(
learning_rate=0.1, epsilon=1e-2, centered=True
)
for step in range(iters):
step_count = opt_rmsprop.minimize(tf_fun, [var])
print(f"epoch {step_count.numpy()}: func_value: {tf_fun()}")
result = OptimizeResult(x=var.numpy(), success=True)
return result
@algo_reg_deco
def tf_adadelta(
x_init: np.array,
fun: Callable = None,
fun_grad: Callable = None,
grad_lookup: Callable = None,
options: dict = {},
) -> OptimizeResult:
"""Optimize using TensorFlow Adadelta
https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/Adadelta
Parameters
----------
x_init : np.array
starting value of parameter(s)
fun : Callable, optional
function to minimize, by default None
fun_grad : Callable, optional
gradient of function to minimize, by default None
grad_lookup : Callable, optional
lookup stored gradients, by default None
options : dict, optional
optional parameters for optimizer, by default {}
Returns
-------
OptimizeResult
SciPy OptimizeResult type object with final parameters
"""
iters = options["maxfun"]
var = tf.Variable(x_init)
def tf_fun():
return fun(var)
opt_adadelta = tf.keras.optimizers.Adadelta(
learning_rate=0.1, rho=0.95, epsilon=1e-2
)
for step in range(iters):
step_count = opt_adadelta.minimize(tf_fun, [var])
print(f"epoch {step_count.numpy()}: func_value: {tf_fun()}")
result = OptimizeResult(x=var.numpy(), success=True)
return result
@algo_reg_deco
def lbfgs(x_init, fun=None, fun_grad=None, grad_lookup=None, options={}):
"""
Wrapper for the scipy.optimize.minimize implementation of LBFG-S. See also:
https://docs.scipy.org/doc/scipy/reference/optimize.minimize-lbfgsb.html
Parameters
----------
x_init : float
Initial point
fun : callable
Goal function
fun_grad : callable
Function that computes the gradient of the goal function
grad_lookup : callable
Lookup a previously computed gradient
options : dict
Options of scipy.optimize.minimize
Returns
-------
Result
Scipy result object.
"""
# TODO print from the log not from here
# options.update({"disp": True})
return minimize(
fun_grad, x_init, jac=grad_lookup, method="L-BFGS-B", options=options
)
@algo_reg_deco
def lbfgs_grad_free(x_init, fun=None, fun_grad=None, grad_lookup=None, options={}):
"""
Wrapper for the scipy.optimize.minimize implementation of LBFG-S.
We let the algorithm determine the gradient by its own.
See also:
https://docs.scipy.org/doc/scipy/reference/optimize.minimize-lbfgsb.html
Parameters
----------
x_init : float
Initial point
fun : callable
Goal function
fun_grad : callable
Function that computes the gradient of the goal function
grad_lookup : callable
Lookup a previously computed gradient
options : dict
Options of scipy.optimize.minimize
Returns
-------
Result
Scipy result object.
"""
return minimize(fun=fun, x0=x_init, options=options)
@algo_reg_deco
def cmaes(x_init, fun=None, fun_grad=None, grad_lookup=None, options={}):
"""
Wrapper for the pycma implementation of CMA-Es. See also:
http://cma.gforge.inria.fr/apidocs-pycma/
Parameters
----------
x_init : float
Initial point.
fun : callable
Goal function.
fun_grad : callable
Function that computes the gradient of the goal function.
grad_lookup : callable
Lookup a previously computed gradient.
options : dict
Options of pycma and the following custom options.
noise : float
Artificial noise added to a function evaluation.
init_point : boolean
Force the use of the initial point in the first generation.
spread : float
Adjust the parameter spread of the first generation cloud.
stop_at_convergence : int
Custom stopping condition. Stop if the cloud shrunk for this number of
generations.
stop_at_sigma : float
Custom stopping condition. Stop if the cloud shrunk to this standard
deviation.
Returns
-------
np.array
Parameters of the best point.
"""
if "noise" in options:
noise = float(options.pop("noise"))
else:
noise = 0
if "batch_noise" in options:
batch_noise = float(options.pop("batch_noise"))
else:
batch_noise = 0
if "init_point" in options:
init_point = bool(options.pop("init_point"))
else:
init_point = False
if "spread" in options:
spread = float(options.pop("spread"))
else:
spread = 0.1
shrunk_check = False
if "stop_at_convergence" in options:
sigma_conv = int(options.pop("stop_at_convergence"))
sigmas = []
shrunk_check = True
sigma_check = False
if "stop_at_sigma" in options:
stop_sigma = int(options.pop("stop_at_sigma"))
sigma_check = True
settings = options
es = cma.CMAEvolutionStrategy(x_init, spread, settings)
iter = 0
while not es.stop():
if shrunk_check:
sigmas.append(es.sigma)
if iter > sigma_conv:
if all(
sigmas[-(i + 1)] < sigmas[-(i + 2)] for i in range(sigma_conv - 1)
):
print(
f"C3:STATUS:Shrunk cloud for {sigma_conv} steps. "
"Switching to gradients."
)
break
if sigma_check:
if es.sigma < stop_sigma:
print("C3:STATUS:Goal sigma reached. Stopping CMA.")
break
samples = es.ask()
if init_point and iter == 0:
samples.insert(0, x_init)
print("C3:STATUS:Adding initial point to CMA sample.")
solutions = []
if batch_noise:
error = np.random.randn() * noise
for sample in samples:
goal = fun(sample)
if noise:
error = np.random.randn() * noise
if batch_noise or noise:
goal = goal + error
solutions.append(goal)
es.tell(samples, solutions)
es.disp()
iter += 1
es.result_pretty()
return es.result.xbest
@algo_reg_deco
def cma_pre_lbfgs(x_init, fun=None, fun_grad=None, grad_lookup=None, options={}):
"""
Performs a CMA-Es optimization and feeds the result into LBFG-S for further
refinement.
"""
if "cmaes" not in options:
options["cmaes"] = {}
if "lbfgs" not in options:
options["lbfgs"] = {}
for k in options:
if k == "cmaes" or k == "lbfgs":
continue
else:
if k not in options["cmaes"]:
options["cmaes"][k] = options[k]
if k not in options["lbfgs"]:
options["lbfgs"][k] = options[k]
x1 = cmaes(x_init, fun, options=options["cmaes"])
lbfgs(x1, fun_grad=fun_grad, grad_lookup=grad_lookup, options=options["lbfgs"])
@algo_reg_deco
def gcmaes(x_init, fun=None, fun_grad=None, grad_lookup=None, options={}):
"""
EXPERIMENTAL CMA-Es where every point in the cloud is optimized with LBFG-S and the
resulting cloud and results are used for the CMA update.
"""
options_cma = options["cmaes"]
if "init_point" in options_cma:
init_point = bool(options_cma.pop("init_point"))
else:
init_point = False
if "spread" in options_cma:
spread = float(options_cma.pop("spread"))
else:
spread = 0.1
shrinked_check = False
if "stop_at_convergence" in options_cma:
sigma_conv = int(options_cma.pop("stop_at_convergence"))
sigmas = []
shrinked_check = True
sigma_check = False
if "stop_at_sigma" in options_cma:
stop_sigma = int(options_cma.pop("stop_at_sigma"))
sigma_check = True
settings = options_cma
es = cma.CMAEvolutionStrategy(x_init, spread, settings)
iter = 0
while not es.stop():
if shrinked_check:
sigmas.append(es.sigma)
if iter > sigma_conv:
if all(
sigmas[-(i + 1)] < sigmas[-(i + 2)] for i in range(sigma_conv - 1)
):
print(
f"C3:STATUS:Shrinked cloud for {sigma_conv} steps. "
"Switching to gradients."
)
break
if sigma_check:
if es.sigma < stop_sigma:
print("C3:STATUS:Goal sigma reached. Stopping CMA.")
break
samples = es.ask()
if init_point and iter == 0:
samples.insert(0, x_init)
print("C3:STATUS:Adding initial point to CMA sample.")
solutions = []
points = []
for sample in samples:
r = lbfgs(
sample,
fun_grad=fun_grad,
grad_lookup=grad_lookup,
options=options["lbfgs"],
)
solutions.append(r.fun)
points.append(r.x)
es.tell(points, solutions)
es.disp()
iter += 1
return es.result.xbest
# def oneplusone(x_init, goal_fun):
# optimizer = algo_registry['OnePlusOne'](instrumentation=x_init.shape[0])
# while True:
# # TODO make this logging happen elsewhere
# # self.logfile.write(f"Batch {self.evaluation}\n")
# # self.logfile.flush()
# tmp = optimizer.ask()
# samples = tmp.args
# solutions = []
# for sample in samples:
# goal = goal_fun(sample)
# solutions.append(goal)
# optimizer.tell(tmp, solutions)
#
# # TODO deal with storing best value elsewhere
# # recommendation = optimizer.provide_recommendation()
# # return recommendation.args[0]