AI Wiki中文/EN

Policy evaluation: solve the value of a fixed rule

策略评估

Compare linear-system evaluation with synchronous and in-place Bellman sweeps, and stop with an explicit error certificate.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Keep the rule fixed while you measure it

Suppose the arcade agent has already committed to advancing at entry and spinning in the room. We want to know the expected return from each state. Replacing a bad action with a better one would change the question: first evaluate the rule that was actually specified.

In the synthetic game, advancing earns 0 and moves to the room. Spinning earns 1.6 and moves to entry, room or termination with probabilities 0.4, 0.4 and 0.2. At discount 0.9 the two nonterminal values satisfy v0 = 0.9 v1 and v1 = 1.6 + 0.36 v0 + 0.36 v1. They are approximately 4.556962025 and 5.063291139.

We will recover those values three ways: a direct linear solve, synchronous Bellman sweeps, and in-place sweeps. Sutton and Barto, Section 4.1 calls this fixed-policy prediction problem policy evaluation. Bertsekas’s discounted-DP lectures provide the contraction argument that turns a residual into an error certificate.

Two update orders evaluate the same policy; identical log-error axes compare actual errors and current-residual certificates.
Two update orders evaluate the same policy; identical log-error axes compare actual errors and current-residual certificates.

The fixed point belongs to one policy

Assume finitely many states and actions, known transition probabilities and expected rewards, and discount 0 ≤ gamma < 1. A stationary policy induces a transition matrix and reward vector. For any candidate value vector v, define:

Pπ(s,s′)=∑aπ(a∣s)P(s′∣s,a),rπ(s)=∑aπ(a∣s)r(s,a),Tπv=rπ+γPπv.P_\pi(s,s')=\sum_a\pi(a\mid s)P(s'\mid s,a),\qquad r_\pi(s)=\sum_a\pi(a\mid s)r(s,a),\qquad T_\pi v=r_\pi+\gamma P_\pi v.

The policy stays fixed in this operator. There is no maximization over actions. The reward term makes the map affine in v; differences between two inputs cancel that constant term. The desired value satisfies v_pi = T_pi v_pi, or:

(I−γPπ)vπ=rπ.(I-\gamma P_\pi)v_\pi=r_\pi.

In this finite discounted model the matrix is invertible. A direct solver is one way to evaluate the policy, and a useful independent reference for a small iterative example. It uses the full known model, not sampled experience. With an absorbing terminal state whose reward is zero, the exact terminal value is zero.

Synchronous sweeps use one frozen input vector

Starting from an initial estimate, repeatedly apply the fixed-policy operator:

v(k+1)=Tπv(k)=rπ+γPπv(k).v^{(k+1)}=T_\pi v^{(k)}=r_\pi+\gamma P_\pi v^{(k)}.

Each new component uses the same old vector. Two arrays, or a vectorized expression producing a fresh array, preserve that meaning. Starting at zero in our example, the first sweep gives [0, 1.6, 0]; the second gives [1.44, 2.176, 0]. Information about later rewards propagates backward through the model.

Why should repeated updates converge? In maximum norm, averaging a difference through a probability row cannot increase its largest magnitude:

∥Tπv−Tπw∥∞=γ∥Pπ(v−w)∥∞≤γ∥v−w∥∞.\|T_\pi v-T_\pi w\|_\infty =\gamma\|P_\pi(v-w)\|_\infty \leq\gamma\|v-w\|_\infty.

Since the multiplier is below one, the operator has a unique fixed point and synchronous iteration approaches it from any finite initial vector. This is the discounted contraction result. The claim depends on the model and discount assumptions, not merely on writing a loop that looks like a Bellman equation.

Check the residual of the vector you will return

Define the current Bellman residual as the maximum absolute difference between T_pi v and v. Insert the fixed point into the triangle inequality and use contraction:

∥v−vπ∥∞≤∥v−Tπv∥∞+γ∥v−vπ∥∞⟹∥v−vπ∥∞≤∥Tπv−v∥∞1−γ.\|v-v_\pi\|_\infty \leq\|v-T_\pi v\|_\infty+\gamma\|v-v_\pi\|_\infty \quad\Longrightarrow\quad \|v-v_\pi\|_\infty\leq\frac{\|T_\pi v-v\|_\infty}{1-\gamma}.

