A robot must reach its dock along a cliff edge. One rule finds the worth of every square and the best move from it. On a slippery floor, policy iteration needs 5 rounds where value iteration needs 18 sweeps, and both give the same answer.
Learn the return, V and Q, the two Bellman equations, and the two algorithms that solve them exactly when you know the world.
Press Solve. Then drag Slip to 10% and solve again: the route moves away from the cliff. Then switch to Policy iteration. Then we build each piece: the return, V and Q, the Bellman equations, policy evaluation, why it converges, policy improvement, and both algorithms.
You need the MDP words from Lecture 1 (state, action, reward, policy) and a little Python. We build the rest from zero.
Based on Lecture 7 of CMU 16-831, Introduction to Robot Learning, taught by Guanya Shi. Every idea is re-taught here in our own words and toys. It follows Lecture 6, Imitation Learning II and leads to Lecture 8, Q-Learning.
Illustrative 6 by 4 grid, gamma 0.9. Every move costs 1. The dock ends the episode with value 0; a cliff square ends it with value −20. With slip s, a move goes sideways with chance s, half to each side. Value iteration stops when no value changes by more than 0.001. Policy iteration starts from “always up” and scores each policy exactly.
Chapter 0
Ask two questions about a robot in a corridor, and see one rule answer both
A robot stands in a corridor of four squares: A, B, C and D. D is its charging dock. Each move costs a little battery, so each move pays a reward of −1. Reaching the dock ends the episode. The robot can move left or right, and it knows exactly where each move lands.
It still has two questions. How good is each square, as a number? And which move is best from each square? Both answers depend on the whole future, not on the square alone.
Here is the rule that answers both. A square is worth the reward of the next move, plus a discounted worth of the square where that move lands. That sentence is the Bellman equation. Apply it to every square, over and over, and watch what happens.
Every square starts at 0. Each sweep applies the rule once to every square. Press Sweep and watch which squares change.
Illustrative corridor. Gamma is 0.9, every move from A, B or C pays −1, and the dock is worth 0. A grey dot means the two moves tie.
Two things happened. The dock's pull moved back one square per sweep, because each sweep looks only one move ahead. And when the numbers stopped, every arrow pointed right. The best move came out of the values.
This lesson builds that rule and two algorithms on it. Policy iteration scores a fixed plan, then improves it, and repeats. Value iteration folds the improvement into each sweep. Both reach the same answer, and both are sure to get there.
Chapter 1
Add up every reward that follows, and shrink each one by how late it comes
The robot walks right from A: three moves, three rewards of −1, then the dock. What is that whole future worth as one number? Call the time now t. Call the reward of the next move rt+1, the one after rt+2, and so on. Call the discount γ (gamma), a number between 0 and 1 that shrinks each later reward once more. The total is the return, Gt.
G-t equals r-t-plus-1, plus gamma times r-t-plus-2, plus gamma squared times r-t-plus-3, and so on.
Take the next reward r-t-plus-1 at full worth. Multiply the one after by gamma, the next by gamma twice, and so on. Add them all. The total is G-t.
From A, always right: rewards −1, −1, −1, then 0. With gamma 0.9: G = −1 − 0.9 − 0.81 = −2.71.
Why shrink later rewards? First, it keeps the sum finite. A robot that pays −1 forever has a return of −1/(1 − γ), which is −10 at gamma 0.9. Second, a reward now is worth more than the same reward later. Gamma near 1 makes a patient robot. Gamma near 0 makes a robot that sees one move ahead.
Each bar is the weight gamma to the k of the reward k steps after the first. Drag gamma and watch the far bars.
The return shown is the corridor's: A, always right, rewards −1, −1, −1, then 0.
Peel the first reward off the return. What is left is the return from the next step, shrunk once by gamma. This one line powers the whole lesson.
G-t equals r-t-plus-1 plus gamma times G-t-plus-1.
The return from here is the next reward r-t-plus-1, plus gamma times the return G-t-plus-1 from where you land.
From B, always right, the return is −1.9. So the return from A is G = −1 + 0.9 × (−1.9) = −2.71, the same as the long sum.
The failure. Set gamma to 1 and score the plan “always left”. The robot never docks, so the return is −1 − 1 − 1 with no end. The symptom: the values drop by 1 on every sweep. Measure the largest change per sweep; it never shrinks. The fix: use gamma below 1, or make sure every plan you score ends.
Chapter 2
Average the return over every future a square can have, with or without a chosen first move
On a slippery floor, the same plan from A gives different futures. So a square's worth is an average return. Call the plan the policy π (pi): it says which move to make in each square. Call the square s. The state value Vπ(s) is the average return if you start in s and follow π.
V-pi of s equals the expected value under pi of G-t, given that s-t is s.
Start in square s many times. Follow pi each time. Average the returns G-t. That average is V-pi of s.
With made-up numbers: from A, 8 of 10 runs return −2.71 and 2 runs return −3.44. V = 0.8 × (−2.71) + 0.2 × (−3.44) = −2.856.
The action value Qπ(s, a) asks more: take move a first, then follow π. Call the chance that move a in square s lands in square s′ p(s′|s, a), and the move's reward r(s, a). One move ahead, you can build Q from V.
Q-pi of s and a equals the sum over s-prime of p of s-prime given s and a, times the quantity r of s and a plus gamma V-pi of s-prime.
For each landing square s-prime, add the reward r of s and a to gamma times V-pi of s-prime. Average those by the chances p. That is Q-pi of s and a.
No slip, so each p is 1. Under the best plan, V(A) = −2.71 and V(B) = −1.9. Q(A, right) = −1 + 0.9 × (−1.9) = −2.71. Q(A, left) = −1 + 0.9 × (−2.71) = −3.439. Right wins.
The best policy gets a star: V* and Q*. A square's best worth is its best move's worth, V*(s) = maxa Q*(s, a). The best move is the one that reaches that max. So Q* hands you the policy with no model. V* does not: to rank moves from V*, you need p to see where each move lands.
The squares show V* at gamma 0.9. Pick a square: the bars show Q* for left and for right. The longer bar loses, because values are costs.
Illustrative corridor, no slip. Left from A bumps the wall and stays in A.
The failure. You stored V and threw the model away. The symptom: you cannot rank the moves, because each Q needs p. Measure it by writing the argmax; it asks for p. The fix: store Q in place of V. Lecture 8 learns Q from experience for this reason.
Chapter 3
Average the one-step recursion for a fixed policy, or take a max for the best one
Put the return recursion Gt = rt+1 + γ Gt+1 inside the average V. Two choices are random. The policy picks move a with chance π(a|s). Then the world picks the landing square s′ with chance p(s′|s, a). Average over both.
V-pi of s equals the sum over a of pi of a given s, times the sum over s-prime of p of s-prime given s and a, times r of s and a plus gamma V-pi of s-prime.
For each move a, average r of s and a plus gamma times V-pi of s-prime over the landing squares, using p. Then average those move scores using pi of a given s.
With made-up numbers: square C, slip 20%, the policy always goes right, and the current guess for B is −1.9. Right lands on the dock with chance 0.8 and on B with 0.2. V(C) = −1 + 0.9 × (0.8 × 0 + 0.2 × (−1.9)) = −1.342.
This is the Bellman expectation equation. It describes one fixed policy. To describe the best policy, take the best move in place of the policy's average. The principle of optimality says why this works: a best plan must stay best from every square it reaches.
V-star of s equals the max over a of the sum over s-prime of p of s-prime given s and a, times r of s and a plus gamma V-star of s-prime.
Score each move a the same way as before, with V-star in place of V-pi. Keep the largest score. That is V-star of s.
Square C, no slip, V*(B) = −1.9, the dock is 0. V*(C) = max(−1 + 0.9 × 0, −1 + 0.9 × (−1.9)) = max(−1, −2.71) = −1.
Purple lines are the policy's moves. Pink lines are the model's landings. Switch between average and max, pick a square, and drag the slip.
Illustrative. The current guess is V = (−2.71, −1.9, −1, 0) for A, B, C and the dock. With slip s, a move goes the other way with chance s.
| Equation | Combines moves by | Shape | How to solve |
|---|---|---|---|
| Expectation | the policy's average | linear in V | exactly, or by sweeps |
| Optimality | the max | not linear | by sweeps |
The failure. You plan with no slip, but the floor slips 20% of the time. You predict V(A) = −2.71 for “always right”; the true value is −3.61. The symptom: the robot takes longer than its values promise. Measure the average return of real runs against V. The fix: estimate p from data.
Chapter 4
Turn the expectation equation into an update and sweep it until the values stop moving
You have a plan, maybe a bad one. What is it worth in every square? Policy evaluation answers with Vπ. There are two routes.
Route 1: solve it. The expectation equation is one linear equation per square. Stack the values in a vector V and the rewards in a vector r. Call T the table of chances to move from each square to each square under π, and I the identity matrix. Then:
V = r + γ T V, so V = (I − γ T)−1 r
This is exact, but the cost grows with the cube of the number of squares.
Route 2: sweep it. Start with every value at 0. Call the values after k sweeps Vk. Compute new values from the old ones with the equation, for every square at once:
Vk+1(s) ← Σa π(a|s) Σs′ p(s′|s, a) [ r(s, a) + γ Vk(s′) ]
The arrow means “becomes”. In the corridor with “always right”, the sweeps go like this:
| Sweep | V(A) | V(B) | V(C) | V(D) |
|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 |
| 1 | −1.00 | −1.00 | −1.00 | 0 |
| 2 | −1.90 | −1.90 | −1.00 | 0 |
| 3 | −2.71 | −1.90 | −1.00 | 0 |
| 4, no change | −2.71 | −1.90 | −1.00 | 0 |
Sweep 3 for A: V3(A) = −1 + 0.9 × V2(B) = −1 + 0.9 × (−1.9) = −2.71. The same −2.71 as the return in Chapter 1.
Tap a square's button to flip its move. Then sweep. The lower plot is the largest change in each sweep, on a log scale.
Illustrative corridor, gamma 0.9, no slip. “Run to the end” stops when the largest change falls below 0.0001.
The failure. You stop after a fixed 3 sweeps. For “always left” every square then reads −2.71, but the true value is −10: the robot never docks. The symptom: a bad plan looks fine. Measure the largest change in the last sweep: 0.81, far from 0. The fix: sweep until that change is tiny. Getting within 0.01 of −10 takes 66 sweeps.
Now write the update yourself. The lab gives you the corridor; you write the one line that is the backup.
Vnew = r in place of r + gamma*(P @ V). What goes wrong?Chapter 5
Run one sweep on two different guesses and measure how much closer they get
Why should sweeping settle at all, and on one answer? Take two guesses, x and y. Call one full sweep F: it takes a list of values and returns a new list. Call ‖x − y‖ the max-norm of the gap: the largest difference between the two lists over all squares.
The largest gap between F of x and F of y is at most gamma times the largest gap between x and y.
Sweep both guesses x and y once. The rewards are the same in both, so they cancel. What is left is gamma times an average of the old gaps, and an average is never above the largest gap.
Square A under “always left”: one sweep maps a guess v to −1 + 0.9v. Guesses 0 and −20 become −1 and −19. The gap goes from 20 to 18, which is 0.9 × 20.
An update with this property is a contraction. The Banach fixed-point theorem then gives three facts:
Two guesses for square A, 0 and −20, swept 30 times. Drag gamma and watch how fast the gap closes.
Illustrative: square A under “always left”, so a sweep maps v to −1 + gamma × v. The fixed point is −1/(1 − gamma).
After 10 sweeps at gamma 0.9 the gap is 20 × 0.910 = 6.97. To cut any error 100 times takes 44 sweeps at gamma 0.9, but 459 at gamma 0.99. The gamma that makes a robot patient also makes the sweeps slow. The full proof, with the max, is in Deep RL, Chapter 1; the optimality sweep is a contraction too.
The failure. You set gamma to 0.999 for a long task. The symptom: thousands of sweeps and values still moving. Measure the ratio of two changes in a row; it sits near gamma. The fix: score each plan exactly (Route 1) and use policy iteration, or use the smallest gamma the task allows.
Chapter 6
Score every move with the old plan's values, and switch to the best one
You scored a plan π. Now make a better one. In each square, compute Qπ(s, a) for every move from the old values. Then switch to the move with the largest Q. Call the new plan π′ (pi-prime).
Pi-prime of s equals the argmax over a of Q-pi of s and a.
In each square s, compute Q-pi of s and a for every move a. Pick the move with the largest Q. If two moves tie, keep the move the old plan used.
The old plan is “always left”, so V = −10 in A, B and C. At C: Q(C, right) = −1 + 0.9 × 0 = −1, and Q(C, left) = −1 + 0.9 × (−10) = −10. C switches to right. At B both moves give −10, a tie, so B keeps left.
The policy improvement theorem says Vπ′(s) ≥ Vπ(s) in every square. The reason: the first move is at least as good as the old one. The same holds again at the next square, and the next.
Pick the old plan. Under each square, two bars show Q for left and right from the old values. Purple marks the new move; a grey “tie” keeps the old one.
Illustrative corridor, gamma 0.9, no slip. The device scores each old plan exactly before the greedy step.
When does improvement stop? When the greedy step gives back the same plan. Then Vπ(s) = maxa Qπ(s, a) in every square. That is the optimality equation from Chapter 3. So a plan that improvement cannot change is a best plan.
The failure. You break ties at random. Two moves with the same Q swap back and forth, so the plan changes on every round and the stop test never fires. Measure the number of switches where the Q gain is 0. The fix: switch only on a strict gain.
Chapter 7
Alternate the two halves until the plan stops changing
You have both halves. Policy iteration runs them in a loop:
Why must it stop? The corridor has 23 = 8 plans. Each round gives a plan at least as good as the last, and with strict-gain switches it never returns to an old plan. So it runs out of plans to try, and the only place it can stop is a best plan.
Run it from the worst plan, “always left”:
| Round | Plan (A, B, C) | V(A) | V(B) | V(C) | Switches |
|---|---|---|---|---|---|
| 1 | L, L, L | −10 | −10 | −10 | C to R |
| 2 | L, L, R | −10 | −10 | −1 | B to R |
| 3 | L, R, R | −10 | −1.9 | −1 | A to R |
| 4 | R, R, R | −2.71 | −1.9 | −1 | none: stop |
Round 3 at A: Q(A, right) = −1 + 0.9 × (−1.9) = −2.71 beats Q(A, left) = −10. Four evaluations, three improvements. The ties at A and B keep them on left until the dock's worth reaches them.
Set a start plan with the buttons, then press Next step. It alternates evaluate and improve. Add slip and run it again.
Illustrative corridor, gamma 0.9. Each evaluation is exact. With slip s, a move goes the other way with chance s.
You need not evaluate to the end before improving. Any mix of partial evaluation and improvement still climbs to the best plan. Sutton and Barto call this generalized policy iteration, and most RL methods have this shape.
The failure. Exact evaluation solves one linear equation per state, and its cost grows with the cube of the count. A 100 by 100 grid has 10,000 states: about 1012 steps per round. Measure the time per round. The fix: evaluate with a few sweeps only, then improve.
Chapter 8
Sweep the optimality equation directly, and read the best move off at the end
Policy iteration scores each plan fully before it improves once. That is many sweeps for a plan you will throw away. Value iteration skips the inner loop. It sweeps the optimality equation from Chapter 3 as an update:
Vk+1(s) ← maxa Σs′ p(s′|s, a) [ r(s, a) + γ Vk(s′) ]
The only change from policy evaluation is the max in front. Each sweep picks the best move on the fly, so it stores values only. The optimality sweep is also a gamma-contraction, so it settles on V* from any start.
| Sweep | V(A) | V(B) | V(C) | V(D) |
|---|---|---|---|---|
| 1 | −1.00 | −1.00 | −1.00 | 0 |
| 2 | −1.90 | −1.90 | −1.00 | 0 |
| 3 | −2.71 | −1.90 | −1.00 | 0 |
| 4, no change | −2.71 | −1.90 | −1.00 | 0 |
Sweep 2 at C: max(−1 + 0.9 × 0, −1 + 0.9 × (−1)) = max(−1, −1.9) = −1. At the end, read the best move: at C, Q(right) = −1 beats Q(left) = −2.71. The plan is “always right”, as policy iteration found.
When do you stop? Stop when the largest change in a sweep falls below a small number ε (epsilon). Then the error is at most ε × γ/(1 − γ). The plan is often right many sweeps before the values settle.
The yellow line is the largest change per sweep. The purple line marks the last sweep that changed the greedy plan. Drag slip and gamma.
Illustrative corridor of five squares and a dock. Values start at 0; ties keep the move “left”. The run stops when the largest change falls below 0.001.
| Policy iteration | Value iteration | |
|---|---|---|
| One round | full evaluation, then a greedy step | one sweep with a max |
| Cost of a round | high | low |
| Rounds needed | few (5 on the hero at 10% slip) | many (18 sweeps there) |
| Keeps a plan during the run | yes | no, read it off at the end |
| Answer | V* and π* | the same V* and π* |
The failure. You stop when the change is below 0.01, with gamma 0.99. The symptom: the values look settled but are still off. Measure with the bound: the error can be up to 0.01 × 0.99/0.01 = 0.99. The fix: set ε from the error you can accept, ε = error × (1 − γ)/γ.
Chapter 9
Keep the terms, the numbers, the code and the next steps in one place
A square is worth its next reward plus gamma times the worth of where it lands. Averaged over a fixed plan, that rule scores the plan. With a max, it describes the best plan. Policy iteration and value iteration both solve it, and both settle because each sweep shrinks every error by gamma.
| Term | What it is | Number on this page |
|---|---|---|
| Return Gt | the sum of rewards, each shrunk by gamma once per step of delay | −2.71 from A, always right |
| Vπ(s) | the average return from s under plan pi | −10 everywhere under always left |
| Qπ(s, a) | the average return after move a, then pi | Q*(A, left) = −3.439 |
| Bellman expectation | V as an average of reward plus gamma times next V | V(C) = −1.342 at 20% slip |
| Bellman optimality | the same with a max over moves | V*(C) = max(−1, −2.71) |
| Contraction | each sweep shrinks the largest gap by gamma | 44 sweeps per 100 times at 0.9; 459 at 0.99 |
| Policy iteration | evaluate, improve, repeat until the plan stops | 4 rounds from always left |
| Value iteration | sweep the optimality equation, read the plan at the end | 3 sweeps, plus 1 to confirm |
| Stopping rule | error at most ε × gamma/(1 − gamma) | 0.99 for ε = 0.01, gamma 0.99 |
pythonimport numpy as np # P[a, s, s2] = chance that move a in state s lands in s2; R[s, a] = reward def q_values(V, P, R, gamma): return R + gamma * np.einsum('asn,n->sa', P, V) # Q[s, a], shape (S, A) def evaluate(pi, P, R, gamma, tol=1e-8): V = np.zeros(P.shape[1]) while True: Vn = q_values(V, P, R, gamma)[np.arange(len(V)), pi] # follow the plan if np.max(np.abs(Vn - V)) < tol: return Vn V = Vn def policy_iteration(P, R, gamma): pi = np.zeros(P.shape[1], dtype=int) while True: V = evaluate(pi, P, R, gamma) Q = q_values(V, P, R, gamma) best = Q.argmax(1) keep = Q[np.arange(len(V)), best] <= Q[np.arange(len(V)), pi] + 1e-12 new = np.where(keep, pi, best) # switch only on a strict gain if np.array_equal(new, pi): return pi, V pi = new def value_iteration(P, R, gamma, eps=1e-3): V = np.zeros(P.shape[1]) while True: Vn = q_values(V, P, R, gamma).max(1) # the optimality backup if np.max(np.abs(Vn - V)) < eps: return q_values(Vn, P, R, gamma).argmax(1), Vn V = Vn
Credit: Lecture 7 of CMU 16-831, Introduction to Robot Learning, taught by Guanya Shi. This page re-teaches the lecture's ideas in its own words, numbers and toys; it does not copy the slides.
Now teach it back: open Present or Teach and derive the optimality equation, one policy iteration run and one value iteration sweep on the corridor. Then go back to the cliff walk and predict the route at 15% slip before you press Solve.