Dynamic programming: policy evaluation, policy iteration and value iteration
Before this lesson: lesson 01 (MDPs, , , the Bellman equations); the -norm (linear algebra 11); reading a proof by steps (foundations 09). Time: about 70 minutes, plus the notebook.
Why this matters #
DP is the exact version of reinforcement learning. Later lessons replace its parts with samples and neural networks: TD learning is sampled policy evaluation (lesson 04), Q-learning is sampled value iteration (lesson 05), actor-critic methods alternate approximate evaluation and improvement (lesson 08), and AlphaZero uses tree search as a policy improvement step and a network as the evaluation (lesson 10). The contraction argument of this lesson explains why these methods converge, and its failure explains why some of them diverge with function approximation (lesson 06).
1. Predict first #
2. The picture #
Evaluation: apply the Bellman equation again and again #
Lesson 01 solved with one linear solve. There is a second way. Start from any guess, for example , and use the right side as an update:
Each sweep updates every state from the values of the previous sweep. On the 4×4 gridworld (random policy, reward per step, ), the first row of is:
| sweep | first row of |
|---|---|
| 0 | |
| 1 | |
| 2 | |
| 3 | |
| 10 | |
After sweeps, is the expected reward of the first steps. The values creep towards . But look at the greedy policy with respect to : from on, it is already the optimal policy (move straight to the nearest corner). Policies settle long before values do.
Improvement: act greedily with respect to the values #
Given values , the greedy policy picks in each state an action with the largest one-step lookahead . Evaluate and improve in turn, and you get policy iteration. Do one sweep, then improve, and you get value iteration.
Press "Evaluate: one sweep" a few times, then "Improve (greedy)". The blue values are ; the orange arrows are the policy (several arrows = a tie, the agent picks one of them at random). After three sweeps the greedy arrows are already optimal. Then try "Run policy iteration" and "Run value iteration", and the other worlds: in the slippery world, raise the slip and watch the policy move away from the pit; in the cliff world, the safe path moves up when the slip is above 0.
Generalized policy iteration #
Both methods are instances of one pattern. Evaluation pushes towards of the current policy. Improvement pushes towards the greedy policy of the current . Each move spoils the other a little: after improvement, is no longer the value of the new policy; after evaluation, the policy is no longer greedy. But the two together move to the only point where both are satisfied: the optimal value and an optimal policy . Sutton and Barto call this pattern generalized policy iteration (GPI).
In the 4×4 gridworld you compute for the random policy exactly () and then take the greedy policy with respect to it. What do you get?
Next to each cell, the value is higher (less negative) in the direction of the nearest corner, so the one-step lookahead points along shortest paths. Here one improvement step is enough. In general it is not: on the robot vacuum, greedy with respect to the random policy's values gives "always clean", which is not optimal (lesson 01).
3. Definitions and main results #
Iterative policy evaluation #
Algorithm (iterative policy evaluation).
- Start with , for example .
- Synchronous sweep: compute every state from the old vector, .
- Stop when is small (the stopping rule below says how small).
In place. Keep one array and overwrite as soon as it is computed, so later states in the same sweep already use the new values. This uses half the memory and usually converges faster. On the 4×4 gridworld with tolerance , synchronous sweeps need 426 sweeps; in-place sweeps in row order need 272.
Each sweep costs for a dense model, and much less when each state has only a few successors. Why does it converge? The next section answers this for . For (the 4×4 gridworld), it converges when the policy ends every episode with probability 1: then restricted to the non-terminal states has spectral radius below 1.
The Bellman operators #
Treat a value function as a vector . Two maps from vectors to vectors:
is the Bellman expectation operator, . is the Bellman optimality operator. In this language, the Bellman equations of lesson 01 say that is a fixed point of () and is a fixed point of . Iterative policy evaluation is ; value iteration will be .
Monotonicity. If in every state, then and . Reason: , so a larger gives a larger average, and the max of larger numbers is larger. We use this twice below.
The max lemma #
Lemma (max lemma). For two functions on a finite set, .
Proof. Suppose (the other case is the same with and swapped). Let be a maximiser of . Then , so
In words: if no action changes its value by more than , the best value cannot change by more than either. The best action may change, but the best value moves at most as much as the values themselves.
The contraction theorem #
Drag the two points. The robot vacuum has two states, so a value function is a point . The blue and the violet are two guesses; the arrows show where sends them. The dashed square around has half-width , so lies on its edge. The shaded square around is times smaller, and always lands inside it. Press "Apply T" a few times: both points move to the same fixed point . The small chart is the max lemma in state H: the gap between the two maxima is never larger than the largest vertical gap.
Theorem (contraction). For and all ,
Hence has exactly one fixed point , and value iteration satisfies, from any start ,
Proof.
- Fix a state . Apply the max lemma with and the same expression with . The rewards cancel in : .
- The weights are and sum to at most 1, so a weighted sum of numbers of size at most has size at most . So .
- This holds for every ; take the max over . This is the contraction.
- At most one fixed point. If and , then . With this forces .
- A fixed point exists. By step 3, , so is a Cauchy sequence and has a limit ( is complete). is continuous, so . (This is Banach's fixed-point theorem.)
- Rate. .
- Stopping rule. By step 6 and the triangle inequality, . Move the last term to the left: .
The same proof without the max (step 1 without the lemma) shows that is a -contraction too. So iterative policy evaluation converges to from any start, with the same rate and stopping rule.
How many iterations? To shrink the error by a factor you need , that is
The number of iterations grows like the effective horizon .
Move and predict the slope. On a log scale, the true error (blue) follows the theorem's line (violet, dashed); the slope is . The grey dashed line is the stopping-rule bound, which you can compute without knowing . The orange line marks the iteration from which the greedy policy is optimal: on the 5×5 grid with this is iteration 29, while the value error is still about 1.15.
Value iteration with . About how many iterations does the theorem need to shrink the error by a factor ?
You need , so . The rule of thumb gives the same. The answer 14 forgets that each step only multiplies the error by 0.99.
On the robot vacuum (), value iteration from gives , so . What does the stopping rule guarantee?
. The bound is true but loose: the real error is . The point of the rule is that it needs only two consecutive iterates, not .
is the fixed point of #
Lesson 01 used this fact. Here is the proof.
Theorem. Let , let be the fixed point of , and let be greedy with respect to . Then , and for every policy . So , and is optimal.
Proof
- Greedy means . With , this gives . is the only fixed point of , so .
- For any policy and any , an average over actions is at most the max: . So .
- Apply again and use monotonicity: . By induction, for all .
- Let : (contraction). So . With step 1, .
This proof compares stationary policies. A classical result (Puterman 1994, ch. 6) shows that policies that use the whole history or the time cannot do better in a finite discounted MDP, so nothing is lost.
The policy improvement theorem #
Theorem (policy improvement). Let and be two policies with
Then for every state . If the first inequality is strict in some state, the second is strict there too.
For a deterministic the condition reads : "take 's action now, then follow " is at least as good as following . The theorem says: then following forever is also at least as good.
Proof.
- The left side of the condition is . So the condition says .
- Apply and use monotonicity: . By induction the sequence increases with .
- It converges to the fixed point of , which is . An increasing sequence stays above its first terms, so .
- If in some state , step 3 gives .
The same idea, unrolled in time: with the first action from ; apply the condition again at , then at , and so on. Every rewritten step follows , and the leftover term goes to 0.
The greedy policy satisfies the condition, because the max is at least the -average: .
Policy iteration #
Algorithm (policy iteration). Start from any policy . For :
- Evaluate: compute exactly (one linear solve, lesson 01).
- Improve: , where . If the current action is already among the best, keep it.
- If , stop.
Why it stops at an optimal policy.
- Each step is at least as good: (policy improvement theorem).
- If the policy changes, some state gets a strictly better action, so the value strictly increases there. Then no policy can appear twice.
- There are at most deterministic policies, so the loop stops after finitely many steps.
- When it stops, is greedy with respect to its own values: . So is the fixed point of , which is .
The rule "keep the current action when it is among the best" matters. Without it, two tied actions can make the policy switch back and forth forever (with floating-point numbers, use a small tolerance such as ).
Why can policy iteration never produce a policy that is worse than the previous one in some state?
The improvement theorem compares the values of two policies state by state. The contraction is about iterating one operator, not about comparing policies. Finiteness explains why the loop stops, not why each step helps. The greedy policy with respect to is better, but not optimal in general.
Value iteration and its relatives #
Algorithm (value iteration). Start from any (often 0). Repeat until is below your tolerance. Return the greedy policy with respect to the final .
Value iteration is policy iteration with one sweep. Let be greedy with respect to . Then : one improvement, then one sweep of evaluation of the new policy, instead of a full solve.
What is ? is the best expected discounted reward over the first steps only. It is not the value of any stationary policy in general. For example, on the robot vacuum is just "the best reward now". Only the limit is a policy's value.
Modified policy iteration. Do sweeps of evaluation after each improvement, . With this is value iteration; with it is policy iteration. Values in between often work best in practice.
Generalized policy iteration is any scheme that interleaves some evaluation with some improvement, in any order and in any amount, state by state if you like. If both continue, the process converges to and (the GPI figure in section 2). Almost every RL algorithm has this form.
Value iteration on the robot vacuum gives . Is there a stationary policy with ?
counts the rewards of steps; a policy's value counts all future rewards. Here a direct check shows that no policy, deterministic or stochastic, has (the four deterministic policies give , , and ). Only the limit is guaranteed to be a policy's value.
The cost of the two methods #
| one iteration costs (dense model) | number of iterations | |
|---|---|---|
| policy iteration | : a linear solve, then the improvement | few in practice (at most ) |
| value iteration | : one max backup of every state | about ; many when |
Here and . Policy iteration wins when is close to 1 and the state space is small enough for a linear solve. Value iteration wins when is large and is moderate, or when only a good policy (not exact values) is needed.
Predict, then press "Step both" a few times, and then "Run both to the end". Each step is one iteration of each method. On the 5×5 grid, policy iteration finishes after 5 evaluations; value iteration needs 154 sweeps to reach , but its greedy policy is optimal much earlier. The cost line uses the dense model of the table.
Answers to section 1. (1) About 5: on the 5×5 grid, policy iteration needs 5 evaluations when tied actions share the probability (the widget above), and 3 when ties go to the lowest action index. (2) Before: the greedy policy is optimal from iteration 29, while the value error is still about 1.15. (3) About 10 times more, because the number of iterations grows like : on the 5×5 grid, 162 iterations for and 1904 for (error below ).
Linear programming, asynchronous DP, and the curse of dimensionality
A linear program. is also the solution of
Why: the constraints say . By monotonicity, , so every feasible is in every state. And itself is feasible. So is the smallest feasible point, and it minimises any sum with positive weights. This gives a third exact method, and LP duality leads to the "occupancy measure" view used in offline RL and imitation learning.
Asynchronous DP. You do not have to sweep all states in order. Update any state at any time, using the latest values of the others. As long as every state is updated infinitely often, the values still converge to or (Bertsekas and Tsitsiklis). In-place sweeps are one example. Real-time DP updates only the states that an agent visits, which focuses the work on relevant states.
The curse of dimensionality. DP needs the model and touches every state in every sweep. A state made of variables with 10 values each has states. Backgammon has about positions and Go about . So we need two more ideas: learning from samples instead of the model (lessons 03–05) and function approximation instead of a table (lesson 06).
4. Worked example #
(a) Policy iteration on the robot vacuum (, states H, L), starting from "always clean".
Evaluation 1. From lesson 01: .
Improvement 1. Compute :
- H: clean ; charge . Keep clean.
- L: clean ; charge . Switch to charge.
Evaluation 2. For "clean in H, charge in L": (lesson 01). Both states improved, as the theorem promises.
Improvement 2.
- H: clean ; charge . Keep clean.
- L: clean ; charge . Keep charge.
Nothing changes, so the policy is optimal and . Policy iteration needed two evaluations.
(b) Value iteration on the robot vacuum, from . Each step takes, in each state, the max of "clean" and "charge".
- : H: . L: . So .
- : H: . L: . So .
- : H: . L: . So .
At , the max in L is "charge" for the first time: the greedy policy with respect to is already optimal. But the values are still far from :
- true error: ;
- theorem: ✓;
- stopping rule: ✓.
(c) The 5×5 gridworld (Sutton and Barto, Example 3.5, ). From cell A every action earns and jumps to A′ in the bottom row. With (from value iteration):
The cell left of A has no reward of its own, and its best move is into A: . Every optimal value is the best, over the four actions, of "reward now plus times the value of the next cell": exactly the optimality equation.
5. In code #
NumPy and SciPy check the worked example: policy iteration, value iteration with the stopping rule, and the linear program of the deeper box as a third route to .
import numpy as np
from scipy.optimize import linprog
gamma = 0.9
P = np.zeros((2, 2, 2)) # robot vacuum: P[s, a, s'], states (H, L)
P[0, 0] = [0.5, 0.5]; P[0, 1] = [1, 0] # actions (clean, charge)
P[1, 0] = [0, 1]; P[1, 1] = [1, 0]
R = np.array([[2.0, 0.0], [1.0, 0.0]])
def evaluate(pi): # deterministic pi: one action per state
P_pi, r_pi = P[[0, 1], pi], R[[0, 1], pi]
return np.linalg.solve(np.eye(2) - gamma * P_pi, r_pi)
# policy iteration from "always clean"
pi = np.array([0, 0])
while True:
V = evaluate(pi)
print(pi, V.round(3)) # [0 0] [11.818 10. ] then [0 1] [13.793 12.414]
new = (R + gamma * P @ V).argmax(axis=1) # greedy (no ties here)
if np.array_equal(new, pi):
break
pi = new
# value iteration with the stopping rule
V, k = np.zeros(2), 0
while True:
V_new = (R + gamma * P @ V).max(axis=1)
k += 1
done = gamma / (1 - gamma) * np.abs(V_new - V).max() < 1e-6
V = V_new
if done:
break
print(k, V.round(4)) # 156 [13.7931 12.4138]
# linear program: minimise sum V(s) subject to V(s) >= R(s,a) + gamma * sum_s' P V
A_ub = gamma * P.reshape(4, 2) - np.repeat(np.eye(2), 2, axis=0) # rows (s, a)
res = linprog(c=np.ones(2), A_ub=A_ub, b_ub=-R.reshape(4), bounds=[(None, None)] * 2)
print(res.x.round(3), 400 / 29, 360 / 29) # [13.793 12.414] 13.793... 12.413...
P[[0, 1], pi] picks the row P[s, pi[s]] for each state, which is for a deterministic policy.
6. Where it shows up #
- Planning with a known model. Inventory control, queueing and maintenance problems in operations research, and small control problems in engineering, are solved exactly with value or policy iteration, or with the LP.
- Q-learning and DQN are sampled value iteration on ; their targets are one application of (lessons 05 and 06).
- Actor-critic and PPO follow GPI: a critic does approximate evaluation, the policy update does a soft improvement (lessons 08 and 09).
- AlphaZero and expert iteration use tree search as the improvement step and a value network as the evaluation (lesson 10).
- Model-based RL learns and from data and then plans with DP-like updates (Dyna, lesson 10).
- ML for science. Planning on a learned emulator, for example the control of a physical process with a fitted model, is DP on an approximate MDP. The contraction bound tells you how errors in the model or in the values propagate: an error in each backup gives at most in the final values.
7. Common mistakes #
- Expecting values and policies to converge together. The greedy policy is often optimal long before the values are accurate. Stop by the policy when you only need the policy.
- Mixing synchronous and in-place updates by accident.
V = r_pi + gamma * P_pi @ Vis synchronous; a loop that writesV[s]and readsVin the same sweep is in place. Both converge, but the iteration counts differ. - Policy iteration that never stops. With ties and floating-point noise, the argmax can switch between equal actions forever. Keep the current action if it is within a small tolerance of the best.
- Using the stopping rule with . The factor is infinite; the contraction proof does not apply. Episodic problems with converge only for policies that end every episode.
- Taking as a policy's value. Value iteration's is a -step value, not of any policy. Evaluate the greedy policy if you need its true value.
- Forgetting the model. Every method here needs and . Without them, use the sample-based methods of lessons 03–05.
8. Check yourself #
- Show that is monotone: implies .
Answer
For each , because . So every term inside the max is at most the matching term for , and the max of smaller numbers is at most the max of larger numbers. - Value iteration with gives . What is the guaranteed bound on ?
Answer
. - Why does policy iteration stop after finitely many iterations?
Answer
Each change gives a strictly better value in some state and no worse value anywhere, so no policy can repeat. There are at most deterministic policies. (This needs the rule that ties keep the current action.) - Write one value-iteration step as "improvement plus evaluation".
Answer
Let be greedy with respect to . Then : one sweep of evaluation of the new greedy policy, starting from . - In the 5×5 gridworld, why is ?
Answer
From the corner , the best action moves right into A with reward 0. The optimality equation gives . - You have 10 000 states, 4 actions and . Would you start with policy iteration or value iteration? Why?
Answer
Policy iteration (or modified policy iteration). Value iteration needs about sweeps. Policy iteration needs a few linear solves; with sparse transitions an iterative solver handles states easily.
Define the Bellman optimality operator .
.
State the contraction property of .
for all (when ).
State the max lemma.
.
Give the stopping rule of value iteration.
.
About how many value-iteration steps shrink the error by a factor ?
.
State the policy improvement theorem.
If for every , then for every .
What does one iteration of policy iteration cost, and of value iteration?
PI: (a linear solve plus improvement), few iterations. VI: (one max backup), many iterations when .
Why is value iteration "policy iteration with one sweep"?
with greedy for : one improvement, then one evaluation sweep instead of a full solve.
What is generalized policy iteration, in one sentence?
Any interleaving of (partial) policy evaluation and (partial) greedy improvement; together they converge to and .
Compute the stopping-rule bound for and .
.
9. Interview angle #
- "Policy iteration or value iteration?" PI: few, expensive iterations (a linear solve each); good when is close to 1 and is moderate. VI: cheap iterations, about of them. Modified PI sits in between.
- "Why does value iteration converge?" is a -contraction in the -norm (max lemma plus , rows sum to at most 1), so Banach's theorem gives a unique fixed point and a geometric rate .
- "Prove the policy improvement theorem." The condition is ; monotonicity gives , and the limit is .
- "Why do we need anything beyond DP?" DP needs the model and a table over all states. Real problems have unknown dynamics and huge state spaces, so we sample (TD, Q-learning) and approximate (neural networks).
10. Practice #
The notebook for this lesson runs in Colab. It has five exercises, each with a check cell and a folded solution:
policy_evaluation_iterative: synchronous sweeps; count them on the 4×4 gridworld and compare with the linear solve.bellman_optimality_operator, and a numerical check of the contraction on 200 random pairs .value_iterationwith the stopping rule; reproduce of the 5×5 gridworld ( at A).policy_iterationwith stable tie-breaking; check that it agrees with value iteration and that values never decrease.- The linear program with
scipy.optimize.linprog: its solution equals .
11. Watch and read #
- Richard Sutton and Andrew Barto, Reinforcement Learning: An Introduction, 2nd ed., free PDF: chapter 4 (§4.1–4.7: policy evaluation, improvement, PI, VI, asynchronous DP, GPI); Example 4.1 is the 4×4 gridworld and Example 3.5 the 5×5 one.
- Alekh Agarwal, Nan Jiang, Sham Kakade, Wen Sun, Reinforcement Learning: Theory and Algorithms, free PDF: chapter 1 (contraction, policy iteration, the LP view) with complete proofs.
- Shangtong Zhang, Python code for Sutton and Barto, chapter 4 grid world: compare it with your notebook after you finish the exercises.
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.
No Google account needed: Python runs inside your browser. The first start downloads about 40 MB; your changes are saved in this browser only.