Escaping Local Optima: Annealing and Beam Search
Hill climbing never goes downhill, so it can't leave a local peak. A purely random walk goes anywhere but never settles. The two ideas in this section sit between those extremes: sometimes accept a worse move (simulated annealing), or keep several candidates alive at once (beam search). Genetic algorithms, in §3.3, combine both ideas.
Simulated annealing
The name comes from metallurgy. To make strong steel you heat it until its atoms move freely, then cool it slowly. At high temperature the atoms jump around, even into higher-energy arrangements. As it cools they settle, and a slow cooling lets them find a very low-energy crystal structure. Quench it (cool it instantly) and the atoms freeze in a messy, brittle state: a local minimum.
Simulated annealing (SA) copies this:
function SIMULATED-ANNEALING(problem, schedule):
current ← initial state
for t = 1, 2, 3, ...:
T ← schedule(t) # temperature, decreasing over time
if T ≈ 0: return current
next ← a RANDOM neighbour of current
ΔE ← value(next) − value(current) # for maximization
if ΔE > 0: current ← next # uphill: always accept
else: current ← next with probability e^(ΔE / T) # downhill: sometimes
Understanding the acceptance probability \(e^{\Delta E/T}\)
For a bad move, \(\Delta E < 0\), so \(\Delta E / T < 0\) and \(e^{\Delta E/T}\) lies between 0 and 1. This one formula has two properties:
- Worse moves are less likely: a larger \(|\Delta E|\) means a smaller probability.
- Higher temperature means more adventurous: when \(T\) is large, \(\Delta E/T \approx 0\) and \(e^0 = 1\), so almost everything is accepted (a random walk). As \(T \to 0\), the probability of any downhill move goes to 0, which is pure hill climbing.
| \(T = 2\) | \(T = 0.5\) | \(T = 0.1\) | |
|---|---|---|---|
| \(\Delta E = -1\) (slightly worse) | \(e^{-0.5} = 0.607\) | \(e^{-2} = 0.135\) | \(e^{-10} \approx 0.00005\) |
| \(\Delta E = -3\) (much worse) | \(e^{-1.5} = 0.223\) | \(e^{-6} = 0.0025\) | \(e^{-30} \approx 0\) |
Imagine shaking a tray with a ping-pong ball on a bumpy surface, trying to get the ball into the deepest hole. Shake hard at first: the ball bounces out of shallow holes easily, but it's harder to bounce out of deep ones. Then shake more and more gently. The ball spends more time in deep holes, and when you stop it is very likely in the deepest one. Temperature is how hard you shake.
Cooling schedules
- Geometric: \(T_{t+1} = \alpha T_t\) with \(\alpha \in [0.8, 0.999]\). By far the most common in practice.
- Linear: \(T_t = T_0 - ct\).
- Logarithmic: \(T_t = c / \log(1+t)\). Theory says that if \(T\) is lowered slowly enough (logarithmically), SA finds the global optimum with probability approaching 1. That is far too slow to use, but it is a nice guarantee.
Choosing \(T_0\): pick it so that, at the start, a typical bad move is accepted perhaps 50–80% of the time.
Back on the bumpy landscape, select Simulated annealing. Watch the dot jump around wildly at first and settle as \(T\) drops. Try a very fast cooling rate (α = 0.9), which "quenches" the search, and compare it with a slow one (0.995).
SA on 8-queens
import math, random
def conflicts(state):
n, h = len(state), 0
for i in range(n):
for j in range(i + 1, n):
if state[i] == state[j] or abs(state[i] - state[j]) == j - i:
h += 1
return h
def simulated_annealing(n=8, T0=2.0, alpha=0.995, max_steps=20000, rng=random):
state = [rng.randrange(n) for _ in range(n)]
E, T = conflicts(state), T0
for step in range(max_steps):
if E == 0:
return state, step
col, row = rng.randrange(n), rng.randrange(n) # a RANDOM neighbour, not the best one
nb = state.copy(); nb[col] = row
dE = conflicts(nb) - E # we are minimizing conflicts
if dE <= 0 or rng.random() < math.exp(-dE / T): # always accept better; sometimes worse
state, E = nb, E + dE
T = max(T * alpha, 1e-3) # cool down
return state, None
rng = random.Random(0)
runs = [simulated_annealing(rng=rng) for _ in range(200)]
ok = [s for s, steps in runs if steps is not None]
print("solved: %d / %d runs" % (len(ok), len(runs)))
print("median steps: %d" % sorted(st for _, st in runs if st is not None)[len(ok) // 2])solved: 195 / 200 runs
median steps: 725
Compare with plain hill climbing's 15.6%: SA solves 97.5% of runs. Each SA step is cheaper (it evaluates one random neighbour, not all 56), but it needs many more steps. Because we're minimizing cost here, the test is \(e^{-\Delta E/T}\) with \(\Delta E = \text{cost}(\text{next}) - \text{cost}(\text{current})\). Read the sign convention of every formula carefully in exams.
Local beam search
Instead of one current state, keep \(k\) of them:
- Start with \(k\) random states.
- Generate all successors of all \(k\) states.
- If any is a goal, stop. Otherwise keep the best \(k\) successors from the whole pool and repeat.
This is not the same as \(k\) independent restarts running in parallel. In beam search the \(k\) states share information: if one state finds a great region, its successors crowd out the successors of poor states, so effort moves to where the action is. "Come over here, the grass is greener!"
The danger is lack of diversity: all \(k\) states can quickly collapse into the same small region, which is just an expensive hill climb. The fix is stochastic beam search: choose the \(k\) survivors randomly, with probability increasing with their value. Now think of the \(k\) states as organisms, their successors as offspring and value as fitness. That's natural selection, one step away from a genetic algorithm.
Comparison so far
| Algorithm | Memory | Escapes local optima? | Key knob |
|---|---|---|---|
| Hill climbing | 1 state | No | neighbourhood |
| Random-restart HC | 1 state | Yes, by restarting | number of restarts |
| Simulated annealing | 1 state | Yes, by accepting bad moves | temperature schedule |
| Local beam search | \(k\) states | Partly (can lose diversity) | \(k\) |
| Stochastic beam | \(k\) states | Better | \(k\), selection pressure |
| Genetic algorithm (next) | population | Yes, by crossover + mutation | pop size, \(p_c\), \(p_m\), selection |
- The exploration vs. exploitation tension shows up here first: high temperature explores, low temperature exploits. It comes back in MDPs and reinforcement learning (Ch 5): should Bolt try a new route (explore) or take the known-good one (exploit)?
- The acceptance probability \(e^{\Delta E/T}\) is a Boltzmann distribution. The same exponential form appears in the softmax function of neural nets and in Gibbs sampling for Bayes nets (§7.4).