To request value error at most epsilon, require residual at most (1−gamma) epsilon. A residual of 0.01 only certifies error at most 1 when discount is 0.99. The number becomes less reassuring as the horizon represented by the discount grows.

For synchronous updates, the difference between consecutive iterates equals the residual of the previous vector. It is easy to attach that number to the wrong returned vector. For in-place updates, one sweep’s component changes are not directly the residual of a single shared input vector. The implementation avoids both ambiguities by recomputing the operator on the current vector before deciding whether to return it. The MIT lecture’s residual bound justifies that decision in exact arithmetic; floating-point evaluation still has rounding error.

In-place sweeps expose updated components sooner

Process states in index order. When updating state s, use already updated values for earlier states and the old values for this and later states:

vs(k+1)=rπ(s)+γ∑j<sPπ(s,j)vj(k+1)+γ∑j≥sPπ(s,j)vj(k).v_s^{(k+1)}=r_\pi(s)+\gamma\sum_{j<s}P_\pi(s,j)v_j^{(k+1)} +\gamma\sum_{j\geq s}P_\pi(s,j)v_j^{(k)}.

This is an in-place Bellman update; the self-transition uses the previous value of the component being updated. It is not a row-wise exact solve that divides by a diagonal coefficient. The working draft distinguishes the in-place scheme from its two-array version and notes the importance of update order.

The first in-place sweep in our model also gives [0, 1.6, 0]. On the second, entry becomes 1.44 before the room is updated. The room therefore becomes 1.6 + 0.36 × 1.44 + 0.36 × 1.6 = 2.6944, rather than the synchronous 2.176. Both schemes converge here; their intermediate vectors and work counts differ.

Compare the iterates with an independent solution

Save this original program as evaluation.py, using Python 3.12 and NumPy 1.26.4. The policy is fixed to advance/spin. policy_model validates probabilities and averages actions; exact_value solves the linear system. The iterative routine records the current vector, its recomputed residual and the resulting bound.

"""Original finite-MDP teaching program; Python 3.12 and NumPy 1.26.4."""
import json
import math
import numpy as np


def model():
    # States: entry, room, terminal. Actions: exit, advance/spin.
    P = np.array([[[0,0,1],[0,1,0]], [[0,0,1],[.4,.4,.2]], [[0,0,1],[0,0,1]]], float)
    rewards = np.array([[2,0],[4,1.6],[0,0]], float)
    return P, rewards


def validate(P, rewards, gamma):
    P, rewards = np.asarray(P,float), np.asarray(rewards,float)
    if P.ndim != 3 or P.shape[0] == 0 or P.shape[1] == 0 or P.shape[2] != P.shape[0]:
        raise ValueError('P must have shape (states, actions, states)')
    if rewards.shape != P.shape[:2] or not np.isfinite(P).all() or not np.isfinite(rewards).all():
        raise ValueError('finite P and state-action rewards required')
    if np.any(P < 0) or not np.allclose(P.sum(axis=2),1,rtol=0,atol=1e-12):
        raise ValueError('each transition row must be a probability distribution')
    if not math.isfinite(gamma) or not 0 <= gamma < 1:
        raise ValueError('gamma must be in [0, 1)')
    return P, rewards


def policy_matrix(actions, P):
    actions = np.asarray(actions)
    if actions.shape != (len(P),) or not np.issubdtype(actions.dtype,np.integer):
        raise ValueError('one integer action index per state required')
    if np.any(actions < 0) or np.any(actions >= P.shape[1]):
        raise ValueError('action outside the model')
    return np.eye(P.shape[1])[actions]


def policy_model(P, rewards, policy, gamma):
    P, rewards = validate(P,rewards,gamma)
    policy = np.asarray(policy,float)
    if policy.shape != P.shape[:2] or not np.isfinite(policy).all() or np.any(policy < 0):
        raise ValueError('finite nonnegative action probabilities required')
    if not np.allclose(policy.sum(axis=1),1,rtol=0,atol=1e-12):
        raise ValueError('policy rows must sum to one')
    return np.einsum('sa,san->sn',policy,P), np.sum(policy*rewards,axis=1)


