Skip to content

Commit d4e8478

Browse files
committedJul 2, 2021
Create simulated annealing.py
1 parent 33141b6 commit d4e8478

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
 

‎simulated annealing.py

+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
"""
2+
3+
simulated annealing search on one-dimensional objective function to find the better local minima
4+
5+
"""
6+
from numpy import asarray
7+
from numpy import exp
8+
from numpy.random import randn
9+
from numpy.random import rand
10+
from numpy.random import seed
11+
12+
# 7 degree polynomial objective function
13+
def objective(p):
14+
# x and u for shifting the a templet function
15+
x = p + 22
16+
y = 0
17+
return (x**5)-(7* x**3)+(2* x**2)-(x**4)+(6*x)+(.005 * x**7) + y
18+
19+
# simulated annealing algorithm
20+
def simulated_annealing(objective, bounds, n_iterations, step_size, temp):
21+
best = bounds[:,0] + randn(len(bounds)) + (bounds[:,1] - bounds[:,0])
22+
best_eval = objective(best)
23+
curr, curr_eval = best, best_eval
24+
25+
for i in range(n_iterations):
26+
candidate = curr + randn(len(bounds)) * step_size
27+
#candidate = best + randn() * step_size
28+
candidate_eval = objective(candidate)
29+
30+
if(candidate_eval < best_eval):
31+
best, best_eval = candidate, candidate_eval
32+
print(i, best, best_eval)
33+
diff = candidate_eval - curr_eval
34+
t = float(temp/(i+1))
35+
metropolis = exp(-diff/t)
36+
if (diff<0 or metropolis < randn()):
37+
curr,curr_eval = candidate, candidate_eval
38+
39+
return [ best, best_eval]
40+
41+
42+
43+
44+
45+
seed(2)
46+
# define range for input **most important hyperparameter
47+
bounds = asarray([[-30, -21.0]])
48+
# define the total iterations
49+
n_iterations = 2000
50+
# define the maximum step size
51+
step_size = .01
52+
# initial temperature ** another hyperparameter
53+
temp = 100
54+
55+
# perform the simulated annealing search
56+
best, score = simulated_annealing(objective, bounds, n_iterations, step_size, temp)
57+
print('Complete!')
58+
print('f(%s) = %f' % (best, score))
59+

0 commit comments

Comments
 (0)
Please sign in to comment.