Simple Algorithm
Reinforcement Learning · Exploration · 17 min

Planning with a Model: Dynamic Programming

Computing the best behavior when the rules of the world are known.

Give an agent the complete rules of its world, what every action does and what it pays, and it no longer needs trial and error: it can work out the best behavior with pencil and paper. This lesson shows how, by computing what every situation is worth and then acting on those values. Richard Bellman called the idea dynamic programming, and every reinforcement learning algorithm you will meet later is an approximation of it.

What you’ll learn

  • Explain what a model of the world is, and why planning with a model needs no trial and error.
  • Evaluate a policy by repeatedly applying "value = reward now + discounted value of where you land".
  • Run policy iteration and value iteration on small worlds, and compare how much work each needs.
  • State Bellman's principle of optimality in plain words, and explain the curse of dimensionality.
  • Update a belief after a noisy observation, and explain why an agent that cannot see the state plans over beliefs.

Knowing the rules

A route planner knows the road map. A warehouse robot with an exact floor plan knows where each move takes it. When an agent knows the rules of its world, it does not have to learn by trial and error: it can work out good behavior in advance, by calculation. That is planning.

The rules form a model: for every state and action, the probabilities of the possible next states (the transition probabilities) and the expected reward. Add a discount factor γ\gamma, which makes a reward one step later worth γ\gamma times as much, and you have a Markov decision process (MDP). The methods that compute the best behavior from such a model are called dynamic programming, a name Richard Bellman chose in the 1950s.

Here is the small world this lesson uses. There are two states, s1s_1 and s2s_2, and in each the agent can stay or go:

  • in s1s_1, stay pays 1 and keeps you in s1s_1; go pays 0 and moves you to s2s_2;
  • in s2s_2, stay pays 2 and keeps you in s2s_2; go pays 0 and moves you to s1s_1.

With γ=0.9\gamma = 0.9, the best plan is easy to guess: go to s2s_2 once, then stay forever. The point of dynamic programming is to find plans like this mechanically, in worlds far too large to guess.

Check your understanding

The fastest route from your home to the airport passes the train station. What does the principle of optimality let you conclude?

  1. Every fastest route to the airport, from anywhere in the city, passes the station
  2. The stretch from home to the station is the fastest way to reach any point beyond the station
  3. The stretch from the station to the airport is the fastest route from the station to the airport
  4. Nothing, unless all the roads are one-way
Show the answer

C. The stretch from the station to the airport is the fastest route from the station to the airport

If a faster way from the station to the airport existed, you could splice it into your route and beat the fastest route, a contradiction. So best routes from far away are built from best routes from nearer places. Dynamic programming solves each of those smaller problems once and reuses the answer for every plan that passes through it.

What is a policy worth?

A policy says which action to take in each state. Its value Vπ(s)V^\pi(s) is the expected discounted sum of rewards you collect from state ss by following the policy π\pi. Take the policy always stay. In s2s_2 it collects 2 at every step, so its value is 2+0.9⋅2+0.92⋅2+⋯2 + 0.9\cdot2 + 0.9^2\cdot2 + \cdots

Predict before you look

With γ=0.9\gamma = 0.9, what is staying in s2s_2 forever worth, 2+0.9⋅2+0.92⋅2+⋯2 + 0.9\cdot2 + 0.9^2\cdot2 + \cdots?

Show the answer

20

A geometric series: 2/(1−0.9)=202/(1-0.9) = 20. A quicker route: whatever the value VV is, staying pays 2 now and then puts you back where you started, worth VV one step later, so V=2+0.9VV = 2 + 0.9V, which gives V=20V = 20.

That quicker route works in every state of every MDP. A state's value is the reward you get now plus the discounted value of the state you land in, averaged over where you might land. This is the Bellman equation for π\pi:

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

There is one equation per state. For always stay they read V(s1)=1+0.9 V(s1)V(s_1) = 1 + 0.9\,V(s_1) and V(s2)=2+0.9 V(s2)V(s_2) = 2 + 0.9\,V(s_2), so the values are 10 and 20. Computing these numbers is called policy evaluation.

