AI Wiki中文/EN

Policy iteration: evaluate a rule, then improve it

策略迭代

Track two successive improvements, handle tied actions consistently, and distinguish exact guarantees from tolerance-based stopping.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

One improvement can make another action worth taking

In our synthetic arcade game, an initial policy leaves immediately: 2 points at entry or 4 points in the room. At discount 0.9, advancing from entry and then following that policy is worth 3.6, so we should change the entry action. Spinning in the room initially looks worse than leaving: its one-step lookahead is 3.76.

After changing the entry action, however, returning to entry is more valuable. Re-evaluate the new policy, and the room’s spin action now has lookahead value 4.336, better than leaving for 4. A second improvement becomes possible.

Policy iteration alternates these two questions: how good is the current rule, and which one-step deviations look better if we follow that rule afterward? Sutton and Barto, Sections 4.2–4.3 develop the policy-improvement argument. Bertsekas’s discounted-DP lectures place the evaluation and improvement operators in a fixed-point framework.

Two improvements lead through three evaluated rules. A separate one-state example shows the cost of a nonzero tie tolerance.
Two improvements lead through three evaluated rules. A separate one-state example shows the cost of a nonzero tie tolerance.

Evaluate fully, then compare actions against that value

Assume a finite, known MDP with bounded rewards and discount below 1. Begin with a stationary deterministic policy. Write its induced transition matrix and expected reward vector as P_pi and r_pi. Exact evaluation solves:

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

This step changes the value estimate, not the policy. Given that value, evaluate each action as a one-step deviation followed by the old policy, then choose a maximizing action:

