Module contents
Lesson 6 of 37Core 105 min

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 S\mathcal S and actions A\mathcal A, an initial distribution and a kernel

p(s′,r∣s,a)=P(St+1=s′,Rt+1=r∣St=s,At=a).p(s',r\mid s,a)=\Pr(S_{t+1}=s',R_{t+1}=r\mid S_t=s,A_t=a).

For continuous rewards, replace the sum over rr 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.

InteractiveA policy on the board
Action↑ up→ right↓ down← left
Qπ−0.761−0.798−0.469−0.742

Floor costs −0.04 per step; entering a goal pays +1 and entering a trap −1. Goals and traps are absorbing with no later rewards. Attempting to cross a wall or edge keeps the agent in place and incurs the usual cost.

The intended action executes with probability 1−ε; each perpendicular direction is taken with probability ε/2. The uniform policy chooses each action with probability 1/4. Values solve (I−γPπ)V=rπ, with γ<1; Q uses the same dynamics then follows the selected policy. Wall cells are implemented as auxiliary absorbing positions inaccessible from floor.

Selected state
Row 1, column 1
V of that state
−0.798
Bellman error
2.2e-16
Edit the environment and policy to see how each action’s values and consequences change.

Policies and the induced chain

A stationary Markov policy π(a∣s)\pi(a\mid s) 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

P(s′∣s,a)=∑rp(s′,r∣s,a),r(s,a)=∑s′,rp(s′,r∣s,a)r.P(s'\mid s,a)=\sum_r p(s',r\mid s,a),\qquad r(s,a)=\sum_{s',r}p(s',r\mid s,a)r.

If mean reward depends on the transition, r(s,a,s′)=E[Rt+1∣s,a,s′]r(s,a,s')=\mathbb E[R_{t+1}\mid s,a,s'], then r(s,a)=∑s′P(s′∣s,a)r(s,a,s′)r(s,a)=\sum_{s'}P(s'\mid s,a)r(s,a,s'). 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

Pπ(s,s′)=∑aπ(a∣s)P(s′∣s,a),rπ(s)=∑aπ(a∣s)r(s,a).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).

Each row of PπP_\pi 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 0≤γ<10\leq\gamma<1, the discounted return from time tt is

Gt=∑k=0∞γkRt+k+1=Rt+1+γGt+1.G_t=\sum_{k=0}^{\infty}\gamma^kR_{t+k+1} =R_{t+1}+\gamma G_{t+1}.

If ∣Rt∣≤Rmax⁡|R_t|\leq R_{\max}, the series converges absolutely and ∣Gt∣≤Rmax⁡/(1−γ)|G_t|\leq R_{\max}/(1-\gamma). The weights sum to 1/(1−γ)1/(1-\gamma): this is often called the effective horizon, although it is not a sharp cutoff. If you retain only the first HH rewards, the tail magnitude is at most Rmax⁡γH/(1−γ)R_{\max}\gamma^H/(1-\gamma). Changing γ\gamma changes the relative importance of near and distant rewards and can change the preferred policy.

InteractiveWhich rewards count
Reward weight γᵏ
0.00.51.0k = 0k = 30

The highlighted bar is k=5, with weight 0.5905. The indifference threshold is γ=0.8027: above it the delayed reward wins, below it the immediate reward wins.

Convention: Gₜ=Rₜ₊₁+γRₜ₊₂+γ²Rₜ₊₃+…; k=0 corresponds to Rₜ₊₁. The corridor has two deterministic routes: one pays 2 at k=0 and ends; the other pays 0 for the first 5 transitions, then 6 at k=5 and ends. The infinite sum of weights is 1/(1−γ), not an exact trajectory cutoff. The plot shows only k=0,…,30; γ=0 retains only the first reward.

0.90
5
2
6
Effective horizon
10.00
Immediate return
2.000
Delayed return
3.543
Preference
Delayed reward
Change the discount to compare future weights and two consequences at different distances.

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 lim⁡T→∞T−1E[∑t=0T−1Rt+1]\lim_{T\to\infty}T^{-1}\mathbb E[\sum_{t=0}^{T-1}R_{t+1}] when the limit exists. It can depend on the initial state if there are multiple recurrent classes. It is not simply discounted return with γ=1\gamma=1: the undiscounted series may diverge. In episodes with γ=1\gamma=1, additional conditions are needed, such as proper termination and integrable return.

State and action value

The value functions of a fixed policy are

Vπ(s)=Eπ[Gt∣St=s],Qπ(s,a)=Eπ[Gt∣St=s,At=a].V^\pi(s)=\mathbb E_\pi[G_t\mid S_t=s],\qquad Q^\pi(s,a)=\mathbb E_\pi[G_t\mid S_t=s,A_t=a].

In QπQ^\pi the first action is forced and then π\pi is followed, even when π(a∣s)=0\pi(a\mid s)=0. 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 Vπ(s)=∑aπ(a∣s)Qπ(s,a)V^\pi(s)=\sum_a\pi(a\mid s)Q^\pi(s,a). Separating the first reward and applying the tower property gives the Bellman evaluation equation:

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

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.

