Policies and values: whose future does a value describe?
策略与价值函数
Solve a stochastic policy, compute action values and discounted occupancy, and distinguish two kinds of policy mixtures.
policies-valuesThe same room can be worth different amounts
Return to the invented arcade game. At entry, leaving earns 2 points and advancing earns 0 before moving to a room. In that room, leaving earns 4 and ends the episode. Spinning earns 1.6, then moves to entry, room or termination with probabilities 0.4, 0.4 and 0.2. The discount is 0.9.
The room is worth 4 to a policy that always leaves there. It is worth approximately 5.063291 to a policy that always spins there and advances whenever it reaches entry. A state’s value is not a permanent property of its location: it describes a future under a specified policy and reward objective.
Sutton and Barto’s value-function definitions make that dependence explicit. This article calculates it, then asks a less obvious question: does flipping a coin at each state have the same value as flipping one coin at the start to choose an entire policy?
Condition on the action you actually commit to
Assume a finite MDP with known transition probabilities, finite expected rewards and discount below 1. A stationary policy gives an action distribution in each state. For return G_t, its state value and action value are:
The action-value definition means: take action a once, then follow pi thereafter. It does not mean repeat a forever, and it does not silently switch to an optimal policy. This distinction matters even when the first action is one that pi would never choose.
Let P(s'|s,a) be the transition probability and r(s,a) the expected immediate reward. Splitting the return after one step gives:
The second equation averages over the policy’s first action. It does not take a maximum; a policy that sometimes selects worse actions has a correspondingly lower expected value. The working draft’s Sections 3.7 and 4.1 develop these conditional values and fixed-policy expectations.
A policy turns an MDP into a Markov reward process
After choosing a policy, average out the action selection. Define its state-to-state transition matrix and reward vector:
Each row of P_pi sums to one. A deterministic policy chooses one action row; it does not force that row to be deterministic. In our game, a deterministic instruction to spin still has three possible outcomes.
Using column vectors for values, the Bellman equation becomes a linear system:
The inverse exists in this finite discounted setting. Powers of gamma P_pi shrink in maximum row-sum norm, so its geometric matrix series converges. In code we solve the system directly rather than explicitly constructing the inverse. Bertsekas’s discounted-DP lectures give the fixed-policy operator and contraction framework. Those lectures minimize costs; here we maximize rewards. The fixed-policy expectation is unaffected by that change of objective sign.
Work through a randomized rule
At each nonterminal state, choose either action with probability 1/2. Include a terminal absorbing state with zero reward so that the transition matrix remains stochastic. The terminal value is zero.
At entry, the expected immediate reward is 1 and half the transitions go to the room, giving the equation v0 = 1 + 0.45 v1. In the room, the expected immediate reward is 2.8; mixing leaving with spinning gives v1 = 2.8 + 0.18 v0 + 0.18 v1. Solving yields approximately v0=2.814614344 and v1=4.032476319.
The two action values at entry are 2 and approximately 3.629228687. Their average is 2.814614344. The second value is 0.9 × v1: advance once, then use the randomized policy in the room. It is not the value of committing to always spin.
Occupancy connects local rewards to total performance
A policy also changes which states the agent visits. Let mu be a column vector giving the fixed starting-state distribution. The normalized discounted occupancy vector is:
Each term is a state distribution weighted by a discounted time weight. Those weights sum to one, so occupancy does too. This definition includes infinitely many zero-reward self-loops after termination. If instead we discarded terminal visits and used a transition matrix only over nonterminal states, the total mass need not be one; that would be a different convention.
Separate the first term of the series. The remaining terms equal gamma P_pi^T d_pi, giving a balance equation. Summing expected rewards through the same occupancy also recovers the start-distribution value:
This is a finite-matrix derivation from the preceding model, not an extra empirical claim. Starting at entry under the randomized policy gives occupancy approximately [0.110960758, 0.060893099, 0.828146143]. Much of the discounted mass belongs to the terminal state, but it contributes no reward. Substituting the reward vector into the last equation recovers 2.814614344.
Two kinds of mixture produce different futures
Policy A always leaves; policy B advances and spins. One experiment chooses A or B with probability 1/2 at the beginning, remembers the choice and uses it throughout the episode. Another chooses between their actions with probability 1/2 every time a state is visited. In general:
The right side describes the initial whole-policy lottery. Its entry value is (2 + 4.556962025)/2, approximately 3.278481013. The left side is the statewise randomized rule just solved, with entry value 2.814614344. The once-chosen policy couples choices across a trajectory; repeated randomization allows different sequences. Because those sequences change subsequent visits, value is not generally linear in the policy probabilities. There is no contradiction with linearity of expectation: the two expectations concern different random experiments.
Values, action values and occupancy from one table
Save this original program as values.py. It runs with Python 3.12 and NumPy 1.26.4. Array P has axes current state, action, next state; rewards contains state-action expected rewards. The model is known, so these are planning calculations rather than estimates learned from samples.
"""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 discounted_occupancy(P, rewards, policy, start, gamma):
kernel,_ = policy_model(P,rewards,policy,gamma)
start = np.asarray(start,float)
if start.shape != (len(P),) or not np.isfinite(start).all() or np.any(start < 0) or not np.isclose(start.sum(),1,rtol=0,atol=1e-12):
raise ValueError('start must be a state distribution')
# Column-vector solution; terminal self-loops are included in this occupancy.
return np.linalg.solve(np.eye(len(P))-gamma*kernel.T,(1-gamma)*start)
def demo():
P,r = model(); gamma = .9
policy = np.array([[.5,.5],[.5,.5],[1,0]])
v = exact_value(P,r,policy,gamma);q = action_values(P,r,v,gamma)
occupancy = discounted_occupancy(P,r,policy,[1,0,0],gamma)
_,rp = policy_model(P,r,policy,gamma)
extremes = [exact_value(P,r,policy_matrix(a,P),gamma) for a in ([0,0,0],[1,1,0])]
return dict(policy=policy.tolist(),values=v.tolist(),action_values=q.tolist(),
state_value_from_q=np.sum(policy*q,axis=1).tolist(),
discounted_occupancy=occupancy.tolist(),
occupancy_start_value=float(occupancy@rp/(1-gamma)),
half_mixture_of_whole_policies=((extremes[0]+extremes[1])/2).tolist(),
extreme_values=[x.tolist() for x in extremes])
if __name__ == '__main__':
print(json.dumps(demo(),indent=2,allow_nan=False))
The output contains the randomized policy, its state and action values, occupancy, and the whole-policy mixture. The first state’s value reconstructed from action values and from occupancy agrees with the linear-system value to floating-point precision. The terminal entry is kept in all arrays, and both of its actions have identical zero-reward self-loops.
With S states and A actions stored densely, forming the induced kernel costs O(S²A) time and storing the original model costs O(S²A) space. A dense direct solve costs O(S³) time and O(S²) working space; occupancy needs another such solve. Sparse models can use different methods. As discount approaches 1, conditioning and numerical accuracy deserve attention; the code restricts discount to below 1 and rejects malformed distributions and nonfinite inputs.
A value has conditions attached
Values change if the policy, transition model, reward definition or discount changes. A state label also needs sufficient predictive information for the assumed Markov model. An exact solve cannot repair a model that confuses distinct situations under the same state ID.
Occupancy is not the ordinary stationary distribution of a continuing Markov chain. It depends on the initial distribution and the discount; it exists here without requiring the chain to be irreducible. Its normalization includes the absorbing completion convention, which should remain visible when interpreting the large terminal mass.
The whole-policy lottery is also not generally a memoryless policy on the original observed state alone: its initial choice is remembered. It could be represented with an augmented state containing that choice. Comparing it with per-visit randomization without describing that memory would obscure why the returns differ.
The discounted-DP theory supplies conditions for a unique fixed value in this setting. It does not justify replacing expectation with a maximum while claiming to evaluate the same policy. Policy evaluation keeps the rule fixed; control methods decide how to change it.
Name the future behind each number
-
Interpret an action value. Under a policy that always leaves in the room, what future follows the entry action “advance” in
q_pi(entry, advance)?Answer: Advance once for zero reward, arrive at the room, then follow the specified policy and leave for 4. The action value is 3.6 at discount 0.9. It does not assume that later actions are optimal or that advancing is repeated forever.
-
Calculate a consistency check. For the randomized policy, the room value is approximately 4.032476319. Recover the entry action values and state value.
Answer: Leaving has action value 2; advancing has
0.9 × 4.032476319 ≈ 3.629228687. Equal action probabilities give their mean, approximately 2.814614344, matching the solved entry value. -
Find a modeling error. Someone removes the terminal component from the reported occupancy vector and renormalizes the other two components to sum to one. Can they use the same performance equation unchanged?
Answer: No. Renormalization changes the measure and its scale. The reported identity uses the original discounted weights over all states, including zero-reward absorbing visits. A nonterminal-only or conditional distribution needs its own normalization factor and derivation.
-
Design a mixture experiment. How would you implement the two policy mixtures so that the difference can actually be observed?
Answer: In one experiment, sample a policy ID at reset and retain it until termination. In the other, independently sample the action choice each time a nonterminal state is visited. Keep the environment and discount identical, collect separate returns, and compare with the two model-derived values. Merely averaging action probabilities does not reproduce the remembered policy lottery.
Expectations first, optimization afterward
The Sutton–Barto working draft defines state and action values as conditional expected returns. Bertsekas’s Lectures 15–16 treat their fixed points through discounted operators. The occupancy identity and mixture example here are original deductions and calculations from the declared finite model.
The source book is the 2014–2015 in-progress edition, read at the recorded value/evaluation sections. Continue with policy evaluation for iterative computation, then policy iteration and value iteration for optimization. Keeping these questions separate makes it easier to see when an algorithm has changed the policy it is supposed to describe.
Make a prediction, then check
What does q_pi(s,a) mean?
Learning objectives
- Relate a policy, its induced transition matrix, state values and one-action-then-policy values.
- Derive normalized discounted occupancy and explain why per-state randomization differs from selecting a whole policy once.
Prerequisites & connections
Explore related knowledge →References
- Reinforcement Learning: An Introduction — second-edition working draft (2014–2015)
Richard S. Sutton; Andrew G. Barto · 2015 - 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: PDF84 definitions3.10–3.11,104–105 fixed-policy expectation/backups; occupancy is an original finite-matrix derivation from those equations. 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. 7 paired equations and four explained exercises. Checked all deterministic policy values against independent rational elimination, v as the policy average of q, discounted occupancy by independent distribution accumulation, terminal mass and whole-policy versus per-visit mixing.
- Checked all deterministic policy values against independent rational elimination, v as the policy average of q, discounted occupancy by independent distribution accumulation, terminal mass and whole-policy versus per-visit mixing.
- 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:
- Reinforcement Learning: An Introduction — second-edition working draft (2014–2015) · PDF84 definitions3.10–3.11,104–105 fixed-policy expectation/backups; occupancy is an original finite-matrix derivation from those equations. Read2026-09-23.
- MIT 6.231 Fall 2015 — discounted dynamic programming, Lectures 15–16 · 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.
Related topics