-
Notifications
You must be signed in to change notification settings - Fork 2
/
L3-random-search.py
50 lines (37 loc) · 996 Bytes
/
L3-random-search.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
import numpy as np
import matplotlib.pyplot as plt
# function to optimize
# assume input x is a numpy array, not a list
def ackley(x):
a = 20
b = 0.2
c = 2*np.pi
d = x.size
term1 = -a*np.exp(-b*np.sqrt((x**2).sum()/d))
term2 = np.exp(np.cos(c*x).sum()/d)
return (term1 - term2 + a + np.exp(1))
ub = 32.768
lb = -32.768
d = 2 # dimension of decision variable space
num_seeds = 10
max_NFE = 100000 # this is a lot, it will take a while
ft = np.zeros((num_seeds, max_NFE))
# pure random search
for seed in range(num_seeds):
np.random.seed(seed)
bestx = None
bestf = None
for i in range(max_NFE):
x = np.random.uniform(lb, ub, d)
f = ackley(x)
if bestf is None or f < bestf:
bestx = x
bestf = f
ft[seed,i] = bestf
# for each trial print the result (but the traces are saved in ft)
print(bestx)
print(bestf)
plt.loglog(ft.T, color='steelblue', linewidth=1)
plt.xlabel('Iterations')
plt.ylabel('Objective Value')
plt.show()