Search as Optimization: Hill Climbing

The state-space landscape

Picture every possible candidate solution laid out on the ground, with the height at each spot equal to the solution's objective value. Optimizing means finding the highest peak (the global maximum). If the objective is a cost, as in Chapter 2's MSE, you flip the picture and look for the lowest valley, the global minimum. The two are equivalent: maximize \(f\) = minimize \(-f\).

A local search algorithm needs three things:

  1. A state representation: what one candidate looks like (a weight vector, a bitstring, a permutation of hostels).
  2. An objective function \(f(\text{state})\): higher is better (or "cost", lower is better).
  3. A neighbourhood: which states are reachable by one small change (nudge one weight, flip one bit, swap two hostels).

Local search keeps only the current state (or a few) in memory and moves to neighbours. Two big advantages follow: it uses constant memory, and it works in spaces far too large to enumerate, including infinite or continuous ones.

Hill climbing

The simplest idea of all: look at your neighbours, move to the best one, and repeat until no neighbour is better.

function HILL-CLIMBING(problem):
    current ← a starting state (often random)
    loop:
        neighbour ← the highest-valued successor of current
        if value(neighbour) ≤ value(current):
            return current          # a peak (maybe only a local one!)
        current ← neighbour

It's also called greedy local search, because it always grabs the best immediate improvement without thinking ahead. In continuous spaces, "move in the direction of steepest improvement" becomes gradient ascent/descent, which is the algorithm that trains almost all of modern ML. Hill climbing is its discrete ancestor.

Worked example: 8-queens

Place 8 queens on a chessboard so that no two attack each other (same row, column or diagonal). Here is a local-search formulation:

  • State: one queen per column, so a state is 8 numbers: the row of each column's queen. There are \(8^8 \approx 16.7\) million states.
  • Cost \(h\): the number of pairs of queens attacking each other. Goal: \(h = 0\).
  • Neighbours: move one queen to another square in its column: \(8 \times 7 = 56\) neighbours.
import random

def conflicts(state):
    """Number of pairs of queens attacking each other. state[c] = row of the queen in column c."""
    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 hill_climb(n=8, rng=random):
    state = [rng.randrange(n) for _ in range(n)]
    steps = 0
    while True:
        best, best_h = None, conflicts(state)
        for col in range(n):                      # all n*(n-1) neighbours: move one queen in its column
            for row in range(n):
                if row == state[col]:
                    continue
                nb = state.copy(); nb[col] = row
                h = conflicts(nb)
                if h < best_h:
                    best, best_h = nb, h
        if best is None:                          # no neighbour is better: local minimum
            return state, conflicts(state), steps
        state, steps = best, steps + 1

rng = random.Random(1)
results = [hill_climb(rng=rng) for _ in range(1000)]
solved = [r for r in results if r[1] == 0]
print("solved: %.1f%% of runs" % (100 * len(solved) / len(results)))
print("avg steps when solved: %.1f" % (sum(r[2] for r in solved) / len(solved)))
print("avg steps when stuck : %.1f" % (sum(r[2] for r in results if r[1] > 0) / (len(results) - len(solved))))

def random_restart(n=8, rng=random):
    restarts = 0
    while True:
        state, h, _ = hill_climb(n, rng)
        if h == 0:
            return state, restarts
        restarts += 1

state, restarts = random_restart(rng=rng)
print("solution:", state, "after", restarts, "restarts")
solved: 15.6% of runs
avg steps when solved: 4.2
avg steps when stuck : 3.1
solution: [0, 5, 7, 2, 6, 3, 1, 4] after 1 restarts

These numbers match the classic result in AIMA §4.1 (14% solved, 4 steps on average when it works, 3 when it gets stuck). Hill climbing is very fast, a handful of steps, but it fails about 85% of the time. Why?

The three ways hill climbing gets stuck

local maximum "flat" local max shoulder global maximum state space plateau region
A one-dimensional landscape. Hill climbing from the left stops at the orange dot forever.
  1. Local maxima: a peak that is higher than all its neighbours but lower than the global maximum. Hill climbing stops there, because every move looks worse.
  2. Plateaus: flat areas where all neighbours have the same value. There is no uphill direction to follow, so the algorithm wanders or stops. A shoulder is a plateau that does eventually rise again.
  3. Ridges: a sequence of local maxima arranged diagonally. Every single-step move goes downhill even though the ridge itself rises, because the neighbourhood moves are axis-aligned while the ridge is diagonal. This matters a lot for the GA lab: polynomial weights are tightly coupled, so changing one weight alone almost always makes things worse.

Try it on a bumpy 1-D landscape. Hill climbing from the left usually stops on the first or second hump. Then switch to random-restart.

Variants that help

VariantIdeaFixes
Steepest-ascentEvaluate all neighbours, take the best (what we did above)—
First-choiceGenerate random neighbours until one is better, then take itNeighbourhoods too large to scan (thousands of neighbours)
StochasticChoose randomly among uphill moves, weighted by steepnessSometimes finds better peaks
Sideways movesAllow moves to equal-valued neighbours (with a limit, e.g. 100)Plateaus and shoulders. 8-queens success rises from 14% to 94%!
Random-restart"If at first you don't succeed, try, try again": restart from a random state until solvedLocal maxima, in probability

How many restarts do we need?

If one run succeeds with probability \(p\), the number of runs until the first success follows a geometric distribution, with expected value \(1/p\). For 8-queens, \(p \approx 0.14\), so about \(1/0.14 \approx 7\) runs (6 failures + 1 success). Expected total steps ≈ \(1 \times 4 + 6 \times 3 = 22\). That's tiny! Random-restart hill climbing is complete with probability 1: it will eventually find a solution if one exists, because every restart has a nonzero chance.

Exam corner
  • Know the 3 failure modes by name, with a picture: local maxima, plateaus (and shoulders), ridges.
  • "Expected number of restarts = \(1/p\)" is a free mark. Remember that it counts runs, including the successful one.
  • Hill climbing is neither complete nor optimal. Random restart makes it complete (with probability 1) but not efficient in general.
  • Be ready to run one step by hand: list all neighbours' values and pick the best.
Connections

Gradient descent on the MSE of Chapter 2 is hill climbing with an infinitely fine neighbourhood. It never gets stuck there because MSE for linear models is convex: one valley, no local minima. Neural network losses are not convex, which is why deep learning borrows the tricks in this chapter: random initialization (restarts), noise in stochastic gradient descent (annealing) and populations of models (ensembles).