qπ(s,a)=r(s,a)+γ∑s′P(s′∣s,a)vπ(s′),π′(s)∈arg max⁡aqπ(s,a).q_\pi(s,a)=r(s,a)+\gamma\sum_{s'}P(s'\mid s,a)v_\pi(s'),\qquad \pi'(s)\in\operatorname*{arg\,max}_a q_\pi(s,a).

Greedy here means greedy with respect to future value, not immediate reward alone. Since the old action is among the candidates, the new policy’s lookahead is at least as good as staying with the old action. In operator notation, T_pi' v_pi ≥ v_pi componentwise.

Why does a one-step comparison justify a permanent change?

The transition operator is monotone: if one value vector is no smaller componentwise, its expected continuation is no smaller. Repeatedly apply the new policy’s operator to the one-step improvement inequality:

vπ≤Tπ′vπ≤Tπ′2vπ≤⋯⟶vπ′.v_\pi\leq T_{\pi'}v_\pi\leq T_{\pi'}^2v_\pi\leq\cdots \longrightarrow v_{\pi'}.

Discounted contraction supplies the limit. Thus the new policy is no worse from any state, not merely from the chosen starting state. A strict advantage yields a strict improvement somewhere. This is the policy-improvement theorem’s argument; repeatedly selecting one action without re-evaluating the altered future would skip an essential part of policy iteration.

Follow both improvements in the same model

Number the states entry 0, room 1 and terminal 2. At entry, action 0 leaves for 2 and action 1 advances for 0. In the room, action 0 leaves for 4; action 1 earns 1.6 and moves to entry, room or terminal with probabilities 0.4, 0.4 and 0.2. Terminal actions are zero-reward self-loops. The evaluated sequence is:

(π(0),π(1))v(0)v(1)(0,0)24(1,0)3.64(1,1)360/79400/79\begin{array}{c|c|c} \bigl(\pi(0),\pi(1)\bigr)&v(0)&v(1)\\\hline (0,0)&2&4\\ (1,0)&3.6&4\\ (1,1)&360/79&400/79 \end{array}

Under the first policy, spinning has value 1.6 + 0.36 × 2 + 0.36 × 4 = 3.76, so only entry changes. After evaluating the second policy, that same action has value 1.6 + 0.36 × 3.6 + 0.36 × 4 = 4.336, so room changes too. Evaluating the third policy gives approximately [4.556962025, 5.063291139, 0]. The next improvement keeps both actions.

Stable ties prevent meaningless cycling

If the current action is already a maximizer, retain it. Otherwise choose a maximizing action with a fixed rule for ties. Arbitrarily changing between equally good actions can keep an action-ID-based stopping test running forever. The working draft’s Figure 4.3 caption explicitly points out this issue in its pseudocode.

In exact arithmetic, if the retained policy is greedy with respect to its exactly evaluated value, that value satisfies both the policy equation and the optimality equation:

vπ=Tπvπ=Tvπ,(Tv)(s)=max⁡a[r(s,a)+γ∑s′P(s′∣s,a)v(s′)]⟹vπ=v∗.v_\pi=T_\pi v_\pi=T v_\pi,\qquad (Tv)(s)=\max_a\left[r(s,a)+\gamma\sum_{s'}P(s'\mid s,a)v(s')\right] \quad\Longrightarrow\quad v_\pi=v_*.

Uniqueness of the discounted optimality fixed point justifies the last implication. With exact evaluation, strict improvements and consistent tie handling, a finite set of deterministic policies cannot supply infinitely many distinct strict improvements. At most A^S deterministic policies exist when every state has A actions. This is a finiteness argument, not a claim that enumerating them is efficient or necessary.

Numerical tolerance weakens the exact conclusion

The implementation retains the incumbent if the best computed action improves on it by no more than a declared tolerance tau. This prevents tiny numerical changes from continually swapping actions, but it can also ignore a real small advantage. For the current value vector, compute the optimality residual and its certificate:

δ=∥Tv−v∥∞,∥v−v∗∥∞≤δ1−γ.\delta=\|Tv-v\|_\infty,\qquad \|v-v_*\|_\infty\leq\frac{\delta}{1-\gamma}.

With mathematically exact policy evaluation, stability under the tolerance rule implies the largest remaining advantage is at most tau, and hence residual at most tau. Floating-point evaluation may add error, so the code reports the actual computed residual rather than treating tolerance alone as a proof. The discounted contraction framework supports the residual bound in exact arithmetic.

For a one-state self-loop with action rewards 0 and 5e-7, discount 0.9 and tolerance 1e-6, the policy choosing zero can remain unchanged. It is suboptimal by 5e-6. The residual certificate reports that scale instead of declaring exact optimality.

Save each evaluated policy before changing it

Save this original program as policy_iteration.py, using Python 3.12 and NumPy 1.26.4. It solves each fixed-policy system directly, computes all action lookaheads and changes only actions with improvement exceeding the tolerance. The trace records the evaluated policy, its value, the number of changed actions and the optimality residual.

"""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 improve(q,actions,tie_tolerance=0.0):
    q=np.asarray(q,float);actions=np.asarray(actions)
    if q.ndim != 2 or not q.size or not np.isfinite(q).all():
        raise ValueError('finite state-action scores required')
    if actions.shape != (len(q),) or not np.issubdtype(actions.dtype,np.integer) or np.any(actions<0) or np.any(actions>=q.shape[1]):
        raise ValueError('valid current actions required')
    if not math.isfinite(tie_tolerance) or tie_tolerance < 0:
        raise ValueError('nonnegative finite tie tolerance required')
    best=np.argmax(q,axis=1);indices=np.arange(len(q))
    # Retain the incumbent on exact or declared near ties.
    return np.where(q[indices,best]>q[indices,actions]+tie_tolerance,best,actions)


def policy_iteration(P,rewards,gamma=.9,initial=None,tie_tolerance=1e-12,max_rounds=100):
    P,rewards=validate(P,rewards,gamma)
    if type(max_rounds) is not int or max_rounds<1:raise ValueError('positive round budget required')
    actions=np.zeros(len(P),dtype=int) if initial is None else np.asarray(initial).copy()
    policy_matrix(actions,P);trace=[]
    for round_ in range(max_rounds):
        v=exact_value(P,rewards,policy_matrix(actions,P),gamma)
        q=action_values(P,rewards,v,gamma)
        new=improve(q,actions,tie_tolerance)
        residual=float(np.max(np.abs(np.max(q,axis=1)-v)))
        trace.append(dict(round=round_,actions=actions.tolist(),values=v.tolist(),
                          changed=int(np.count_nonzero(new!=actions)),optimality_residual=residual))
        if np.array_equal(new,actions):
            return dict(actions=actions.tolist(),values=v.tolist(),trace=trace,
                        value_error_bound=residual/(1-gamma),tie_tolerance=tie_tolerance)
        actions=new
    raise RuntimeError('round budget exhausted without a stable policy')


def demo():
    P,r=model()
    return dict(result=policy_iteration(P,r),
                tied_incumbents=improve([[1,1],[2,2]],[1,0]).tolist(),
                tolerated_small_gain=improve([[1,1+5e-7]],[0],1e-6).tolist())


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

The default run evaluates three policies and performs two improvements. Its action arrays are [0,0,0], [1,0,0] and [1,1,0]; the terminal’s dummy action remains 0. The final residual is about 8.88e-16, near floating-point roundoff. This observed small residual and the separately checked enumeration of all four nonterminal deterministic policies support the result for this tiny model.

The output also shows that exact ties preserve the current actions, while a gain of 5e-7 can be ignored under tolerance 1e-6. A round budget is an operational safeguard; exhausting it raises an error, not a success flag. No transition samples are collected: this is planning with known probabilities and rewards.

For dense arrays, each round costs O(S³) for direct evaluation plus O(S²A) for action lookaheads and kernel construction. The model occupies O(S²A) memory; a trace of K rounds adds O(KS) stored policies and values. The number of rounds depends on the problem. Approximate evaluation can reduce per-round work, but then its error must enter the analysis rather than inheriting the exact-policy proof unchanged.

Do not infer a theorem from a stopped loop

The monotonic-improvement argument assumes the evaluated value matches the current policy in the same model. Stale values, inaccurate model estimates or coarse evaluation can make a supposedly improving action worse. The full known-model result does not automatically transfer to approximate neural values or sampled estimates.

Tie handling also has a scope. Retaining an exactly maximizing incumbent avoids needless changes without sacrificing optimality. Treating near ties as equal intentionally permits some residual suboptimality. Report the tolerance and residual; “policy stable” alone does not tell the reader which case occurred.

Discount 1, improper nonterminating policies and unbounded returns require other conditions. This implementation rejects discount 1. The source lectures discuss broader dynamic-programming settings, but this article uses only the finite discounted case.

Finally, our three-state example illustrates dependency between improvements. It is not evidence that policy iteration always needs three evaluations, or that it is universally faster than value iteration. Comparing algorithms requires counting both rounds and the work within each round.

Check the future used in an improvement

  1. Explain the greedy choice. Why does the first improvement advance at entry even though it earns zero immediately?

    Answer: Improvement compares immediate reward plus discounted old-policy continuation. Advancing reaches a room worth 4 under the old policy, giving lookahead 3.6, which exceeds leaving for 2.

  2. Calculate the second improvement. Why does spin lose to exit before the entry action changes, but win afterward?

    Answer: Its first lookahead is 1.6 + 0.36 × (2+4) = 3.76, below 4. After exact re-evaluation of advance/exit, entry is worth 3.6 and the lookahead becomes 1.6 + 0.36 × (3.6+4) = 4.336. The transition model is unchanged; the value of returning to entry changed.

  3. Repair a tie loop. A one-state model has two identical actions. The implementation alternates their IDs on every greedy update and stops only if the ID is unchanged. What should be repaired?

    Answer: Retain the current action if it already maximizes the value, or use another consistent tie/stopping convention that does not force unnecessary switches. Alternating equally good IDs can prevent termination even though the value is already optimal.

  4. Assess a tolerance claim. In the one-state example with rewards 0 and 5e-7, discount 0.9 and tolerance 1e-6, is a stable zero-reward policy exactly optimal?

    Answer: No. The better action’s continuing value is 5e-7/(1−0.9)=5e-6, while the retained policy’s value is zero. Its remaining one-step advantage is below tolerance. Report the residual-based error scale instead of replacing numerical stability with an exact-optimality claim.

Alternate two operations without conflating them

Sutton and Barto’s working draft supplies the improvement inequality, repeated evaluation/improvement sequence and an explicit warning about ties. Bertsekas’s Lectures 15–16 express the same discounted planning ideas through policy and optimality operators. The implementation here uses a direct linear solve and its own model, not copied source pseudocode or a reproduced benchmark.

Read policy evaluation for the inner prediction step. Value iteration interleaves improvement with incomplete value updates; Q-learning uses sampled transitions under a different information setting. Similar-looking maxima do not make their inputs or guarantees identical.

Make a prediction, then check

Several actions have exactly equal best values. Why retain the current action if it is one of them?

Choose one answer

Learning objectives

  • Explain the policy-improvement inequality and reproduce the full evaluation/improvement sequence.
  • Prevent tie cycling and report a residual-based bound when numerical tolerance permits a small remaining advantage.

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: PDF108–111 §4.2–4.3 improvement, monotonic sequence and Fig4.3 explicit tie-cycling warning; viewed111. 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 every deterministic starting rule, the full two-improvement chain, value monotonicity, exact-tie incumbents, tolerance counterexample and residual bound. Floating-point tolerance is distinct from the exact finite-policy theorem.

  • Checked every deterministic starting rule, the full two-improvement chain, value monotonicity, exact-tie incumbents, tolerance counterexample and residual bound. Floating-point tolerance is distinct from the exact finite-policy theorem.
  • 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.