TExcelTAD
Home › Probability Theory › Markov Decision Processes

Markov Decision Processes

A Markov chain moves on its own. In a Markov decision process (MDP), an agent chooses an action in each state, the action determines the transition probabilities, and each step earns a reward. MDPs are the mathematical model of reinforcement learning: robots, game-playing agents, recommendation policies and inventory control all fit the framework.

The model

An MDP has states SS, actions AA, transition probabilities P(s′∣s,a)P(s' \mid s, a), rewards R(s,a)R(s, a) and a discount factor γ∈[0,1)\gamma \in [0, 1) that makes future rewards worth less than immediate ones. A policy π\pi picks an action in each state; once fixed, the MDP becomes a Markov chain with rewards. The value of a state under π\pi is the expected discounted sum of rewards:

Vπ(s)=E[∑t=0∞γtR(st,at) | s0=s]V^\pi(s) = E\left[\sum_{t=0}^{\infty} \gamma^t R(s_t, a_t) \,\middle|\, s_0 = s\right]

The Bellman equations

Conditioning on the first step gives a linear system for the value of a fixed policy:

Vπ(s)=R(s,π(s))+γ∑s′P(s′∣s,π(s)) Vπ(s′)V^\pi(s) = R(s, \pi(s)) + \gamma \sum_{s'} P(s' \mid s, \pi(s))\, V^\pi(s')

and the optimal value function satisfies the Bellman optimality equation

V∗(s)=max⁡a[R(s,a)+γ∑s′P(s′∣s,a) V∗(s′)]V^*(s) = \max_a \left[ R(s, a) + \gamma \sum_{s'} P(s' \mid s, a)\, V^*(s') \right]

Value iteration starts from V=0V = 0 and applies the right-hand side repeatedly. Because γ<1\gamma < 1, each sweep shrinks the error by a factor γ\gamma, so it converges to V∗V^*; the best action in each state then gives an optimal policy.

Example: maintaining a machine

A machine is Good, Worn or Broken. Each day you either run it (earning money, but it wears) or repair it (costs money, restores it).

python · try it yourself
import numpy as np

states = ["good", "worn", "broken"]
actions = ["run", "repair"]
# P[a][s] = distribution of next state
P = {"run":    np.array([[0.7, 0.3, 0.0],
                         [0.0, 0.6, 0.4],
                         [0.0, 0.0, 1.0]]),
     "repair": np.array([[1.0, 0.0, 0.0],
                         [1.0, 0.0, 0.0],
                         [1.0, 0.0, 0.0]])}
R = {"run": np.array([10.0, 6.0, 0.0]), "repair": np.array([-2.0, -5.0, -15.0])}
gamma = 0.9

V = np.zeros(3)
for sweep in range(500):
    Q = {a: R[a] + gamma * P[a] @ V for a in actions}
    V_new = np.maximum(Q["run"], Q["repair"])
    if np.max(np.abs(V_new - V)) < 1e-9:
        break
    V = V_new
policy = ["run" if Q["run"][i] >= Q["repair"][i] else "repair" for i in range(3)]
print("converged after", sweep, "sweeps")
print("optimal values:", dict(zip(states, np.round(V, 2).tolist())))
print("optimal policy:", dict(zip(states, policy)))
converged after 214 sweeps
optimal values: {'good': 68.11, 'worn': 56.3, 'broken': 46.3}
optimal policy: {'good': 'run', 'worn': 'repair', 'broken': 'repair'}

Evaluating a policy exactly

For a fixed policy, the Bellman equation is linear: V=Rπ+γPπVV = R_\pi + \gamma P_\pi V, so V=(I−γPπ)−1RπV = (I - \gamma P_\pi)^{-1}R_\pi, the same kind of inverse as the fundamental matrix. Comparing policies by solving these systems is policy iteration.

python · try it yourself
import numpy as np

P_run = np.array([[0.7, 0.3, 0.0], [0.0, 0.6, 0.4], [0.0, 0.0, 1.0]])
P_rep = np.array([[1.0, 0.0, 0.0]] * 3)
R_run, R_rep = np.array([10.0, 6.0, 0.0]), np.array([-2.0, -5.0, -15.0])
gamma = 0.9

def evaluate(policy):
    Pp = np.array([P_run[i] if a == "run" else P_rep[i] for i, a in enumerate(policy)])
    Rp = np.array([R_run[i] if a == "run" else R_rep[i] for i, a in enumerate(policy)])
    return np.linalg.solve(np.eye(3) - gamma * Pp, Rp)

for policy in [("run", "run", "repair"), ("run", "repair", "repair"), ("run", "run", "run")]:
    print(policy, np.round(evaluate(policy), 2).tolist())
('run', 'run', 'repair') [57.57, 41.85, 36.81]
('run', 'repair', 'repair') [68.11, 56.3, 46.3]
('run', 'run', 'run') [36.55, 13.04, 0.0]

Never repairing is terrible: the machine eventually breaks and earns nothing forever. Whether to repair a worn machine early or run it until it breaks depends on the numbers; here repairing a worn machine early is clearly better, as the value functions show.

From MDPs to reinforcement learning

When PP and RR are unknown, reinforcement learning estimates values from experience. Q-learning updates Q(s,a)←Q(s,a)+α[r+γmax⁡a′Q(s′,a′)−Q(s,a)]Q(s, a) \leftarrow Q(s, a) + \alpha\left[r + \gamma\max_{a'}Q(s', a') - Q(s, a)\right] after each observed transition; with enough exploration it converges to the optimal QQ. Deep RL replaces the table by a neural network.

In software

MDPs drive inventory and pricing systems, adaptive bitrate streaming, robot control, game AI (Game AI) and recommendation policies that optimise long-term engagement. The fine-tuning of language models with reinforcement learning treats text generation as an MDP whose actions are tokens (Sampling from Language Models).

Go further: Reinforcement Learning in ML Foundations plays a multi-armed bandit and learns a grid-world policy with Q-learning.

Exercises

Exercise 1: A one-state MDP

A single state pays reward 1 forever with γ=0.9\gamma = 0.9. What is its value?

Answer
Solution

V=1+0.9VV = 1 + 0.9V, so V=1/(1−0.9)=10V = 1/(1 - 0.9) = 10, the geometric series ∑0.9t\sum 0.9^t.

Exercise 2: Discounting

Why must γ\gamma be below 1 for an infinite-horizon problem with constant rewards?

Answer

Otherwise the sum of rewards is infinite.

Solution

With γ=1\gamma = 1, ∑tr\sum_t r diverges for any r≠0r \ne 0, so values are not defined. Discounting also expresses that rewards now are worth more than rewards later, and it makes value iteration a contraction.

Exercise 3: Q-learning (code)

Learn the machine-maintenance policy by Q-learning from simulated transitions, without using PP directly in the update.

Answer

The learned greedy policy matches the value-iteration policy.

Solution
python · try it yourself
import random

rng = random.Random(7)
P = {"run": [[0.7, 0.3, 0.0], [0.0, 0.6, 0.4], [0.0, 0.0, 1.0]],
     "repair": [[1.0, 0.0, 0.0]] * 3}
R = {"run": [10.0, 6.0, 0.0], "repair": [-2.0, -5.0, -15.0]}
gamma, alpha, eps = 0.9, 0.05, 0.2
Q = {(s, a): 0.0 for s in range(3) for a in P}
s = 0
for step in range(200_000):
    if rng.random() < eps:
        a = rng.choice(["run", "repair"])
    else:
        a = max(P, key=lambda b: Q[(s, b)])
    s2 = rng.choices([0, 1, 2], weights=P[a][s])[0]
    target = R[a][s] + gamma * max(Q[(s2, b)] for b in P)
    Q[(s, a)] += alpha * (target - Q[(s, a)])
    s = s2
print({name: max(P, key=lambda b: Q[(i, b)]) for i, name in enumerate(["good", "worn", "broken"])})
{'good': 'run', 'worn': 'repair', 'broken': 'repair'}

Test yourself

What does the Bellman optimality equation express?

  1. The value of a state is the best immediate reward plus the discounted value of where it leads
  2. Rewards are independent
  3. The policy is random
  4. Transition matrices are symmetric

For a fixed policy, the value function solves…

  1. a nonlinear optimisation
  2. a linear system V=R+γPVV = R + \gamma P V
  3. an eigenvalue problem
  4. a differential equation