def exact_value(P, rewards, policy, gamma):
    kernel, mean_reward = policy_model(P,rewards,policy,gamma)
    return np.linalg.solve(np.eye(len(P))-gamma*kernel,mean_reward)


def action_values(P, rewards, value, gamma):
    P,rewards = validate(P,rewards,gamma)
    value = np.asarray(value,float)
    if value.shape != (len(P),) or not np.isfinite(value).all():
        raise ValueError('one finite value per state required')
    return rewards+gamma*np.einsum('san,n->sa',P,value)



def iterative_evaluation(P,rewards,policy,gamma=.9,tolerance=1e-9,max_sweeps=10000,mode='synchronous',initial=None):
    kernel,mean_reward = policy_model(P,rewards,policy,gamma)
    if not math.isfinite(tolerance) or tolerance <= 0 or type(max_sweeps) is not int or max_sweeps < 1:
        raise ValueError('positive tolerance and integer sweep budget required')
    if mode not in ('synchronous','in-place'):
        raise ValueError('unknown update mode')
    v = np.zeros(len(P)) if initial is None else np.array(initial,float,copy=True)
    if v.shape != (len(P),) or not np.isfinite(v).all():
        raise ValueError('one finite initial value per state required')
    trace=[]
    for sweep in range(max_sweeps+1):
        residual=float(np.max(np.abs(mean_reward+gamma*kernel@v-v)))
        trace.append(dict(sweep=sweep,value=v.tolist(),residual=residual,error_bound=residual/(1-gamma)))
        if residual/(1-gamma) <= tolerance:
            return v,trace
        if sweep == max_sweeps:
            raise RuntimeError('sweep budget exhausted before the requested error certificate')
        if mode == 'synchronous':
            v = mean_reward+gamma*kernel@v
        else:
            for s in range(len(v)):
                v[s] = mean_reward[s]+gamma*kernel[s]@v


def demo():
    P,r=model();policy=policy_matrix([1,1,0],P);rows=[]
    for mode in ['synchronous','in-place']:
        v,trace=iterative_evaluation(P,r,policy,mode=mode)
        exact=exact_value(P,r,policy,.9)
        rows.append(dict(mode=mode,sweeps=trace[-1]['sweep'],value=v.tolist(),exact=exact.tolist(),
                         actual_error=float(np.max(np.abs(v-exact))),certificate=trace[-1]['error_bound'],
                         trace=[x for x in trace if x['sweep'] in (0,1,2,5,10,20,trace[-1]['sweep'])]))
    return dict(policy=policy.tolist(),methods=rows)


if __name__ == '__main__':
    print(json.dumps(demo(),indent=2,allow_nan=False))

With requested value tolerance 1e-9, the synchronous method takes 92 sweeps. Its maximum actual error against the direct solution is approximately 4.48e-10, below its certificate of approximately 9.99e-10. In-place iteration in index order takes 63 sweeps, with actual error about 2.70e-10 and certificate about 8.55e-10. These counts describe this model, start vector, ordering and tolerance, not a universal speed advantage.

The function checks the initial vector too: an already valid solution needs zero sweeps. A sweep budget limits work, but exhaustion raises an error rather than returning an uncertified success. Empty or malformed distributions, nonfinite values, unsupported update modes and invalid budgets are rejected.

For S states and A actions, forming the dense fixed-policy kernel costs O(S²A) time. Each sweep and residual calculation costs O(S²), while a dense direct solve costs O(S³). The original model occupies O(S²A) space; saving every value vector in K sweeps adds O(KS) trace storage. A production implementation could omit most trace entries. Those costs concern computation from a model; they do not include learning the model from data.

The certificate does not validate the model

A small residual certifies closeness to the value of the supplied policy under the supplied model. If transition probabilities are wrong, the result may be precisely wrong about the real environment. If a reward is mis-specified, the solver faithfully evaluates the wrong objective.

The 1/(1−gamma) certificate used here excludes discount 1. Some undiscounted episodic problems can be evaluated under termination assumptions, but they need an appropriate state/boundary formulation and a different justification. Keeping an absorbing terminal row in a full system with discount 1 also makes I−P_pi singular; simply changing the number is not a complete method.