Sweep kkVk(s1)V_k(s_1)Vk(s2)V_k(s_2)Gap to the true values
000(10, 20)
112(9, 18)
21.93.8(8.1, 16.2)
32.715.42(7.29, 14.58)
∞\infty10200
In big worlds you cannot solve the equations by eye. Instead, start from any guess, here all zeros, and replace each value by the right-hand side of its equation, sweeping through all states again and again. Each sweep shrinks the gap by the factor γ=0.9\gamma = 0.9, so after 50 sweeps the values are over 99% of the way there.

Improve, then repeat: policy iteration

Knowing what always stay is worth, can you do better? In each state, look one step ahead: try each action once, then follow the old policy, and compare.

  • In s1s_1: stay gives 1+0.9×10=101 + 0.9\times10 = 10, while go gives 0+0.9×20=180 + 0.9\times20 = 18. Going is better, so switch.
  • In s2s_2: stay gives 2+0.9×20=202 + 0.9\times20 = 20, while go gives 0+0.9×10=90 + 0.9\times10 = 9. Keep staying.

Choosing the best one-step lookahead in every state gives the greedy policy for the old values. The policy improvement theorem guarantees that it is at least as good as the old policy in every state, and strictly better wherever it switched. Here the new policy, go, then stay, is worth (18,20)(18, 20) instead of (10,20)(10, 20).

Policy iteration repeats the two steps, evaluate and improve, until improving changes nothing. A policy that its own one-step lookahead cannot improve is optimal. Here one more lookahead from (18,20)(18, 20) changes nothing: in s1s_1, go gives 0.9×20=180.9\times20 = 18 and stay only 1+0.9×18=17.21 + 0.9\times18 = 17.2.

Value iteration: one step further each sweep

Policy iteration evaluates each policy completely before improving it. Value iteration goes to the other extreme. It keeps a single table of values and, in every sweep, backs up the best action in each state instead of a fixed policy's action:

