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 , actions , transition probabilities , rewards and a discount factor that makes future rewards worth less than immediate ones. A policy picks an action in each state; once fixed, the MDP becomes a Markov chain with rewards. The value of a state under is the expected discounted sum of rewards:
The Bellman equations
Conditioning on the first step gives a linear system for the value of a fixed policy:
and the optimal value function satisfies the Bellman optimality equation
Value iteration starts from and applies the right-hand side repeatedly. Because , each sweep shrinks the error by a factor , so it converges to ; 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).
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: , so , the same kind of inverse as the fundamental matrix. Comparing policies by solving these systems is policy iteration.
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 and are unknown, reinforcement learning estimates values from experience. Q-learning updates after each observed transition; with enough exploration it converges to the optimal . 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 . What is its value?
Answer
Solution
, so , the geometric series .
Exercise 2: Discounting
Why must be below 1 for an infinite-horizon problem with constant rewards?
Answer
Otherwise the sum of rewards is infinite.
Solution
With , diverges for any , 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 directly in the update.
Answer
The learned greedy policy matches the value-iteration policy.
Solution
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?
- The value of a state is the best immediate reward plus the discounted value of where it leads
- Rewards are independent
- The policy is random
- Transition matrices are symmetric
For a fixed policy, the value function solves…
- a nonlinear optimisation
- a linear system
- an eigenvalue problem
- a differential equation