Lesson 2 of 12 · Foundations
Markov Decision Processes
Markov decision processes explained: states, actions, transition probabilities, rewards, γ and the Markov property, with a small MDP simulated in NumPy.
- 16 min read
- Advanced
- Reviewed
- Describe an MDP by its states, actions, transition probabilities, rewards and discount factor
- Write a small MDP as NumPy arrays and simulate it
- Explain the Markov property, and repair a state that breaks it
- Tell deterministic from stochastic policies, and episodic from continuing tasks
- Compare policies by their average discounted return
The idea in plain words
In the corridor from Agents, Environments and Rewards, every action had a certain result: "right" always moved one cell right. Real actions are less reliable. A robot's wheel slips on a wet floor, a recommended video may or may not be watched, a machine may or may not survive another day of work. A Markov decision process (MDP) is the standard way to write down such a problem exactly: which situations can occur, which actions are possible, how likely each outcome is, and what each step is worth.
The MDP is the common language of reinforcement learning. Every method in the rest of this course, from value iteration to Q-learning and policy gradients, is a way of finding a good policy for an MDP. Some methods need the MDP written out in full; others only need to try actions in it and watch what happens.
The five parts of an MDP
S states the situations the agent can be in
A actions the choices it can make
P transition probabilities P(s′ | s, a): the chance of landing in state s′ after action a in state s
R rewards R(s, a): the reward for taking action a in state s
γ discount factor how much a reward one step later is worth, between 0 and 1This lesson's example is a factory machine. Each morning the operator, our agent, checks its condition (the state: new, worn or broken) and chooses to run it for the day or to repair it. Running earns money while the machine wears out; a repair costs money but makes it as good as new:
| State | Action | Reward | The next morning |
|---|---|---|---|
| new | run | +10 | new 70%, worn 30% |
| worn | run | +6 | worn 60%, broken 40% |
| broken | run | 0 | broken 100% |
| any | repair | −10, or −20 if broken | new 100% |
Each row's chances add up to 100%, because something must happen. The outcomes are random, but not arbitrary: running a worn machine is a gamble with known odds.
An MDP in NumPy
Two arrays hold the whole MDP: P[s, a] is a list of chances for the next state, and R[s, a] is a reward. Simulating it needs one key line: each day the agent chooses an action, and the environment "rolls the dice" for the next state with rng.choice:
import numpy as np
STATES, ACTIONS = ["new", "worn", "broken"], ["run", "repair"]
# P[s, a, s2]: the chance of moving to state s2 after taking action a in state s
P = np.zeros((3, 2, 3))
P[0, 0] = [0.7, 0.3, 0.0] # run a new machine: it may wear
P[1, 0] = [0.0, 0.6, 0.4] # run a worn machine: it may break
P[2, 0] = [0.0, 0.0, 1.0] # run a broken machine: it stays broken
P[:, 1] = [1.0, 0.0, 0.0] # repair, from any state: as good as new
# R[s, a]: the reward for taking action a in state s
R = np.array([[10.0, -10.0],
[6.0, -10.0],
[0.0, -20.0]])
print("every row of P sums to 1:", np.allclose(P.sum(axis=2), 1))
# Simulate 10 days with the policy "repair only when broken"
policy = [0, 0, 1] # the action for each state: run, run, repair
rng = np.random.RandomState(0)
state, total = 0, 0.0
for day in range(1, 11):
action = policy[state]
reward = R[state, action]
next_state = rng.choice(3, p=P[state, action]) # the environment rolls the dice
print(f"day {day:>2}: {STATES[state]:<6} -> {ACTIONS[action]:<6} reward {reward:+5.0f} -> {STATES[next_state]}")
state, total = next_state, total + reward
print("total reward over 10 days:", total)every row of P sums to 1: True day 1: new -> run reward +10 -> new day 2: new -> run reward +10 -> worn day 3: worn -> run reward +6 -> broken day 4: broken -> repair reward -20 -> new day 5: new -> run reward +10 -> new day 6: new -> run reward +10 -> new day 7: new -> run reward +10 -> new day 8: new -> run reward +10 -> worn day 9: worn -> run reward +6 -> broken day 10: broken -> repair reward -20 -> new total reward over 10 days: 32.0
The agent controls only the action; the environment decides what happens next. Here the machine broke down twice, and the two rebuilds, at 20 points each, ate more than half of the 72 points it earned. Was waiting for breakdowns a good policy? Comparing policies is coming up, but first, the assumption hiding in the word "Markov".
The Markov property
In symbols, P(sₜ₊₁ | sₜ, aₜ) tells you everything: knowing sₜ₋₁, sₜ₋₂ and the rest of the past adds nothing. A chess position works this way: to choose the best move you need the board, not the list of moves that produced it (plus a few extras, such as whether castling is still allowed, which chess programs add to the state). A photo of a flying ball does not: from its position alone you can't tell where it goes next, but its position and velocity together are enough.
Whether a problem is Markov depends on what you put in the state. The program below runs the machine for 20,000 days and checks whether yesterday's condition changes the chance of a breakdown tomorrow, first with the full state, then with a cheap sensor that only reports "working" or "broken":
import numpy as np
P = np.zeros((3, 2, 3))
P[0, 0] = [0.7, 0.3, 0.0]
P[1, 0] = [0.0, 0.6, 0.4]
P[2, 0] = [0.0, 0.0, 1.0]
P[:, 1] = [1.0, 0.0, 0.0]
policy = [0, 0, 1] # repair only when broken
rng = np.random.RandomState(0)
states = [0]
for day in range(20000): # one long run of the machine
s = states[-1]
states.append(rng.choice(3, p=P[s, policy[s]]))
states = np.array(states)
yesterday, today, tomorrow = states[:-2], states[1:-1], states[2:]
def p_break(rows):
"""How often the machine was broken tomorrow, on the days selected by rows."""
return np.mean(tomorrow[rows] == 2)
print("Full state (new, worn, broken): does yesterday matter?")
print(f" worn today, new yesterday: {p_break((today == 1) & (yesterday == 0)):.2f}")
print(f" worn today, worn yesterday: {p_break((today == 1) & (yesterday == 1)):.2f}")
print("A sensor that only says working or broken:")
print(f" working today, broken yesterday: {p_break((today < 2) & (yesterday == 2)):.2f}")
print(f" working today, working yesterday: {p_break((today < 2) & (yesterday < 2)):.2f}")Full state (new, worn, broken): does yesterday matter? worn today, new yesterday: 0.39 worn today, worn yesterday: 0.39 A sensor that only says working or broken: working today, broken yesterday: 0.00 working today, working yesterday: 0.20
With the full state, yesterday makes no difference: a worn machine breaks about 40% of the time, however it got worn. With the cheap sensor, history matters a lot. A machine that was broken yesterday has just been rebuilt, so it can't break today (0.00), while one that has been working for a while may be worn (0.20). "Working" is not a Markov state, so an agent that sees only "working" would be choosing with missing information. The fix is to put what matters into the state: the wear level, the days since the last repair, or the last few sensor readings. DeepMind's Atari player did exactly this, using the last four video frames as its state, because one frame shows where the ball is but not where it's going. When the true state can never be observed, the problem is a partially observable MDP (POMDP), which is harder to solve.
Deterministic and stochastic policies
A deterministic policy always picks the same action in a state: π(s) = a. In code it is a list with one action per state, like [0, 0, 1] above. A stochastic policy gives each action a probability: π(a | s). In code it is a table with one row per state, and every row adds up to 1:
"repair when worn" (deterministic) "worn: toss a coin" (stochastic)
P(run) P(repair) P(run) P(repair)
new 1.0 0.0 new 1.0 0.0
worn 0.0 1.0 worn 0.5 0.5
broken 0.0 1.0 broken 0.0 1.0A deterministic policy is just a stochastic one whose probabilities are all 0 or 1. Stochastic policies matter for three reasons: an agent that sometimes tries other actions keeps learning about them (the next lesson), an opponent can't predict and exploit you (any fixed choice in rock-paper-scissors loses to the right counter), and the policy-gradient methods later in this course learn smooth probabilities rather than hard choices.
Comparing policies by simulation
A policy's quality is its expected discounted return. Without a formula for it yet, simulation can estimate it: run the machine from new many times and average. The program runs each policy 300 times for 60 days with γ = 0.9. After 60 days, γ⁶⁰ ≈ 0.002, so later days barely count:
import numpy as np
# The machine MDP: states 0 new, 1 worn, 2 broken; actions 0 run, 1 repair
P = np.zeros((3, 2, 3)) # P[s, a, s2] = chance of s2 after action a in state s
P[0, 0] = [0.7, 0.3, 0.0] # run a new machine: it may wear
P[1, 0] = [0.0, 0.6, 0.4] # run a worn machine: it may break
P[2, 0] = [0.0, 0.0, 1.0] # a broken machine stays broken
P[:, 1] = [1.0, 0.0, 0.0] # repair: as good as new
R = np.array([[10.0, -10.0], # R[s, a]: new: run earns 10, repair costs 10
[6.0, -10.0], # worn: run earns 6
[0.0, -20.0]]) # broken: run earns nothing, repair costs 20
def discounted_return(pi, rng, days=60, gamma=0.9):
"""Run the machine for 60 days from new, choosing actions with policy pi."""
state, G = 0, 0.0
for t in range(days):
action = rng.choice(2, p=pi[state])
G += gamma ** t * R[state, action]
state = rng.choice(3, p=P[state, action])
return G
policies = { # rows: new, worn, broken; columns: P(run), P(repair)
"never repair": np.array([[1, 0], [1, 0], [1, 0]], dtype=float),
"repair when broken": np.array([[1, 0], [1, 0], [0, 1]], dtype=float),
"repair when worn": np.array([[1, 0], [0, 1], [0, 1]], dtype=float),
"worn: toss a coin": np.array([[1, 0], [0.5, 0.5], [0, 1]]),
}
rng = np.random.RandomState(11)
for name, pi in policies.items():
returns = [discounted_return(pi, rng) for _ in range(300)]
std_error = np.std(returns) / np.sqrt(len(returns))
print(f"{name:<19} average discounted return {np.mean(returns):5.1f} ± {std_error:.1f}")never repair average discounted return 36.3 ± 0.9 repair when broken average discounted return 51.9 ± 0.8 repair when worn average discounted return 58.1 ± 0.8 worn: toss a coin average discounted return 55.1 ± 0.8
Never repairing is worst: sooner or later the machine breaks and earns nothing, forever. Preventive maintenance, repairing as soon as the machine is worn, beats waiting for a breakdown, because a worn machine earns only 6 a day and risks a rebuild that costs 20, while a service costs 10 and brings back a machine that earns 10. The coin toss lands in between the two policies it mixes. The ± is the standard error: these are averages of random runs, so another seed would move each one by roughly that much. Value Functions computes the exact values, with no simulation at all.
Episodic and continuing tasks
An episodic task ends: the corridor ends at the coin or the treasure, and a game ends in a win or a loss. Each episode's return is a finite sum, so even γ = 1 works, as long as every episode is certain to end. A continuing task never ends: the machine runs day after day, and so do a thermostat, a trading system and a recommender. Without discounting, the return of any decent policy is an infinite sum, and infinities can't be compared. Discounting keeps it finite:
a reward of 10 every day, forever, with γ = 0.9:
10 + 0.9 × 10 + 0.9² × 10 + 0.9³ × 10 + … = 10 ÷ (1 − 0.9) = 100
in general, if no reward is bigger than r_max:
return ≤ r_max ÷ (1 − γ)One trick lets the same code handle both kinds. Write each end of an episodic task as an absorbing state that leads back to itself with probability 1 and reward 0. Once there, nothing more can be earned, so the infinite sum stops growing exactly where the episode ended. In the corridor, cells 0 and 6 would become absorbing states.
Common mistakes
Practice
Once the policy is fixed, the MDP becomes a simpler process with a single transition matrix, P_pi: row s holds the chances of tomorrow's state when today's is s. Build P_pi for the policy "repair only when broken", then follow a new machine's chances of being new, worn or broken. Print them after 1, 2, 3 and 30 days. (After 30 days, the chances have settled: they are the share of days the machine spends in each condition in the long run.)
import numpy as np P = np.zeros((3, 2, 3)) P[0, 0] = [0.7, 0.3, 0.0] P[1, 0] = [0.0, 0.6, 0.4] P[2, 0] = [0.0, 0.0, 1.0] P[:, 1] = [1.0, 0.0, 0.0] policy = [0, 0, 1] # run, run, repair: repair only when broken # 1. Build P_pi: a 3 x 3 array whose row s is P[s, policy[s]] P_pi = np.zeros((3, 3)) # 2. d holds the chance of each state today. A new machine: certainly "new". # Each day, d = d @ P_pi gives tomorrow's chances. # Print them after 1, 2, 3 and 30 days, like: # day 1: new 0.700, worn 0.300, broken 0.000 d = np.array([1.0, 0.0, 0.0])
A robot's state is just its position on a line, but where it ends up next also depends on how fast it is moving. What is wrong, and what is the fix?
Summary
- An MDP describes a problem by its states S, actions A, transition probabilities P(s′ | s, a), rewards R(s, a) and discount factor γ. In NumPy it is two arrays, and
rng.choice(n, p=P[s, a])simulates a step. - The Markov property: the next state depends only on the current state and action. If it doesn't hold, add the missing information to the state.
- A deterministic policy picks one action per state; a stochastic policy gives each action a probability.
- Episodic tasks end; continuing tasks don't, and need γ < 1 to keep returns finite: at most r_max ÷ (1 − γ).
- With the policy fixed, simulating many runs and averaging estimates its expected discounted return.
Next: Exploration vs Exploitation.
Finished reading? Tick it off to track your progress.