InteractiveA Bellman backup
V(Start) = 1.680
Averages over actions of π.
Safe
π = 60 % · Q = 2.000 → contribution 1.200
P = 1.00 · (r = 2.0 + 0.90 × V(Terminal) = 0.000)
Contribution 2.000
Risky
π = 40 % · Q = 1.199 → contribution 0.480
P = 0.70 · (r = 0.0 + 0.90 × V(Continuation) = 2.379)
Contribution 1.499
P = 0.30 · (r = −1.0 + 0.90 × V(Terminal) = 0.000)
Contribution −0.300

The safe action ends and pays 2 from Start or 3 from Continuation. The risky action moves to the other state with probability p, paying 0 from Start and 1 from Continuation; on failure it ends and pays −1 or 0 respectively. Terminal is absorbing with later reward 0 and V(terminal)=0. The indicated reward arrives on the current transition, before discounting the next value by γ.

Values exactly solve the two Bellman equations for the chosen policy. Q mode fixes the initial action and follows π thereafter; V mode also averages over action probabilities. Zero-probability branches are shown to keep the model visible.

State
Backup
60 %
50 %
70 %
0.90
2
Value V
1.680
V(start)
1.680
V(continuation)
2.379
Expand the action and transition branches and see how their contributions are summed.

Solving and counting visits

In matrix form, Vπ=rπ+γPπVπV^\pi=r_\pi+\gamma P_\pi V^\pi. For 0≤γ<10\leq\gamma<1, matrix PπP_\pi is stochastic and ∥γPπ∥∞=γ<1\|\gamma P_\pi\|_\infty=\gamma<1. Therefore the Neumann series converges and

(I−γPπ)−1=∑k=0∞γkPπk,Vπ=(I−γPπ)−1rπ.(I-\gamma P_\pi)^{-1}=\sum_{k=0}^{\infty}\gamma^kP_\pi^k,\qquad V^\pi=(I-\gamma P_\pi)^{-1}r_\pi.

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 γ\gamma approaches one, check conditioning and numerical error.

Entry (s,s′)(s,s') of the inverse is ∑k≥0γkP(St+k=s′∣St=s)\sum_{k\geq0}\gamma^k\Pr(S_{t+k}=s'\mid S_t=s): an expected discounted number of visits, including the initial visit. Its entries are nonnegative and each row sums to 1/(1−γ)1/(1-\gamma), because each PπkP_\pi^k has rows summing to one. Multiplying a row by 1−γ1-\gamma gives a probability distribution. It is equivalent to observing the state at an independent time KK with P(K=k)=(1−γ)γk\Pr(K=k)=(1-\gamma)\gamma^k; 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.

[ ]Tabular MDP: gridworld and inventoryBrowser
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

ProofA first step from Q
Prove: Derive the Bellman evaluation equation for Q under a stationary policy.
0
A finite MDP has dynamics P(s',r|s,a), bounded rewards and discount 0≤γ<1. The first action is fixed to a; from the next state actions are chosen according to π. Define Qπ(s,a) as the expected discounted return from that pair.

Step 1 of 3. How do you separate the first term of return?

ProofThe inverse counts visits
Prove: Prove invertibility and normalization of discounted occupancy.
0
Pπ is a finite stochastic transition matrix and 0≤γ<1. Use the matrix infinity norm, the maximum absolute row sum.

Step 1 of 3. Why does the matrix geometric series converge?

NumericValues in three states
A fixed policy induces the chain 0→1→2→2. The first two transitions reward 1 and 2; in absorbing state 2 the reward is 0. With γ=0,5 (decimal comma), what is Vπ(0)?
QuizWhat is missing from the state
In a warehouse tomorrow’s demand depends on the day of the week, and only current inventory is observed as state. What change is sufficient for demand’s distribution to depend on the state, if its law depends only on that day?
QuizA finite horizon
A task terminates after exactly ten steps. The same physical position occurs after two and nine steps. Which state makes the dynamics with termination depend only on state and action?
QuizA robot’s position
A robot has inertia: its next position depends on its position, velocity and control. Is position enough as state?
QuizA hidden illness
The true severity of an illness persists and affects future observations, but only a noisy test is observed. Which representation can preserve available information for decisions?
QuizA service queue
In a queue, the next departure depends on elapsed time in the current service because remaining duration is not memoryless. What happens if the state counts only people?
CodeSolve for V and Q
Implement evaluate_policy(P,R,pi,gamma). P has shape (S,A,S), S,A>0, with finite nonnegative stochastic rows; R has shape (S,A) and finite expected rewards; pi has shape (S,A) and finite nonnegative distribution rows. gamma is a finite real number 0≤gamma<1, excluding booleans. Return V with shape (S,) and Q with shape (S,A), evaluating the stationary policy: Pπ=Σa pi·P, rπ=Σa pi·R, V=(I−gamma Pπ)⁻¹rπ and Q=R+gamma Σs' P·V. Reject invalid shapes or probabilities with ValueError and do not modify inputs. Each row must sum to one with absolute tolerance 10⁻¹²; normalize accepted rows in copies before evaluation. If the normalized system remains singular or produces nonfinite float64 values, you may raise ValueError.
import numpy as np

def evaluate_policy(P,R,pi,gamma):
  pass
Shift+Enter to run
[ ]Comprobar valores de la cadenaBrowser
gamma=.5
v2=0.0
v1=2+gamma*v2
v0=1+gamma*v1
print('Vπ(0), Vπ(1), Vπ(2):',v0,v1,v2)