Finite-precision calculations are not interval proofs. Extremely small requested tolerances, ill-conditioning or huge reward scales can exceed the numerical precision available. The implementation exposes the residual and fails on an exhausted budget; it does not promise arbitrary accuracy.

Finally, even an exact value is not necessarily optimal. Evaluating the always-leave policy gives [2, 4, 0]. The entry value is lower than the advance/spin value, but that is a property of the policy, not a failure of evaluation. Policy iteration addresses how to improve it.

Audit a stopping claim

  1. Separate prediction and control. Why would replacing the policy-weighted action average by a maximum change this algorithm’s purpose?

    Answer: The average describes actions selected by the fixed policy. A maximum instead selects whichever action currently looks best, aiming at an optimality fixed point. It no longer measures the original rule’s expected return.

  2. Reproduce a sweep. Starting at zero for advance/spin, the first vector is [0, 1.6, 0]. Compute the second room value synchronously and in entry-first in-place order.

    Answer: Synchronous evaluation uses the old entry value zero: 1.6 + 0.36 × 0 + 0.36 × 1.6 = 2.176. In-place evaluation first sets entry to 1.44, then gives room value 1.6 + 0.36 × 1.44 + 0.36 × 1.6 = 2.6944.

  3. Calculate a certificate. At discount 0.99, the current residual is 0.01. Does that certify value error below 0.01? What residual would suffice?

    Answer: No. The bound is 0.01/(1−0.99)=1. To certify error at most 0.01, a residual at most 0.01 × 0.01 = 0.0001 suffices under the stated model assumptions and exact arithmetic.

  4. Design a failure report. The iteration budget expires before the certificate meets the target. What should a useful caller report instead of “converged”?

    Answer: Report the exhausted budget, requested tolerance, current residual and any valid bound, together with the update order and discount. The current code raises an exception; an extended interface could return a structured incomplete result. Neither route should label the estimate certified when the stopping condition failed.

One fixed policy, several computational methods

Sutton and Barto’s in-progress second edition explains known-model policy evaluation and synchronous versus in-place backups. Bertsekas’s discounted-DP notes supply the contraction and residual argument. The numerical comparison is an original small example; it does not reproduce either source’s figures.

Read policies and values for the quantities being solved, and value iteration for the maximum-over-actions operator. The two iterative loops can look nearly identical, so the operator inside the loop deserves more attention than the function’s name.

Make a prediction, then check

If a fixed-policy Bellman residual is delta and gamma is less than one, what value-error bound follows from contraction?

Choose one answer

Learning objectives

  • Derive and solve the fixed-policy Bellman linear system without changing the policy.
  • Compare update orders and use the current Bellman residual to certify value error under discounting.

Prerequisites & connections

Explore related knowledge →

References

  1. Reinforcement Learning: An Introduction — second-edition working draft (2014–2015)
    Richard S. Sutton; Andrew G. Barto · 2015
  2. MIT 6.231 Fall 2015 — discounted dynamic programming, Lectures 15–16
    Dimitri P. Bertsekas · 2015

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-23 · Single AI author. Scoped reading: PDF104–105 §4.1 policy evaluation, known dynamics, simultaneous equations and two-array versus in-place sweeps. Read2026-09-23. Read PDF167–168,173–175,179–180 and182–185; viewed175. Bounded discounted costs, policy/optimality operators, contraction, residual certificate and PI/VI. Diagrams181/184 were only partially legible as text. Tutorial switches cost minimization to reward maximization; affine reward-plus-transition maps are not called linear. 6 paired equations and four explained exercises. Checked fixed-policy linear solves against fraction oracles, synchronous and in-place sweep order, each current residual certificate, zero discount, initial values and explicit budget failure. In-place updates retain the old diagonal component rather than performing exact row solves.

  • Checked fixed-policy linear solves against fraction oracles, synchronous and in-place sweep order, each current residual certificate, zero discount, initial values and explicit budget failure. In-place updates retain the old diagonal component rather than performing exact row solves.
  • Four computed SVG variants per topic;12 numeric/geometry tests and36 responsive cases passed. Twelve selected current captures visually checked: eight byte-identical to viewed initial images and four reviewed final images; line-wrap revisions retained. Full article acceptance recorded separately.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.