Value Iteration and Policy Iteration
The Bellman equations are \(n\) non-linear equations in \(n\) unknowns. There are two classic ways to solve them. Both are dynamic programming, and both need the full model (\(P\) and \(R\)).
Value iteration
The idea: start with arbitrary utilities (say all zeros), then repeatedly apply the Bellman equation as an update, using the current estimates on the right-hand side:
$$ U_{k+1}(s) \;\leftarrow\; R(s) + \gamma \max_a \sum_{s'} P(s'\mid s,a)\, U_k(s'). $$function VALUE-ITERATION(mdp, ε):
U ← 0 for every state
repeat:
δ ← 0
for each state s:
U'[s] ← R(s) + γ · max_a Σ_s' P(s'|s,a) · U[s']
δ ← max(δ, |U'[s] − U[s]|)
U ← U'
until δ < ε(1−γ)/γ # (if γ = 1, just use δ < ε)
return U
\(U_k(s)\) is the optimal expected reward if Bolt has only \(k\) steps left. After 1 iteration only the terminals "know" their value. After 2, their neighbours know the goal is one step away. After \(k\), states up to \(k\) steps from the goal have meaningful values. The value floods backward from the rewards through the grid, like ink spreading in water. Watch it happen in the widget below.
Worked by hand: the first sweeps
Take the 4×3 world with \(R = -0.04\), \(\gamma=1\), and \(U_0 = 0\) everywhere. Coordinates are (column, row) with (0,0) at the bottom-left.
Iteration 1. Every non-terminal gets \(-0.04 + \max_a(\text{weighted sum of zeros}) = -0.04\). Terminals are fixed at ±1.
Iteration 2, for cell (2,2), just left of +1. Try action E:
$$ 0.8\,U_1(3,2) + 0.1\,U_1(2,2)_{\text{N bumps, stays}} + 0.1\,U_1(2,1)_{\text{S}} = 0.8(1) + 0.1(-0.04) + 0.1(-0.04) = 0.792 $$Every other action is worse (the others mostly reach −0.04 states), so \(U_2(2,2) = -0.04 + 0.792 = 0.752\). All other non-terminals are still far from +1 and get \(-0.08\).
Iteration 3, for (2,2) again with action E: \(0.8(1) + 0.1(0.752) + 0.1(-0.08) = 0.8672\), so \(U_3(2,2) = 0.8272\). The value now reaches (1,2): action E gives \(0.8(0.752) + 0.1(-0.08) + 0.1(-0.08) = 0.5856\), so \(U_3(1,2) = 0.5456\).
| Cell | \(U_1\) | \(U_2\) | \(U_3\) | \(U_4\) | … \(U_{30}\) (converged) |
|---|---|---|---|---|---|
| (2,2) | −0.040 | 0.752 | 0.827 | 0.888 | 0.918 |
| (1,2) | −0.040 | −0.080 | 0.546 | 0.731 | 0.868 |
| (0,2) | −0.040 | −0.080 | −0.120 | 0.372 | 0.812 |
| (2,1) | −0.040 | −0.080 | 0.454 | 0.567 | 0.660 |
| (0,0) start | −0.040 | −0.080 | −0.120 | −0.160 | 0.705 |
Things to try:
- Press Sweep repeatedly from Reset. The arrows near the goal settle first, and the far corner settles last.
- Notice the policy often becomes optimal long before the values converge. Policy iteration exploits this.
- Set the living reward to −2 (rush to any exit), −0.2 (shortcut), −0.01 (super-cautious wall-hugging) and run to convergence each time.
- Now try +0.1 with γ = 1. The values grow by 0.1 every sweep and never converge, because staying forever is worth infinite reward. Lower γ to 0.9 and it converges: every cell is then worth 0.1/(1 − 0.9) = 1, exactly as much as the +1 exit, so Bolt has no reason to deliver at all. Reward design matters!
- Set slip noise to 0. The world becomes deterministic, and the policy is just the shortest path.
- Set γ to 0.6. Bolt becomes short-sighted: distant cells barely feel the +1.
Why does it converge? (The contraction argument)
Let \(B\) be the Bellman update operator, \(U_{k+1} = B U_k\). For any two utility vectors,
$$ \lVert BU - BU' \rVert_\infty \le \gamma\, \lVert U - U' \rVert_\infty. $$Each update shrinks the distance between any two estimates by a factor \(\gamma\). So \(B\) is a contraction, it has a unique fixed point (the true \(U\)), and the error shrinks geometrically: \(\lVert U_k - U\rVert \le \gamma^k \lVert U_0 - U\rVert\). In practice, a stopping rule follows: if \(\lVert U_{k+1} - U_k\rVert < \varepsilon(1-\gamma)/\gamma\), then \(\lVert U_{k+1} - U\rVert < \varepsilon\).
The number of iterations needed to reach error \(\varepsilon\) is about \(\log(R_{\max}/(\varepsilon(1-\gamma))) / \log(1/\gamma)\), so it grows quickly as \(\gamma \to 1\). Far-sighted agents are expensive.
Value iteration in code
import numpy as np
# ---- Bolt's 4x3 world (AIMA Fig 17.1). (col, row) with (0,0) bottom-left; (1,1) is a wall ----
COLS, ROWS, WALL = 4, 3, (1, 1)
TERMINAL = {(3, 2): +1.0, (3, 1): -1.0}
STATES = [(c, r) for c in range(COLS) for r in range(ROWS) if (c, r) != WALL]
ACTIONS = {"N": (0, 1), "S": (0, -1), "E": (1, 0), "W": (-1, 0)}
SIDEWAYS = {"N": "EW", "S": "EW", "E": "NS", "W": "NS"}
def step(s, a):
"""Where Bolt ends up if it actually moves in direction a (bumping into walls = stay put)."""
nxt = (s[0] + ACTIONS[a][0], s[1] + ACTIONS[a][1])
return nxt if nxt in STATES else s
def transitions(s, a):
"""P(s' | s, a): 0.8 intended direction, 0.1 each perpendicular direction."""
out = {}
for prob, direction in [(0.8, a), (0.1, SIDEWAYS[a][0]), (0.1, SIDEWAYS[a][1])]:
s2 = step(s, direction)
out[s2] = out.get(s2, 0) + prob
return out
def R(s):
return TERMINAL.get(s, -0.04) # small "living cost" for every non-terminal step
def expected_utility(s, a, U):
return sum(p * U[s2] for s2, p in transitions(s, a).items())
def value_iteration(gamma=1.0, eps=1e-6):
U = {s: 0.0 for s in STATES}
k = 0
while True:
U_new, delta = {}, 0.0
for s in STATES:
if s in TERMINAL:
U_new[s] = R(s)
else: # Bellman update
U_new[s] = R(s) + gamma * max(expected_utility(s, a, U) for a in ACTIONS)
delta = max(delta, abs(U_new[s] - U[s]))
U, k = U_new, k + 1
if delta < eps:
return U, k
def greedy_policy(U, gamma=1.0):
return {s: max(ACTIONS, key=lambda a: expected_utility(s, a, U)) for s in STATES if s not in TERMINAL}
def show(U, pi=None):
for r in reversed(range(ROWS)):
row = []
for c in range(COLS):
s = (c, r)
if s == WALL: row.append(" #### ")
elif pi and s in pi: row.append(f"{U[s]:6.3f} {pi[s]}")
else: row.append(f"{U[s]:6.3f} ")
print(" ".join(row))
U, iters = value_iteration(gamma=1.0)
print(f"converged after {iters} iterations")
show(U, greedy_policy(U))converged after 30 iterations
0.812 E 0.868 E 0.918 E 1.000
0.762 N #### 0.660 N -1.000
0.705 N 0.655 W 0.611 W 0.388 W
These are exactly the utilities in AIMA Fig. 17.3. Look at cell (3,0), bottom-right, with value 0.388 and action W. The cell directly North of it is the −1 pit, so going North would mean falling in with probability 0.8. The optimal policy goes away from the goal and takes the long way round. Also (2,0) chooses W, not N: it prefers the long, safe route through the left column.
Policy iteration
Value iteration polishes the utilities to many decimal places even though only the policy matters, and the policy usually stabilizes much earlier. Policy iteration works with policies directly by alternating two steps:
- Policy evaluation: given policy \(\pi_i\), compute \(U^{\pi_i}\). The policy is fixed, so there is no max and the Bellman equations are linear: $$ U^{\pi_i}(s) = R(s) + \gamma \sum_{s'} P(s' \mid s, \pi_i(s))\, U^{\pi_i}(s'). $$ That's \(n\) linear equations in \(n\) unknowns, solvable exactly in \(O(n^3)\) with Gaussian elimination.
- Policy improvement: make the policy greedy with respect to those utilities: $$ \pi_{i+1}(s) = \arg\max_a \sum_{s'} P(s' \mid s, a)\, U^{\pi_i}(s'). $$
Repeat until the policy stops changing. At that point the policy satisfies the Bellman equation, so it is optimal.
def policy_evaluation(pi, gamma=1.0):
"""Solve the LINEAR system U(s) = R(s) + gamma * sum_s' P(s'|s,pi(s)) U(s') exactly."""
idx = {s: i for i, s in enumerate(STATES)}
A, b = np.eye(len(STATES)), np.array([R(s) for s in STATES])
for s in STATES:
if s not in TERMINAL:
for s2, p in transitions(s, pi[s]).items():
A[idx[s], idx[s2]] -= gamma * p
u = np.linalg.solve(A, b)
return {s: u[idx[s]] for s in STATES}
def policy_iteration(gamma=1.0):
pi = {s: "N" for s in STATES if s not in TERMINAL} # start: always go North
rounds = 0
while True:
U = policy_evaluation(pi, gamma)
rounds += 1
changed = 0
for s in pi: # policy improvement
best = max(ACTIONS, key=lambda a: expected_utility(s, a, U))
if expected_utility(s, best, U) > expected_utility(s, pi[s], U) + 1e-12:
pi[s], changed = best, changed + 1
print(f"round {rounds}: {changed} states changed their action")
if changed == 0:
return pi, U
pi, U = policy_iteration()
show(U, pi)round 1: 6 states changed their action
round 2: 1 states changed their action
round 3: 1 states changed their action
round 4: 1 states changed their action
round 5: 0 states changed their action
0.812 E 0.868 E 0.918 E 1.000
0.762 N #### 0.660 N -1.000
0.705 N 0.655 W 0.611 W 0.388 W
Five rounds instead of 30 sweeps, and the identical answer. Switch the widget to Policy iteration to watch the rounds.
Comparison
| Value iteration | Policy iteration | |
|---|---|---|
| Works on | Utilities | Policies |
| Cost per iteration | \(O(|S|^2|A|)\), cheap | \(O(|S|^3)\) to solve the linear system, plus improvement |
| Number of iterations | Many (depends on \(\gamma\), \(\varepsilon\)) | Few. Finite, since there are only finitely many policies, and each round strictly improves the policy until it is optimal |
| Exact answer? | Approximate (stops at \(\varepsilon\)) | Exact optimal policy |
| Best when | Many states, cheap sweeps | Fewer states, or a good initial policy is known |
Modified policy iteration sits in between: evaluate the policy approximately with \(k\) simplified Bellman sweeps (no max) instead of an exact solve. With \(k=1\) it is value iteration. The widget's PI uses this approach. Asynchronous versions update states in any order, prioritizing those whose values are changing most.
The MDL MDP assignment typically gives you a story-based world: a character with a few health levels, arrows or stamina, and a monster or a goal, with stochastic action outcomes. You're asked to:
- Enumerate the state space carefully: the Cartesian product of all components, e.g. (position, health, materials, monster state). Write a function from state tuple to index and back. Most bugs live here.
- Encode
P(s'|s,a)for every action from every state. Check that each row sums to 1 with an assert. - Run value iteration with the given γ and ε, and log the utility and action of every state at every iteration in the required trace format.
- Simulate a few episodes from given start states following the final policy.
- Change one parameter (γ, step cost, a probability) and explain the behavioural change, as in the "how reward shapes behaviour" table in §5.2.
Note which convention the assignment uses: reward on states \(R(s)\), on transitions \(R(s,a,s')\), or a step cost per action. The Bellman update changes slightly: \(U(s) = \max_a \sum_{s'} P(s'|s,a)[R(s,a,s') + \gamma U(s')]\).