Markov decision processes: policies, returns and Bellman equations
Model sequential decisions as Markov decision processes and evaluate stationary policies using discounted returns and Bellman equations.
After this lesson you can
- Specify states, actions, rewards and transitions for a Markov decision process.
- Distinguish stationary policies, induced chains, termination and truncation.
- Derive Bellman expectation equations for state and action values.
- Solve finite discounted policy evaluation as a linear system.
- Interpret discounted occupancy and its normalization.
Before you start
Actions also change what comes next
In a bandit, the choice determines the observed reward, but does not itself change a persistent situation. In a warehouse, selling a unit reduces tomorrow’s inventory; on a board, moving changes the actions available afterward. A decision that looks good for its immediate reward can leave you in a worse state.
A Markov decision process (MDP) describes this interaction. To begin, take finite sets of states and actions , an initial distribution and a kernel
For continuous rewards, replace the sum over with the corresponding integral. The Markov property requires that, conditional on the current state and action, the joint distribution of the next state and reward does not depend on the rest of the history. It does not say that successive observations are independent or that actions have no future effect.
A state must retain what is needed to predict and decide. If you observe only inventory but demand depends on the season and the season cannot be inferred from inventory, your representation may not be Markov. Adding the season or maintaining a belief about it can help; a partial observation does not automatically become a sufficient state by calling it one. In text generation, the full prefix can serve as the state for a defined autoregressive generation process, although truncating context or changing tools and memory changes the relevant model.
Policies and the induced chain
A stationary Markov policy is a distribution over actions depending on the current state, not time. It can be deterministic, concentrating all mass on one action, or stochastic. A history-dependent policy can use the whole trajectory; a non-stationary Markov policy can also depend explicitly on time. Not all induce a single homogeneous transition matrix over the original state.
The marginal transition and expected immediate reward are
If mean reward depends on the transition, , then . Do not multiply by the transition probability twice. Reward and next state can be correlated: the joint kernel preserves that dependence.
For a fixed stationary policy, the induced chain has matrix and reward
Each row of sums to one. It is a Markov reward process, even if it is not irreducible or has no unique stationary distribution. The policy and model remain fixed in this lesson’s evaluation equations.
What it means to value the future
For , the discounted return from time is
If , the series converges absolutely and . The weights sum to : this is often called the effective horizon, although it is not a sharp cutoff. If you retain only the first rewards, the tail magnitude is at most . Changing changes the relative importance of near and distant rewards and can change the preferred policy.
An episode can terminate in an absorbing state with zero subsequent reward. If the task has an intrinsic finite horizon, remaining time may be needed in the state to maintain the Markov property, and the optimal policy can depend on it. An external simulation cutoff for a continuing task is different: ending a trajectory for convenience does not imply that true future value is zero. Gymnasium distinguishes termination and truncation; when using bootstrap estimates, that distinction changes the target.
Another choice for continuing tasks is long-run average reward, for example when the limit exists. It can depend on the initial state if there are multiple recurrent classes. It is not simply discounted return with : the undiscounted series may diverge. In episodes with , additional conditions are needed, such as proper termination and integrable return.
State and action value
The value functions of a fixed policy are
In the first action is forced and then is followed, even when . The conditional notation above abbreviates that fixed-first-action experiment; it does not require conditioning on a zero-probability event. For stationary policies and homogeneous dynamics, both values depend on state, not time. The relationship is . Separating the first reward and applying the tower property gives the Bellman evaluation equation:
These are expectation equations for a given policy: no maximum over actions appears. The optimality equation, studied later, is a different operation. See Sutton and Barto, chapter 3.
Solving and counting visits
In matrix form, . For , matrix is stochastic and . Therefore the Neumann series converges and
This is exact policy evaluation for a known finite discounted MDP. In a numerical implementation, solve the linear system rather than forming the inverse just to multiply it; if approaches one, check conditioning and numerical error.
Entry of the inverse is : an expected discounted number of visits, including the initial visit. Its entries are nonnegative and each row sums to , because each has rows summing to one. Multiplying a row by gives a probability distribution. It is equivalent to observing the state at an independent time with ; it is not generally the chain’s stationary distribution.
Modeling before optimizing
For inventory, a state might include available units, outstanding orders and a demand signal; the action decides how much to order and the transition incorporates arrivals and demand. Reward can combine revenue, order cost and stockout penalty, with explicit units and timing. In defensive vulnerability management, the state can include exposure, assets and pending patches; actions allocate resources and transitions represent changes in exposure. If variables are hidden or a budget depends on history, include them or model partial observability.
A reward specifies the objective, but does not guarantee it: rewarding only the number of closed alerts can incentivize closing them without resolving risk. Before comparing policies, check the horizon, allowed actions, information availability and what happens at termination. The next lab compares an exact linear system with simulation of the same policy and model.
We represent expected rewards R[s,a] and transitions P[s,a,siguiente]. In both examples the original reward can depend on the transition outcome: first we compute its conditional expectation. The simulation uses that expected reward, so it estimates the same expected value, although its return distribution need not match that of the original rewards. Terminal states are absorbing with zero subsequent reward; the simulation limit is numerical truncation, not a new terminal.
import numpy as np
class MDP:
def __init__(self,P,R):
P=np.asarray(P,dtype=float); R=np.asarray(R,dtype=float)
if P.ndim!=3 or not all(P.shape) or P.shape[0]!=P.shape[2] or R.shape!=P.shape[:2]:
raise ValueError('Formas incompatibles')
if not np.all(np.isfinite(P)) or np.any(P<0) or not np.allclose(P.sum(axis=2),1,atol=1e-12,rtol=0):
raise ValueError('Transiciones inválidas')
if not np.all(np.isfinite(R)):
raise ValueError('Recompensas inválidas')
self.P=P.copy(); self.R=R.copy()
self.S,self.A=R.shape
def evaluate(self,pi,gamma):
pi=np.asarray(pi,dtype=float)
if pi.shape!=(self.S,self.A) or not np.all(np.isfinite(pi)) or np.any(pi<0) or not np.allclose(pi.sum(axis=1),1,atol=1e-12,rtol=0):
raise ValueError('Política inválida')
if not np.isfinite(gamma) or not 0<=gamma<1:
raise ValueError('Se requiere 0≤gamma<1')
transition=np.einsum('sa,san->sn',pi,self.P)
reward=np.sum(pi*self.R,axis=1)
value=np.linalg.solve(np.eye(self.S)-gamma*transition,reward)
q=self.R+gamma*np.einsum('san,n->sa',self.P,value)
return value,q,transition,reward
def gridworld():
# Cuadrícula 3×3: centro bloqueado, trampa 3 y meta 8.
states=[0,1,2,3,5,6,7,8]; index={s:i for i,s in enumerate(states)}
P=np.zeros((len(states),4,len(states))); R=np.zeros((len(states),4))
moves=[(-1,0),(0,1),(1,0),(0,-1)]
for s in states:
i=index[s]
for a in range(4):
if s in (3,8):
P[i,a,i]=1
continue
for move,probability in ((a,.8),((a-1)%4,.1),((a+1)%4,.1)):
dr,dc=moves[move]; row,col=divmod(s,3); nr,nc=row+dr,col+dc
candidate=3*nr+nc
dest=candidate if 0<=nr<3 and 0<=nc<3 and candidate in index else s
reward=1.0 if dest==8 else (-1.0 if dest==3 else -.05)
P[i,a,index[dest]]+=probability
R[i,a]+=probability*reward
return MDP(P,R), index[0]
def inventory():
# Estado: 0..3 unidades; acción: pedir 0 o 1 antes de demanda.
P=np.zeros((4,2,4)); R=np.zeros((4,2))
for stock in range(4):
for action in range(2):
order=min(action,3-stock); available=stock+order
for demand,probability in enumerate((.3,.5,.2)):
sold=min(demand,available); remaining=available-sold
reward=2*sold-.5*order-.1*remaining
P[stock,action,remaining]+=probability
R[stock,action]+=probability*reward
return MDP(P,R), 0
def monte_carlo(mdp,pi,gamma,start,seed,episodes=3000,horizon=60):
rng=np.random.default_rng(seed)
states=np.full(episodes,start,dtype=int); returns=np.zeros(episodes)
discount=1.0
for _ in range(horizon):
u=rng.random(episodes)
actions=(u[:,None]>=np.cumsum(pi[states],axis=1)).sum(axis=1)
actions=np.minimum(actions,mdp.A-1)
returns+=discount*mdp.R[states,actions]
u=rng.random(episodes)
next_states=(u[:,None]>=np.cumsum(mdp.P[states,actions],axis=1)).sum(axis=1)
states=np.minimum(next_states,mdp.S-1)
discount*=gamma
return returns.mean(),returns.std(ddof=1)/np.sqrt(episodes)
gamma=.9
for name,builder,seed in [('Gridworld',gridworld,101),('Inventario',inventory,102)]:
mdp,start=builder()
pi=np.full((mdp.S,mdp.A),1/mdp.A)
value,q,transition,reward=mdp.evaluate(pi,gamma)
occupancy=np.linalg.solve(np.eye(mdp.S)-gamma*transition,np.eye(mdp.S))
assert np.allclose(value,reward+gamma*transition@value,atol=1e-10,rtol=0)
assert np.allclose(value,np.sum(pi*q,axis=1),atol=1e-10,rtol=0)
assert np.allclose((1-gamma)*occupancy.sum(axis=1),1,atol=1e-10,rtol=0)
estimate,se=monte_carlo(mdp,pi,gamma,start,seed)
# Cota del resto: |R|max gamma^H / (1-gamma).
tail=np.max(np.abs(mdp.R))*gamma**60/(1-gamma)
print(name,'V exacto inicial',round(float(value[start]),4),
'Monte Carlo',round(float(estimate),4),'error estándar',round(float(se),4),
'cota de truncación',round(float(tail),4))The Monte Carlo difference is random; we do not require a particular sample to fall within an arbitrary tolerance. The standard error describes only variation in those simulations with mean reward, and the truncation term separately bounds omitted discount. The effective horizon 1/(1−γ) summarizes geometric mass; it does not mean all later rewards disappear.
Exercises
Step 1 of 3. How do you separate the first term of return?
Step 1 of 3. Why does the matrix geometric series converge?
import numpy as np
def evaluate_policy(P,R,pi,gamma):
pass
gamma=.5
v2=0.0
v1=2+gamma*v2
v0=1+gamma*v1
print('Vπ(0), Vπ(1), Vπ(2):',v0,v1,v2)