Simulated Annealing
Local methods get stuck in the nearest valley. Simulated annealing escapes by sometimes accepting uphill moves, with a probability that shrinks over time. The idea comes from metallurgy: cooling a metal slowly lets its atoms settle into a low-energy crystal instead of a brittle glass. It is simple, works on discrete and continuous problems, and needs only function values.
The algorithm
From the current state , propose a random neighbour . With , accept it with the Metropolis probability
where the temperature decreases according to a cooling schedule, e.g. geometric with slightly below 1. At high almost everything is accepted (exploration); at low only improvements are (exploitation).
import numpy as np
T_values = (10.0, 1.0, 0.1)
for delta in (0.5, 2.0, 5.0):
print(f"uphill by {delta}: accept with prob", [round(float(np.exp(-delta / T)), 4) for T in T_values], "at T =", T_values)uphill by 0.5: accept with prob [0.9512, 0.6065, 0.0067] at T = (10.0, 1.0, 0.1)
uphill by 2.0: accept with prob [0.8187, 0.1353, 0.0] at T = (10.0, 1.0, 0.1)
uphill by 5.0: accept with prob [0.6065, 0.0067, 0.0] at T = (10.0, 1.0, 0.1)
A multimodal function
The Rastrigin function has a local minimum near every integer point and its global minimum 0 at the origin. Gradient methods stop in whichever valley they start; annealing hops between them:
import numpy as np
from scipy.optimize import minimize
f = lambda x: 10 * len(x) + np.sum(x**2 - 10 * np.cos(2 * np.pi * x))
rng = np.random.default_rng(0)
x0 = np.array([3.3, -2.7])
print("BFGS from x0:", np.round(minimize(f, x0, method="BFGS").x, 3), " f =", round(float(minimize(f, x0, method="BFGS").fun), 4))
x, fx = x0.copy(), f(x0); best = (fx, x.copy())
T = 10.0
for k in range(20000):
y = x + rng.normal(scale=0.5, size=2)
fy = f(y)
if fy <= fx or rng.uniform() < np.exp(-(fy - fx) / T):
x, fx = y, fy
if fx < best[0]:
best = (fx, x.copy())
T *= 0.9995
print("annealing best:", np.round(best[1], 3), " f =", round(float(best[0]), 4), " final T =", f"{T:.1e}")BFGS from x0: [ 2.985 -2.985] f = 17.9092
annealing best: [-0.003 0.002] f = 0.0027 final T = 4.5e-04
A combinatorial problem: the travelling salesman
For discrete problems, a neighbour is a small change of the solution. For a TSP tour, the classic move is 2-opt: reverse a segment of the tour.
import numpy as np
rng = np.random.default_rng(1)
n = 30
cities = rng.uniform(0, 100, size=(n, 2))
D = np.linalg.norm(cities[:, None] - cities[None], axis=2)
length = lambda t: D[t, np.roll(t, -1)].sum()
tour = np.arange(n); L = length(tour); start = L
T = 50.0
for k in range(60000):
i, j = sorted(rng.choice(n, 2, replace=False))
new = np.r_[tour[:i], tour[i:j + 1][::-1], tour[j + 1:]] # 2-opt move
Ln = length(new)
if Ln <= L or rng.uniform() < np.exp(-(Ln - L) / T):
tour, L = new, Ln
T *= 0.9998
print(f"initial tour length {start:.1f}, after annealing {L:.1f}")initial tour length 1621.6, after annealing 413.5
Tuning
| Choice | Guidance |
|---|---|
| initial temperature | accept most uphill moves at the start (e.g. 80%) |
| cooling | geometric with per step or per batch of steps |
| neighbourhood | small enough to be local, large enough to move; adapt the step size to keep a target acceptance rate |
| stopping | when is tiny or no improvement for a long time; restart from the best point |
With a logarithmic schedule annealing provably finds a global minimum with probability 1, but that schedule is far too slow; practical schedules give good, not guaranteed, solutions.
In software
scipy.optimize.dual_annealing(generalized annealing plus local search),simanneal; annealing heuristics are common in VLSI placement, timetabling and routing.- Quantum annealers (D-Wave) apply the same idea to Ising-model formulations of combinatorial problems.
Exercises
Exercise 1: Acceptance probability
At , what is the probability of accepting a move that increases by 1?
Answer
.
Solution
.
Exercise 2: Cooling time
With and , after how many steps is below 0.01?
Answer
About 6905.
Solution
gives .
Exercise 3: SciPy's dual annealing (code)
Minimize the 2D Rastrigin function with scipy.optimize.dual_annealing on .
Answer
It finds the global minimum at the origin.
Solution
import numpy as np
from scipy.optimize import dual_annealing
f = lambda x: 10 * len(x) + np.sum(x**2 - 10 * np.cos(2 * np.pi * x))
r = dual_annealing(f, bounds=[(-5, 5)] * 2, seed=0)
print(np.round(r.x, 6) + 0, round(r.fun, 8) + 0)[0. 0.] 0.0
Test yourself
In simulated annealing, an uphill move by is accepted with probability…
- 0
- 1
As the temperature decreases, the algorithm…
- accepts more uphill moves
- accepts fewer uphill moves and behaves like local search
- stops evaluating
- becomes gradient descent with exact steps
A standard neighbourhood move for TSP tours is…
- 2-opt: reversing a segment of the tour
- adding a city
- sorting the cities
- a gradient step