Policy Evaluation
Computing what a policy is worth, by solving equations or by sweeping backups.
What is a policy worth? For a fixed policy the answer is the solution of a linear system with one equation per state. You can solve it directly, at a cost that grows with the cube of the number of states, or by sweeping a simple backup over the states until nothing changes. The sweeps are cheap, work on sparse models and parallel hardware, and are the template that temporal-difference learning and every learned critic follow.
What you’ll learn
- Derive the Bellman expectation equation for a stochastic policy and write it as the linear system .
- Implement iterative policy evaluation with synchronous and in-place sweeps, and compare its cost with a direct solve.
- Prove that the sweeps converge geometrically, and derive a stopping rule with a guaranteed error.
- Reproduce Sutton and Barto's 4×4 gridworld example and interpret its values as expected times to termination.
A policy’s value is a linear system
A finite MDP has states , actions , transition probabilities , expected rewards and a discount . A stochastic policy fixes how actions are chosen, and its state-value function is , the expected return from . Policy evaluation means computing from the model.
The return satisfies . Condition on and average over the action and the next state :
By the Markov property, what happens after does not depend on how you got there, so the inner expectation is . This is the Bellman expectation equation:
Collect the policy's average reward and transition matrix, and . The equations become one vector equation, linear in :
The system has exactly one solution. Each row of is a probability distribution, so for every vector . If then , which forces . So is invertible:
In the two-state world (; in , stay pays 1 and stays, go pays 0 and moves to ; in , stay pays 2 and stays), a policy stays in and flips a fair coin in . Then . What is ?
- 14, halfway between always staying (10) and always going (18)
- 9.5
- 18
Show the answer
C.
The equation for is , so . Values are not linear in the action probabilities: with the coin, the agent leaves after two steps on average, so it soon collects the 2s of , and its value lies much nearer to always going than to always staying.
Gaussian elimination solves the system in arithmetic operations and memory. That is instant for a few hundred states, but a dense solve with states takes on the order of operations and almost a gigabyte of memory, and is out of reach. Real transition matrices are usually sparse, and the second way of solving the system exploits that.
Iterative policy evaluation
Define the Bellman operator of by . Its fixed point is . Iterative policy evaluation starts from any , often zeros, and applies it over and over, . Each application is one sweep of backups, one per state: an expected update that averages over all actions and next states using the model.
There are two ways to sweep. A synchronous sweep computes all new values from the old ones and needs two arrays. An in-place sweep overwrites each value as soon as it is computed, so states later in the sweep already use their neighbors' new values. In numerical linear algebra these are, up to how self-transitions are handled, the Jacobi and Gauss–Seidel iterations.
import numpy as np
def evaluate_policy(P, r, pi, gamma, theta=1e-8, in_place=True):
"""P[s, a, s2]: transition probabilities, r[s, a]: expected rewards,
pi[s, a]: action probabilities. Sweeps until no value changes by theta."""
V = np.zeros(r.shape[0])
while True:
V_read = V if in_place else V.copy() # in place: new values used at once
delta = 0.0
for s in range(len(V)):
v_new = pi[s] @ (r[s] + gamma * P[s] @ V_read)
delta = max(delta, abs(v_new - V[s]))
V[s] = v_new
if delta < theta:
return V # within gamma * theta / (1 - gamma) of V^pi
def solve_policy(P, r, pi, gamma):
"""The direct method: solve (I - gamma P_pi) V = r_pi."""
P_pi = np.einsum('sa,sat->st', pi, P)
r_pi = (pi * r).sum(axis=1)
return np.linalg.solve(np.eye(len(r_pi)) - gamma * P_pi, r_pi)A sweep costs with a dense model and when each state–action pair has at most possible successors, and it needs memory only for the values (two copies when synchronous). The return comment is the stopping guarantee proved in the next step.
Why the sweeps converge
Contraction. The difference of two backups is . Each entry is times an average of entries of , and an average is at most the largest entry in absolute value:
A priori. is the fixed point, , so each sweep shrinks the error by :
A posteriori. Insert with the triangle inequality and solve for the error. The right-hand side is computable while the algorithm runs:
In place. Compare an in-place sweep from with one from , state by state in the sweep order. The first update reads two vectors at distance at most , so its outputs differ by at most ; every later update reads entries that are either already updated or untouched, all within , so its outputs also differ by at most . After the sweep every state is updated, so the whole sweep is a -contraction with fixed point , and steps 2 and 3 apply unchanged.
From with rewards bounded by , the initial error is at most , so sweeps guarantee accuracy . Since , about sweeps suffice: the effective horizon sets the cost, so needs roughly ten times as many sweeps as .
Worked example: the 4×4 gridworld
Sutton and Barto's Example 4.1 is a 4×4 grid whose top-left and bottom-right corners are terminal. The actions up, down, left and right move deterministically, a move off the grid leaves you in place, every step pays , and . The policy picks each of the four actions with probability . It is proper, since a random walk reaches a corner eventually, so the sweeps converge, and is the expected number of steps the random walk needs to finish from .
| Sweeps | Cell 1 (next to an exit) | Cell 2 (edge) | Cell 3 (far corner) | Cell 5 (diagonal to an exit) |
|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 |
| 1 | −1 | −1 | −1 | −1 |
| 2 | −1.75 | −2 | −2 | −2 |
| 3 | −2.44 | −2.94 | −3 | −2.88 |
| 10 | −6.14 | −8.35 | −8.97 | −7.74 |
| −14 | −20 | −22 | −18 |
From the far corner (cell 3), how many steps does the random walk take on average before it reaches an exit?
Show the answer
22
and every step costs 1, so the expected time to finish is 22 steps, although the nearest exit is only 3 steps away. The random walk wastes most of its moves, which is exactly what one round of policy improvement will fix.
Two more facts about this example, both computed with the code above:
- In place is faster. Bringing the largest change below takes 173 synchronous sweeps but only 114 in-place sweeps in reading order, because each in-place sweep already propagates new values from cells updated earlier in the same sweep.
- The greedy policy settles early. Acting greedily on gives an optimal policy for every , long before the values approach . Improving the random policy once, with its exact values, is already optimal. Policy iteration builds on exactly this.
Cell 3 has value under the random policy. What does this number tell you?
- The shortest path from cell 3 to an exit has 22 steps
- The random walk from cell 3 needs 22 steps on average to reach an exit
- An optimal agent loses 22 points from cell 3
- Every step from cell 3 costs 22
Show the answer
B. The random walk from cell 3 needs 22 steps on average to reach an exit
With reward per step and no discounting, the value is minus the expected number of steps until termination under the policy being evaluated. The optimal policy needs only 3 steps from that corner, so its value there is .
Deeper: the Fixed Point lessons
Key takeaways
- For a fixed policy, the Bellman expectation equation is a linear system, , with a unique solution whenever .
- A direct solve costs . Iterative policy evaluation applies sweep after sweep, at per sweep or less for sparse models, synchronously or in place.
- is a -contraction in the max norm, so the error shrinks like , and a last change below guarantees an error below . With you need a proper policy instead.
- In Sutton and Barto's 4×4 gridworld the random policy's values are minus the expected time to finish, in-place sweeps converge in about a third fewer sweeps, and the greedy policy is optimal long before the values converge.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Which linear system does solve?
Show the answer
C.
Rearranging gives , and is invertible because shrinks the max norm by the factor .
Synchronous iterative evaluation with stops when the largest change in a sweep falls below . How far from can the result be, at most?
- 0.01
- 0.09
- 0.1
- 0.9
Show the answer
B. 0.09
The a posteriori bound gives . A small last change does not mean a small error: changes shrink geometrically, so the remaining ones add up to about times the last.
An MDP has states, and from each state the policy can reach at most 10 next states. Which is cheaper: a dense direct solve, or 500 sweeps of iterative evaluation?
- The direct solve, because it is exact
- They cost about the same
- It depends only on
- The sweeps: about operations against roughly
Show the answer
D. The sweeps: about operations against roughly
A sweep touches each state's 10 successors, about operations, so 500 sweeps cost about . Dense Gaussian elimination costs on the order of operations and numbers of memory. Sparse direct solvers can do better than dense ones, but for large sparse models iterative methods are the norm.
With and a reward of per step, you evaluate a policy that, from some state, walks in a circle forever and never reaches the terminal state. What do the sweeps do?
- The values of the circling states fall by about 1 every sweep, without limit
- They converge, because every backup is an average
- They converge to 0, because no terminal reward is ever collected
- They oscillate between two values
Show the answer
A. The values of the circling states fall by about 1 every sweep, without limit
The true value of a state on the circle is : the walk pays forever. Without discounting and without guaranteed termination, is not a contraction, and each sweep adds roughly another . Convergence with needs a proper policy.
Go deeper
- Policy Evaluation as Linear Algebra · The matrix (I − γP)⁻¹, the Neumann series and conditioning as γ → 1.
- Asynchronous & Prioritized Dynamic Programming · In-place sweeps, prioritized sweeping and real-time dynamic programming.
- Average-Reward Dynamic Programming · Gain, bias and relative value iteration for tasks that never end.
Further reading
- R. S. Sutton & A. G. Barto, Reinforcement Learning: An Introduction, ch. 4 (MIT Press, 2nd ed., 2018).
- M. L. Puterman, Markov Decision Processes: Discrete Stochastic Dynamic Programming, ch. 6 (Wiley, 1994).
- D. P. Bertsekas & J. N. Tsitsiklis, Neuro-Dynamic Programming, ch. 2 (Athena Scientific, 1996).