Vk+1(s)=max⁡a[r(s,a)+γ∑s′P(s′∣s,a) Vk(s′)].V_{k+1}(s) = \max_a\Big[r(s,a) + \gamma\sum_{s'}P(s'\mid s,a)\,V_k(s')\Big].

Starting from zero, Vk(s)V_k(s) is the most discounted reward you can collect in kk steps from ss. As kk grows the values converge to the optimal values V⋆V^\star, which solve the Bellman optimality equation.

In the two-state world the sweeps give (1,2)(1, 2), (1.9,3.8)(1.9, 3.8), (3.42,5.42)(3.42, 5.42), (4.878,6.878)(4.878, 6.878), … creeping toward V⋆=(18,20)V^\star = (18, 20). Yet the greedy policy for V2=(1.9,3.8)V_2 = (1.9, 3.8) already chooses go in s1s_1, because 0.9×3.8=3.420.9\times3.8 = 3.42 beats 1+0.9×1.9=2.711 + 0.9\times1.9 = 2.71. The policy is right long before the values are.

Check your understanding

Policy iteration needed 3 rounds here and value iteration 15 sweeps. Why is policy iteration not simply the better algorithm?

  1. Policy iteration only finds approximately optimal policies
  2. Each of its rounds evaluates a policy exactly, which costs far more than one sweep
  3. It needs a model, while value iteration does not
  4. Its improvement step can make the policy worse
Show the answer

B. Each of its rounds evaluates a policy exactly, which costs far more than one sweep

Exact evaluation means solving a system of equations, one per state, which in large worlds costs much more than a single sweep. Value iteration does a little evaluation per improvement, policy iteration a lot. Between them lies a whole family of methods that evaluate partially, and choosing among them is a trade-off, not a contest.

Why planning alone does not solve RL

Every method so far touches every state in every sweep. That is fine for 11 cells and hopeless for most real problems, because the number of states grows exponentially with the number of variables that describe a state. Bellman called this the curse of dimensionality.

Predict before you look

A robot arm has 7 joints. Its state records each joint's angle and speed, each rounded to one of 10 levels. The number of states is 10 to what power?

Show the answer

14

Seven angles and seven speeds are 14 variables with 10 levels each, so 101410^{14} combinations. Even at a billion state updates per second, one sweep would take 10510^5 seconds, more than a day, and dynamic programming needs many sweeps.

Games are worse: backgammon has about 102010^{20} positions and Go about 1017010^{170}. And there is a second obstacle: real agents rarely have a model at all. The rest of this course removes the two assumptions one at a time, while keeping the shape of dynamic programming (evaluate, improve, repeat):

  • Learning from Experience: Monte Carlo & TD learns values from sampled experience instead of a model (model-free learning).
  • Function Approximation & Deep Q-Learning replaces the table of values by a function with far fewer parameters than there are states.
  • Model-Based RL: Learning to Plan learns the model from experience, then plans with it.

When you cannot see the state

So far the agent always knew which state it was in. Often it does not: a robot's sensors are noisy, and a doctor sees symptoms rather than the disease. In a partially observable MDP (POMDP) the agent receives observations that depend on the state only probabilistically. The best it can do is keep a belief, a probability distribution over the states, update it after every observation, and act on it.

The classic example is the tiger problem (Kaelbling, Littman & Cassandra, 1998). A tiger hides behind one of two doors. Opening the other door pays +10+10, opening the tiger's door costs 100, and listening costs 1 but reports the tiger's side correctly only 85% of the time.

The belief update is Bayes' rule. After one left from 50/50, P(left)=0.85×0.50.85×0.5+0.15×0.5=0.85P(\text{left}) = \frac{0.85\times0.5}{0.85\times0.5 + 0.15\times0.5} = 0.85. After a second left, 0.8520.852+0.152≈0.970\frac{0.85^2}{0.85^2 + 0.15^2} \approx 0.970. Planning in a POMDP means planning over beliefs: the "state" of the planning problem is now a probability, which can take infinitely many values.

Think first You are 85% sure the tiger is on the left. Should you open the right door now, or listen once more?

Opening now is worth 0.85×10−0.15×100=−6.50.85\times10 - 0.15\times100 = -6.5 on average: a 15% chance of losing 100 outweighs the likely 10. Listening costs 1. With probability 0.745 the second report also says left, your belief rises to 0.97, and opening is then worth about +6.7+6.7; otherwise you are back at 50/50 and can listen again. Looking two steps ahead, listening first is worth about +3.7+3.7 on average against −6.5-6.5 for opening now. Information has a price and a value, and weighing them is why an optimal policy can listen several times in a row.

What comes next

Dynamic programming is two ideas: values obey Bellman equations, and acting greedily on values improves behavior. The Bootstrapping lessons turn each piece of this lesson into precise algorithms with proofs.

Bootstrapping lessonWhat you will do there
Policy EvaluationWrite a policy's values as a linear system, solve it directly or by sweeps, prove that the sweeps converge, and reproduce a classic gridworld example by hand.
Policy IterationProve the policy improvement theorem, run policy iteration on the two-state world, and see why it needs so few rounds.
Value IterationDerive value iteration, its rate of convergence γ\gamma, and a stopping rule that guarantees a near-optimal policy.
Partial Observability & POMDPsUpdate beliefs with Bayes' rule, turn a POMDP into an MDP over beliefs, and solve the tiger problem.
The Fixed Point lessons go further still: policy evaluation as linear algebra, prioritized and real-time dynamic programming, average reward, policy iteration as Newton's method and how fast it really is, linear programming, sparse sampling, α-vectors and memory in deep RL.

Key takeaways

  • With a model of the world, the best behavior can be computed instead of learned: dynamic programming builds it from the values of states.
  • A policy's value obeys "value = reward now + discounted value of where you land". Policy evaluation solves these equations, for example by sweeping until the values stop changing.
  • Policy iteration evaluates each policy exactly and then improves it greedily, and needs few rounds; value iteration backs up the best action in every sweep, and its greedy policy is usually right long before its values settle.
  • Bellman's principle of optimality, that the rest of a best plan is a best plan, is what lets dynamic programming solve each subproblem once and reuse it.
  • Sweeping every state is defeated by the curse of dimensionality, and real agents rarely have a model: hence sampling, function approximation and learned models. When the state is hidden, the agent plans over beliefs updated by Bayes' rule.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

What does a planning agent need that an agent learning by trial and error does not?

  1. A neural network to store its values
  2. A reward signal
  3. Many episodes of experience
  4. A model: the transition probabilities and expected rewards for every state and action
Show the answer

D. A model: the transition probabilities and expected rewards for every state and action

Dynamic programming computes values from the model alone, without acting. A learning agent replaces the model with experience: it acts, observes what happens and adjusts its estimates.

Question 2

In the two-state world (γ=0.9\gamma = 0.9), your current value estimates are V(s1)=4V(s_1) = 4 and V(s2)=5V(s_2) = 5. In s1s_1, stay pays 1 and stays; go pays 0 and moves to s2s_2. Which action is greedy in s1s_1?

  1. Stay: its one-step lookahead is worth 4.6
  2. Go, because s2s_2 has the higher value
  3. Go: its one-step lookahead is worth 5
  4. Neither: the two actions tie
Show the answer

A. Stay: its one-step lookahead is worth 4.6

Stay gives 1+0.9×4=4.61 + 0.9\times4 = 4.6 and go gives 0+0.9×5=4.50 + 0.9\times5 = 4.5, so stay wins narrowly. The greedy choice weighs the reward now against the discounted value of where you land.

Question 3

Which statement about value iteration and policy iteration is true?

  1. Policy iteration finds the optimal policy only if it starts from a good one
  2. Value iteration's greedy policy cannot be optimal until the values have fully converged
  3. Both reach optimal behavior; policy iteration takes fewer but more expensive iterations
  4. Value iteration needs a model, but policy iteration does not
Show the answer

C. Both reach optimal behavior; policy iteration takes fewer but more expensive iterations

Policy iteration evaluates each policy exactly and usually needs only a few rounds; value iteration does one cheap backup per state per sweep and needs many sweeps. Both use the model, both converge from any start, and value iteration's greedy policy is often optimal long before its values settle.

Question 4

Why can't value iteration, run as in this lesson, solve the game of Go?

  1. Go gives no reward until the game ends
  2. Go is a two-player game, and dynamic programming only handles one decision maker
  3. With about 1017010^{170} positions, even a single sweep over all states is impossible
  4. The rules of Go are not known precisely enough to form a model
Show the answer

C. With about 1017010^{170} positions, even a single sweep over all states is impossible

The rules are known exactly, so the obstacle is size: a table with one value per position cannot be stored, let alone swept repeatedly. Successful Go programs combine search from the current position with learned approximations of the values.

Question 5

In the tiger problem, listening reports the tiger's side correctly 85% of the time. You start at 50/50, listen and hear left, then listen again and hear right. What is your belief that the tiger is on the left?

  1. 0.85
  2. 0.15
  3. 0.72
  4. 0.5
Show the answer

D. 0.5

The first report multiplies the odds for left by 0.85/0.150.85/0.15 and the second divides them by the same factor, so you are back at even odds. In the formula, 0.85×0.150.85×0.15+0.15×0.85=0.5\frac{0.85\times0.15}{0.85\times0.15 + 0.15\times0.85} = 0.5.

Go deeper

Further reading

  • R. S. Sutton & A. G. Barto, Reinforcement Learning: An Introduction, ch. 3–4 (MIT Press, 2nd ed., 2018).
  • R. Bellman, Dynamic Programming (Princeton University Press, 1957).