Markov Decision Processes
Chapter Seventy-Nine
Syllabus topic Module 2, "Markov Decision Processes"
Pages 505 to 513 of 591
In one line
A Markov decision process is the formal statement of a reinforcement learning problem: states, actions, a transition model, a reward and a discount.
The Reinforcement Learning Framework described the setting in words. This chapter writes it down, and being able to write it down is what makes the next chapter's equations possible.
The five parts
A paper asking "define an MDP" wants exactly these, with the Markov property stated.
S | the set of states | |
A | the set of actions | |
P | the transition model, P(s' given s, a) | the probability of landing in s' |
R | the reward | attached to a state, or to a transition |
gamma | the discount factor | between 0 and 1 |
Note what is not in the list: any mention of time, of history, or of how the agent got to a state.
The measurement
# A Markov decision process written out in full: the five parts, the transition
# model checked, and three fixed policies EVALUATED so that the difference
# between judging a policy and finding one is visible.
COLS, ROWS = 4, 3
WALL = (1, 1)
TERMINAL = {(3, 2): 1.0, (3, 1): -1.0}
START = (0, 0)
LIVING = -0.04 # the reward for being in any non-terminal square
GAMMA = 1.0
ACTIONS = ["N", "S", "E", "W"]
MOVE = {"N": (0, 1), "S": (0, -1), "E": (1, 0), "W": (-1, 0)}
# A slip sends the agent at right angles to the way it meant to go.
SIDEWAYS = {"N": ("W", "E"), "S": ("E", "W"), "E": ("N", "S"), "W": ("S", "N")}
P_INTENDED, P_SLIP = 0.8, 0.1
STATES = [(c, r) for r in range(ROWS) for c in range(COLS) if (c, r) != WALL]
def legal(s):
c, r = s
return 0 <= c < COLS and 0 <= r < ROWS and (c, r) != WALL
def move(s, a):
"""Walking into a wall or off the edge leaves the agent where it was."""
d = MOVE[a]
t = (s[0] + d[0], s[1] + d[1])
return t if legal(t) else s
def transitions(s, a):
"""P(s' | s, a) as a list of (probability, next state)."""
left, right = SIDEWAYS[a]
out = {}
for p, act in ((P_INTENDED, a), (P_SLIP, left), (P_SLIP, right)):
t = move(s, act)
out[t] = out.get(t, 0.0) + p
return [(p, t) for t, p in sorted(out.items())]
def reward(s):
return TERMINAL[s] if s in TERMINAL else LIVING
def draw(grid, fmt="%6s"):
for r in range(ROWS - 1, -1, -1):
line = " "
for c in range(COLS):
line += fmt % ("#" if (c, r) == WALL else grid.get((c, r), "."))
print(line.rstrip())
print("A MARKOV DECISION PROCESS HAS FIVE PARTS.")
print(" S the set of states")
print(" A the set of actions")
print(" P the transition model, P(s' | s, a)")
print(" R the reward")
print(" gamma the discount factor")
print()
print("THE GRID. the robot starts at the bottom left and is trying to reach the")
print("+1 square. # is a pillar it cannot enter.")
labels = {t: "%+.0f" % v for t, v in TERMINAL.items()}
labels[START] = "start"
draw(labels)
print()
print(" S: %d squares, two of them terminal." % len(STATES))
print(" A: %s. gamma = %.2f. reward %.2f in every non-terminal square,"
% (", ".join(ACTIONS), GAMMA, LIVING))
print(" %+.0f and %+.0f in the two terminal ones."
% (TERMINAL[(3, 2)], TERMINAL[(3, 1)]))
print()
print(" P: THE FLOOR IS SLIPPERY. an action goes the intended way with")
print(" probability %.1f and at right angles with probability %.1f each."
% (P_INTENDED, P_SLIP))
print(" walking into the pillar or off the edge leaves the robot where it was.")
print()
print(" one state and action written out in full, from %s going N:" % str((0, 0)))
for p, t in transitions((0, 0), "N"):
why = "intended" if t == (0, 1) else ("blocked, stays put" if t == (0, 0) else "slipped")
print(" P(%s | %s, N) = %.1f (%s)" % (str(t), str((0, 0)), p, why))
print(" and from %s going N, where the pillar is above:" % str((1, 0)))
for p, t in transitions((1, 0), "N"):
why = "blocked by the pillar, stays put" if t == (1, 0) else "slipped"
print(" P(%s | %s, N) = %.1f (%s)" % (str(t), str((1, 0)), p, why))
print()
bad = 0
for s in STATES:
if s in TERMINAL:
continue
for a in ACTIONS:
tot = sum(p for p, _ in transitions(s, a))
if abs(tot - 1.0) > 1e-12:
bad += 1
print(" CHECKED: for all %d non-terminal states and %d actions the transition"
% (len(STATES) - len(TERMINAL), len(ACTIONS)))
print(" probabilities sum to 1. violations: %d." % bad)
print()
print("THE MARKOV PROPERTY, which is what the M stands for.")
print(" P(s' | s, a) depends on the CURRENT state and action only. how the")
print(" robot reached (2,1) does not change what happens next from (2,1).")
print(" THAT IS AN ASSUMPTION ABOUT THE PROBLEM, and it is what lets a policy")
print(" be a function of the state alone rather than of the whole history.")
print()
print("A POLICY maps each state to an action. for an MDP with a fixed discount")
print("an optimal policy can always be taken to be")
print(" DETERMINISTIC: no need to randomise, since one action is at least as")
print(" good as any mixture of actions.")
print(" STATIONARY: the same in a state whenever it is visited, since the")
print(" future from a state does not depend on the time of arrival.")
print(" so the search is over %d**%d = %d policies, which is finite and far"
% (len(ACTIONS), len(STATES) - len(TERMINAL),
len(ACTIONS) ** (len(STATES) - len(TERMINAL))))
print(" too many to try one at a time.")
print()
def evaluate(policy, tol=1e-10):
"""POLICY EVALUATION: the value of every state UNDER A GIVEN POLICY.
V(s) = R(s) + gamma * sum over s' of P(s' | s, policy(s)) * V(s')"""
V = {s: 0.0 for s in STATES}
for s in TERMINAL:
V[s] = TERMINAL[s]
sweeps = 0
while True:
sweeps += 1
delta = 0.0
for s in STATES:
if s in TERMINAL:
continue
total = sum(p * V[t] for p, t in transitions(s, policy[s]))
new = reward(s) + GAMMA * total
delta = max(delta, abs(new - V[s]))
V[s] = new
if delta < tol:
return V, sweeps
def show_policy(policy):
g = dict(policy)
for t, v in TERMINAL.items():
g[t] = "%+.0f" % v
draw(g)
print("EVALUATING A FIXED POLICY. this is the PREDICTION problem: not 'what")
print("should the robot do' but 'how good is this particular rule'.")
print()
POLICIES = {
"always north": {s: "N" for s in STATES if s not in TERMINAL},
"always east": {s: "E" for s in STATES if s not in TERMINAL},
"along the bottom and up the right hand side": {
(0, 0): "E", (1, 0): "E", (2, 0): "E", (3, 0): "N",
(0, 1): "N", (2, 1): "N",
(0, 2): "E", (1, 2): "E", (2, 2): "E"},
"up the left hand side and along the top": {
(0, 0): "N", (1, 0): "E", (2, 0): "N", (3, 0): "W",
(0, 1): "N", (2, 1): "N",
(0, 2): "E", (1, 2): "E", (2, 2): "E"},
}
for name, pol in POLICIES.items():
V, sweeps = evaluate(pol)
print(" %s" % name.upper())
show_policy(pol)
print(" its values:")
draw({s: "%+.3f" % V[s] for s in STATES}, fmt="%9s")
print(" value of the start square: %+.4f, after %d sweeps."
% (V[START], sweeps))
print()
print("READ THE FOUR START VALUES TOGETHER:")
for name, pol in POLICIES.items():
V, _ = evaluate(pol)
print(" %+.4f %s" % (V[START], name))
print()
v_north = evaluate(POLICIES["always north"])[0][START]
v_right = evaluate(POLICIES["along the bottom and up the right hand side"])[0][START]
v_top = evaluate(POLICIES["up the left hand side and along the top"])[0][START]
print(" 'always north' is worth %+.4f: the robot presses into the top wall and"
% v_north)
print(" reaches the goal only by slipping sideways along the top row.")
print(" 'always east' is worth %+.4f, because from the bottom right corner it"
% evaluate(POLICIES["always east"])[0][START])
print(" presses east into the edge and slips into the -1 square.")
print()
print(" AND THE TWO ROUTES THAT LOOK SENSIBLE ON THE MAP ARE %+.4f APART."
% (v_top - v_right))
print(" going right along the bottom and up the right hand side is the SHORTER")
print(" route, and it is worth %+.4f, because the only way up the right hand" % v_right)
print(" column passes through the -1 square. going up the left and along the")
print(" top is longer, costs more steps at %.2f each, and is worth %+.4f."
% (LIVING, v_top))
print(" THE SHORT ROUTE ON THE MAP IS THE BAD POLICY, and no amount of looking")
print(" at the grid says so. only the evaluation does.")
print()
print("NOTICE WHAT EVALUATION DOES NOT DO. it scores a policy that was handed to")
print("it; it never proposes one. finding the best policy is the CONTROL problem")
print("and it needs the next chapter's equations.")Markov Decision Processes
A MARKOV DECISION PROCESS HAS FIVE PARTS.
S the set of states
A the set of actions
P the transition model, P(s' | s, a)
R the reward
gamma the discount factor
THE GRID. the robot starts at the bottom left and is trying to reach the
+1 square. # is a pillar it cannot enter.
. . . +1
. # . -1
start . . .
S: 11 squares, two of them terminal.
A: N, S, E, W. gamma = 1.00. reward -0.04 in every non-terminal square,
+1 and -1 in the two terminal ones.
P: THE FLOOR IS SLIPPERY. an action goes the intended way with
probability 0.8 and at right angles with probability 0.1 each.
walking into the pillar or off the edge leaves the robot where it was.
one state and action written out in full, from (0, 0) going N:
P((0, 0) | (0, 0), N) = 0.1 (blocked, stays put)
P((0, 1) | (0, 0), N) = 0.8 (intended)
P((1, 0) | (0, 0), N) = 0.1 (slipped)
and from (1, 0) going N, where the pillar is above:
P((0, 0) | (1, 0), N) = 0.1 (slipped)
P((1, 0) | (1, 0), N) = 0.8 (blocked by the pillar, stays put)
P((2, 0) | (1, 0), N) = 0.1 (slipped)
CHECKED: for all 9 non-terminal states and 4 actions the transition
probabilities sum to 1. violations: 0.
THE MARKOV PROPERTY, which is what the M stands for.
P(s' | s, a) depends on the CURRENT state and action only. how the
robot reached (2,1) does not change what happens next from (2,1).
THAT IS AN ASSUMPTION ABOUT THE PROBLEM, and it is what lets a policy
be a function of the state alone rather than of the whole history.
A POLICY maps each state to an action. for an MDP with a fixed discount
an optimal policy can always be taken to be
DETERMINISTIC: no need to randomise, since one action is at least as
good as any mixture of actions.
STATIONARY: the same in a state whenever it is visited, since the
future from a state does not depend on the time of arrival.
so the search is over 4**9 = 262144 policies, which is finite and far
too many to try one at a time.
EVALUATING A FIXED POLICY. this is the PREDICTION problem: not 'what
should the robot do' but 'how good is this particular rule'.
ALWAYS NORTH
N N N +1
N # N -1
N N N N
its values:
-1.400 -1.000 -0.200 +1.000
-1.450 # -0.333 -1.000
-1.466 -1.196 -0.525 -0.992
value of the start square: -1.4662, after 910 sweeps.
ALWAYS EAST
E E E +1
E # E -1
E E E E
its values:
+0.500 +0.694 +0.744 +1.000
-0.648 # -0.905 -1.000
-1.396 -1.439 -1.389 -1.400
value of the start square: -1.3959, after 204 sweeps.
ALONG THE BOTTOM AND UP THE RIGHT HAND SIDE
E E E +1
N # N -1
E E E N
its values:
+0.812 +0.868 +0.918 +1.000
+0.762 # +0.660 -1.000
-0.794 -0.938 -0.888 -1.032
value of the start square: -0.7940, after 26 sweeps.
UP THE LEFT HAND SIDE AND ALONG THE TOP
E E E +1
N # N -1
N E N W
its values:
+0.812 +0.868 +0.918 +1.000
+0.762 # +0.660 -1.000
+0.691 +0.527 +0.577 +0.357
value of the start square: +0.6910, after 27 sweeps.
READ THE FOUR START VALUES TOGETHER:
-1.4662 always north
-1.3959 always east
-0.7940 along the bottom and up the right hand side
+0.6910 up the left hand side and along the top
'always north' is worth -1.4662: the robot presses into the top wall and
reaches the goal only by slipping sideways along the top row.
'always east' is worth -1.3959, because from the bottom right corner it
presses east into the edge and slips into the -1 square.
AND THE TWO ROUTES THAT LOOK SENSIBLE ON THE MAP ARE +1.4850 APART.
going right along the bottom and up the right hand side is the SHORTER
route, and it is worth -0.7940, because the only way up the right hand
column passes through the -1 square. going up the left and along the
top is longer, costs more steps at -0.04 each, and is worth +0.6910.
THE SHORT ROUTE ON THE MAP IS THE BAD POLICY, and no amount of looking
at the grid says so. only the evaluation does.
NOTICE WHAT EVALUATION DOES NOT DO. it scores a policy that was handed to
it; it never proposes one. finding the best policy is the CONTROL problem
and it needs the next chapter's equations.Markov Decision Processes
Reading the model
A four by three grid with a pillar, a +1 square and a -1 square, and a slippery floor: an action goes the intended way with probability 0.8 and at right angles with probability 0.1 each. Walking into the pillar or off the edge leaves the robot where it was.
Markov Decision Processes
Two transitions written out in full, and they are worth reading closely:
Markov Decision Processes
from (0,0) going N: P((0,1)) = 0.8 intended, P((1,0)) = 0.1 slipped, P((0,0)) = 0.1 blocked
from (1,0) going N: P((1,0)) = 0.8 blocked by the pillar, P((0,0)) = 0.1, P((2,0)) = 0.1
Markov Decision Processes
The second one is the case students forget: the most likely outcome of the intended action is to stay exactly where you are, because the pillar is in the way. A transition model must account for blocked moves, and if it does not, the probabilities stop summing to 1. The program checks that: for all 9 non-terminal states and 4 actions, 0 violations.
The Markov property
P(s' given s, a) depends on the current state and action only. How the robot reached a square does not change what happens next from it.
That is an assumption about the problem, not a property of the mathematics. It is what allows a policy to be a function of the state alone rather than of the entire history, and it is the same assumption Hidden Markov Models made about a chain of states.
When it fails, the usual repair is to enlarge the state until it holds: if what matters is the last two squares, make the state the pair of squares. That works and it multiplies the number of states.
What a policy is, and how many there are
A policy maps each state to an action. For an MDP with a fixed discount, an optimal policy can always be taken to be:
| Why | |
|---|---|
| deterministic | one action is at least as good as any mixture of actions, so nothing is gained by randomising |
| stationary | the future from a state does not depend on when the state was reached, so the best action there is always the same |
Both facts matter for the search. They reduce the problem to choosing one action per state, so the number of policies here is 49 = 262144. Finite, and far too many to try one at a time**, which is exactly why the next chapter exists.
Policy evaluation
The prediction problem: not "what should the robot do" but "how good is this particular rule". One equation, applied repeatedly until it stops changing:
V(s) = R(s) + gamma sum over s' of P(s' given s, policy(s)) V(s')
Read it as a sentence: the value of a state is its own reward plus the discounted average value of where the policy takes you. The terminal states keep their own values and are never updated.
Markov Decision Processes
The four policies
| Policy | Value of the start square | Sweeps |
|---|---|---|
| always north | -1.4662 | 910 |
| always east | -1.3959 | 204 |
| along the bottom and up the right hand side | -0.7940 | 26 |
| up the left hand side and along the top | +0.6910 | 27 |
Always north presses into the top wall and reaches the goal only by slipping sideways along the top row, which takes a great many steps at -0.04 each, and it needs 910 sweeps to settle, because the values propagate slowly through a policy that mostly stands still.
Always east is worse than it looks: from the bottom right corner it presses east into the edge and slips into the -1 square.
And now the measurement that matters. The two routes that look sensible on the map are 1.4850 apart.
| Right along the bottom, then up the right hand column | -0.7940 |
| Up the left hand column, then along the top | +0.6910 |
The shorter route is the bad one, because the only way up the right hand column passes through the -1 square. The longer route costs more steps at -0.04 each and is worth nearly one and a half more.
Nothing about the picture says so. A person looking at the grid sees a short path and a long path. Only the evaluation distinguishes them, and that is the argument for having the machinery at all.
Prediction and control
The distinction to state in an answer.
| Prediction | Control | |
|---|---|---|
| Question | how good is this policy | what is the best policy |
| Input | a policy | none |
| Method | policy evaluation | value iteration, policy iteration, Q-learning |
| Chapter | this one | the next two |
Policy evaluation never proposes a policy. It scores one handed to it. Turning it into a search is the whole content of The Bellman Equations, Value Iteration and Policy Iteration.
What the model is, and when you have it
An MDP as written here assumes P and R are known. That is a strong assumption and it divides the subject.
| Model-based | Model-free | |
|---|---|---|
P and R | known, or learned | never needed |
| Method | value iteration, policy iteration | Q-learning, SARSA |
| Needs | a description of the world | only experience of it |
| This chapter and the next | yes | Q-Learning |
For the grid, the slip probabilities were given. For a real robot on a real floor they are not, and either they are estimated by counting, which is Learning With Complete Data again, or the model is done away with entirely.
Distinctions
| Reward | Value | |
|---|---|---|
| Of | a state, immediately | a state, under a policy |
| Here | -0.04 everywhere | -1.4662 to +0.6910 at the start square |
| Depends on the policy | no | yes |
Markov Decision Processes
| A search problem | An MDP | |
|---|---|---|
| Actions | deterministic | stochastic |
| Answer | a sequence of actions | a policy, an action for every state |
| Why | the plan cannot go wrong | the robot may end up anywhere, so it needs an answer everywhere |
| Stationary | Deterministic | |
|---|---|---|
| Means | the same action in a state whenever visited | no randomising between actions |
| Because | the future does not depend on the time of arrival | one action is at least as good as any mixture |
What it does not mean
An MDP is not a search problem. Its answer is a policy, not a route, because the actions can go wrong.
The Markov property is not automatic. It is an assumption, repaired by enlarging the state.
A transition model is not complete without blocked moves. From one square here the most likely outcome of going north is staying put.
The shorter route is not the better policy. It is worth -0.7940 against +0.6910.
Policy evaluation does not find a policy. It scores one.
Knowing the MDP is not the usual case. Model-free methods exist because P is usually unknown.
Quick revision
- An MDP is
S,A,P(s' given s, a),R,gamma. No time and no history appear in it. - The Markov property: the next state depends on the current state and action only. It is an assumption, repaired by enlarging the state.
- A transition model must handle blocked moves: from
(1,0)going north,P(stay) = 0.8. Checked here: 9 states, 4 actions, 0 violations. - An optimal policy can be taken to be deterministic and stationary, so the search is over
4**9 = 262144policies: finite, and far too many to enumerate. - Policy evaluation:
V(s) = R(s) + gamma sum of P(s' given s, policy(s)) V(s'), applied until it stops changing. - Measured start values: always north -1.4662 (910 sweeps), always east -1.3959, bottom and right -0.7940, left and top +0.6910.
- The shorter route is worth 1.4850 less, because the only way up the right hand column passes the
-1square. The map does not show this; the evaluation does. - Prediction is scoring a policy; control is finding one. Evaluation does only the first.
- Model-based methods need
PandR; model-free methods, such as Q-learning, do not.
Test yourself
1. Define a Markov decision process. A set of states, a set of actions, a transition model giving the probability of each next state from a state and action, a reward, and a discount factor. Nothing in the definition refers to time or to the history of how a state was reached.
2. State the Markov property and say what it buys. The probability of the next state depends only on the current state and the action taken, not on any earlier state. It allows a policy to be a function of the state alone rather than of the whole history, which is what makes the problem finite.
Markov Decision Processes
3. Why must a transition model account for blocked moves? Because an action that would take the agent into an obstacle or off the edge must lead somewhere, and leaving it out makes the probabilities fail to sum to one. In this grid, going north from the square below the pillar leaves the robot where it is with probability 0.8, so the most likely outcome of the intended action is no movement at all.
4. Why is the answer to an MDP a policy rather than a sequence of actions? Because the actions are stochastic. A planned sequence assumes each action has its intended effect; here an action goes sideways one time in five, so the agent can find itself in a square its plan never anticipated and needs an answer for every state.
5. Write the policy evaluation equation and say what it computes. V(s) equals the reward of s plus gamma times the sum over next states of the probability of reaching them under the policy's action, each multiplied by its own value. Applied repeatedly until the values stop changing, it gives the expected discounted return from every state under that fixed policy. It is the prediction problem.
6. In the measurement, the shorter route scored -0.7940 and the longer one +0.6910. Explain. The only way up the right hand column passes through the -1 square, so the short route's final step risks the penalty and frequently incurs it. The long route up the left hand side and along the top pays an extra -0.04 for each additional step but never passes beside the penalty, and it is worth 1.4850 more. The grid drawing gives no hint of this; only evaluating the two policies does.
7. Distinguish prediction from control, and model-based from model-free. Prediction asks how good a given policy is and is answered by policy evaluation; control asks which policy is best and needs value iteration, policy iteration or a learning method. Model-based methods assume the transition model and reward are known, or learn them; model-free methods such as Q-learning never form a model and work from experience alone.
The rest of this subject
These notes are cut from the University's printed syllabus. Open the syllabus itself, or the past papers, for the same subject.