Simple Algorithm
Reinforcement Learning · Bootstrapping · 22 min

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 (I−γPπ)Vπ=rπ(I-\gamma P^\pi)V^\pi = r^\pi.
  • 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 S\mathcal S, actions A\mathcal A, transition probabilities P(s′∣s,a)P(s'\mid s,a), expected rewards r(s,a)r(s,a) and a discount γ∈[0,1)\gamma\in[0,1). A stochastic policy π(a∣s)\pi(a\mid s) fixes how actions are chosen, and its state-value function is Vπ(s)=Eπ[Gt∣St=s]V^\pi(s)=\E_\pi[G_t\mid S_t=s], the expected return from ss. Policy evaluation means computing VπV^\pi from the model.

DerivationFrom the return to a linear system
  1. Vπ(s)=∑aπ(a∣s)[r(s,a)+γ∑s′P(s′∣s,a) Eπ[Gt+1∣St=s,At=a,St+1=s′]]V^\pi(s)=\sum_a\pi(a\mid s)\Big[r(s,a)+\gamma\sum_{s'}P(s'\mid s,a)\,\E_\pi\big[G_{t+1}\mid S_t=s,A_t=a,S_{t+1}=s'\big]\Big]

    The return satisfies Gt=Rt+1+γGt+1G_t=R_{t+1}+\gamma G_{t+1}. Condition on St=sS_t=s and average over the action At∼π(⋅∣s)A_t\sim\pi(\cdot\mid s) and the next state St+1∼P(⋅∣s,At)S_{t+1}\sim P(\cdot\mid s,A_t):

  2. Vπ(s)=∑aπ(a∣s)[r(s,a)+γ∑s′P(s′∣s,a) Vπ(s′)]V^\pi(s)=\sum_a\pi(a\mid s)\Big[r(s,a)+\gamma\sum_{s'}P(s'\mid s,a)\,V^\pi(s')\Big]

    By the Markov property, what happens after St+1=s′S_{t+1}=s' does not depend on how you got there, so the inner expectation is Vπ(s′)V^\pi(s'). This is the Bellman expectation equation:

  3. Vπ=rπ+γPπVπ⟺(I−γPπ) Vπ=rπV^\pi=r^\pi+\gamma P^\pi V^\pi\qquad\Longleftrightarrow\qquad(I-\gamma P^\pi)\,V^\pi=r^\pi

    Collect the policy's average reward and transition matrix, rπ(s)=∑aπ(a∣s) r(s,a)r^\pi(s)=\sum_a\pi(a\mid s)\,r(s,a) and Pπ(s,s′)=∑aπ(a∣s) P(s′∣s,a)P^\pi(s,s')=\sum_a\pi(a\mid s)\,P(s'\mid s,a). The SS equations become one vector equation, linear in VπV^\pi:

  4. Vπ=(I−γPπ)−1rπV^\pi=(I-\gamma P^\pi)^{-1}r^\pi

    The system has exactly one solution. Each row of PπP^\pi is a probability distribution, so ∥Pπx∥∞≤∥x∥∞\norm{P^\pi x}_\infty\le\norm{x}_\infty for every vector xx. If (I−γPπ)x=0(I-\gamma P^\pi)x=0 then ∥x∥∞=γ∥Pπx∥∞≤γ∥x∥∞\norm{x}_\infty=\gamma\norm{P^\pi x}_\infty\le\gamma\norm{x}_\infty, which forces x=0x=0. So I−γPπI-\gamma P^\pi is invertible:

Check your understanding

In the two-state world (γ=0.9\gamma=0.9; in s1s_1, stay pays 1 and stays, go pays 0 and moves to s2s_2; in s2s_2, stay pays 2 and stays), a policy stays in s2s_2 and flips a fair coin in s1s_1. Then Vπ(s2)=20V^\pi(s_2)=20. What is Vπ(s1)V^\pi(s_1)?

  1. 14, halfway between always staying (10) and always going (18)
  2. 9.5
  3. 190/11≈17.27190/11\approx17.27
  4. 18
Show the answer

C. 190/11≈17.27190/11\approx17.27

The equation for s1s_1 is V=12⋅1+0.9(12V+12⋅20)=9.5+0.45VV=\tfrac12\cdot1+0.9\big(\tfrac12V+\tfrac12\cdot20\big)=9.5+0.45V, so V=9.5/0.55=190/11V=9.5/0.55=190/11. Values are not linear in the action probabilities: with the coin, the agent leaves s1s_1 after two steps on average, so it soon collects the 2s of s2s_2, and its value lies much nearer to always going than to always staying.

Gaussian elimination solves the system in O(S3)\order{S^3} arithmetic operations and O(S2)\order{S^2} memory. That is instant for a few hundred states, but a dense solve with S=104S=10^4 states takes on the order of 101210^{12} operations and almost a gigabyte of memory, and S=106S=10^6 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 π\pi by TπV=rπ+γPπV\mathcal T^\pi V=r^\pi+\gamma P^\pi V. Its fixed point is VπV^\pi. Iterative policy evaluation starts from any V0V_0, often zeros, and applies it over and over, Vk+1=TπVkV_{k+1}=\mathcal T^\pi V_k. 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.

python
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 O(S2A)\order{S^2A} with a dense model and O(SAb)\order{SAb} when each state–action pair has at most bb 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

DerivationProof
  1. ∣(TπV−TπU)(s)∣=γ ∣∑s′Pπ(s,s′)(V(s′)−U(s′))∣≤γ∥V−U∥∞\abs{(\mathcal T^\pi V-\mathcal T^\pi U)(s)}=\gamma\,\Big|\sum_{s'}P^\pi(s,s')\big(V(s')-U(s')\big)\Big|\le\gamma\norm{V-U}_\infty

    Contraction. The difference of two backups is γPπ(V−U)\gamma P^\pi(V-U). Each entry is γ\gamma times an average of entries of V−UV-U, and an average is at most the largest entry in absolute value:

  2. ∥Vk−Vπ∥∞=∥TπVk−1−TπVπ∥∞≤γ∥Vk−1−Vπ∥∞≤⋯≤γk∥V0−Vπ∥∞\norm{V_k-V^\pi}_\infty=\norm{\mathcal T^\pi V_{k-1}-\mathcal T^\pi V^\pi}_\infty\le\gamma\norm{V_{k-1}-V^\pi}_\infty\le\dots\le\gamma^k\norm{V_0-V^\pi}_\infty

    A priori. VπV^\pi is the fixed point, TπVπ=Vπ\mathcal T^\pi V^\pi=V^\pi, so each sweep shrinks the error by γ\gamma:

  3. ∥Vk+1−Vπ∥∞≤γ∥Vk−Vπ∥∞≤γ∥Vk−Vk+1∥∞+γ∥Vk+1−Vπ∥∞ ⟹ ∥Vk+1−Vπ∥∞≤γ1−γ∥Vk+1−Vk∥∞\norm{V_{k+1}-V^\pi}_\infty\le\gamma\norm{V_k-V^\pi}_\infty\le\gamma\norm{V_k-V_{k+1}}_\infty+\gamma\norm{V_{k+1}-V^\pi}_\infty\ \Longrightarrow\ \norm{V_{k+1}-V^\pi}_\infty\le\frac{\gamma}{1-\gamma}\norm{V_{k+1}-V_k}_\infty

    A posteriori. Insert VkV_k with the triangle inequality and solve for the error. The right-hand side is computable while the algorithm runs:

  4. In place. Compare an in-place sweep from VV with one from UU, state by state in the sweep order. The first update reads two vectors at distance at most ∥V−U∥∞\norm{V-U}_\infty, so its outputs differ by at most γ∥V−U∥∞\gamma\norm{V-U}_\infty; every later update reads entries that are either already updated or untouched, all within ∥V−U∥∞\norm{V-U}_\infty, so its outputs also differ by at most γ∥V−U∥∞\gamma\norm{V-U}_\infty. After the sweep every state is updated, so the whole sweep is a γ\gamma-contraction with fixed point VπV^\pi, and steps 2 and 3 apply unchanged.

From V0=0V_0=0 with rewards bounded by Rmax⁡R_{\max}, the initial error is at most Rmax⁡/(1−γ)R_{\max}/(1-\gamma), so k≥ln⁡ ⁣(Rmax⁡/(ε(1−γ)))/ln⁡(1/γ)k\ge\ln\!\big(R_{\max}/(\varepsilon(1-\gamma))\big)/\ln(1/\gamma) sweeps guarantee accuracy ε\varepsilon. Since ln⁡(1/γ)≥1−γ\ln(1/\gamma)\ge1-\gamma, about 11−γln⁡Rmax⁡ε(1−γ)\frac{1}{1-\gamma}\ln\frac{R_{\max}}{\varepsilon(1-\gamma)} sweeps suffice: the effective horizon 1/(1−γ)1/(1-\gamma) sets the cost, so γ=0.99\gamma=0.99 needs roughly ten times as many sweeps as γ=0.9\gamma=0.9.

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 −1-1, and γ=1\gamma=1. The policy picks each of the four actions with probability 14\tfrac14. It is proper, since a random walk reaches a corner eventually, so the sweeps converge, and −Vπ(s)-V^\pi(s) is the expected number of steps the random walk needs to finish from ss.

Sweeps kkCell 1 (next to an exit)Cell 2 (edge)Cell 3 (far corner)Cell 5 (diagonal to an exit)
00000
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
∞\infty−14−20−22−18
Synchronous sweeps from V0=0V_0=0, with cells numbered 1 to 14 in reading order (cell 1 is right of the top-left exit, cell 3 is the top-right corner, cell 5 is below cell 1). By symmetry the other cells mirror these. After two sweeps, cell 1 has −1−14⋅0−34⋅1=−1.75-1-\tfrac14\cdot0-\tfrac34\cdot1=-1.75: one of its four moves enters the exit. The book's figure prints these numbers to one decimal.
Predict before you look

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

Vπ(3)=−22V^\pi(3)=-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 10−410^{-4} 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 VkV_k gives an optimal policy for every k≥3k\ge3, long before the values approach −14,…,−22-14,\dots,-22. Improving the random policy once, with its exact values, is already optimal. Policy iteration builds on exactly this.
Check your understanding

Cell 3 has value −22-22 under the random policy. What does this number tell you?

  1. The shortest path from cell 3 to an exit has 22 steps
  2. The random walk from cell 3 needs 22 steps on average to reach an exit
  3. An optimal agent loses 22 points from cell 3
  4. 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 −1-1 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 −3-3.

Deeper: the Fixed Point lessons

Key takeaways

  • For a fixed policy, the Bellman expectation equation is a linear system, (I−γPπ)Vπ=rπ(I-\gamma P^\pi)V^\pi=r^\pi, with a unique solution whenever γ<1\gamma<1.
  • A direct solve costs O(S3)\order{S^3}. Iterative policy evaluation applies Tπ\mathcal T^\pi sweep after sweep, at O(S2A)\order{S^2A} per sweep or less for sparse models, synchronously or in place.
  • Tπ\mathcal T^\pi is a γ\gamma-contraction in the max norm, so the error shrinks like γk\gamma^k, and a last change below θ\theta guarantees an error below γθ/(1−γ)\gamma\theta/(1-\gamma). With γ=1\gamma=1 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.

Question 1

Which linear system does VπV^\pi solve?

  1. (I−Pπ)V=γrπ(I-P^\pi)V=\gamma r^\pi
  2. (γI−Pπ)V=rπ(\gamma I-P^\pi)V=r^\pi
  3. (I−γPπ)V=rπ(I-\gamma P^\pi)V=r^\pi
  4. V=rπ+PπV/γV=r^\pi+P^\pi V/\gamma
Show the answer

C. (I−γPπ)V=rπ(I-\gamma P^\pi)V=r^\pi

Rearranging V=rπ+γPπVV=r^\pi+\gamma P^\pi V gives (I−γPπ)V=rπ(I-\gamma P^\pi)V=r^\pi, and I−γPπI-\gamma P^\pi is invertible because γPπ\gamma P^\pi shrinks the max norm by the factor γ<1\gamma<1.

Question 2

Synchronous iterative evaluation with γ=0.9\gamma=0.9 stops when the largest change in a sweep falls below θ=0.01\theta=0.01. How far from VπV^\pi can the result be, at most?

  1. 0.01
  2. 0.09
  3. 0.1
  4. 0.9
Show the answer

B. 0.09

The a posteriori bound gives γ1−γθ=9×0.01=0.09\frac{\gamma}{1-\gamma}\theta=9\times0.01=0.09. A small last change does not mean a small error: changes shrink geometrically, so the remaining ones add up to about γ/(1−γ)\gamma/(1-\gamma) times the last.

Question 3

An MDP has 10510^5 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?

  1. The direct solve, because it is exact
  2. They cost about the same
  3. It depends only on γ\gamma
  4. The sweeps: about 5×1085\times10^8 operations against roughly 101510^{15}
Show the answer

D. The sweeps: about 5×1085\times10^8 operations against roughly 101510^{15}

A sweep touches each state's 10 successors, about 10610^6 operations, so 500 sweeps cost about 5×1085\times10^8. Dense Gaussian elimination costs on the order of S3=1015S^3=10^{15} operations and 101010^{10} numbers of memory. Sparse direct solvers can do better than dense ones, but for large sparse models iterative methods are the norm.

Question 4

With γ=1\gamma=1 and a reward of −1-1 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?

  1. The values of the circling states fall by about 1 every sweep, without limit
  2. They converge, because every backup is an average
  3. They converge to 0, because no terminal reward is ever collected
  4. 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 −∞-\infty: the walk pays −1-1 forever. Without discounting and without guaranteed termination, Tπ\mathcal T^\pi is not a contraction, and each sweep adds roughly another −1-1. Convergence with γ=1\gamma=1 needs a proper policy.

Go deeper

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).