Introduction
This section continues our journey in learning to make good decisions from the experience we build by interacting with an environment, also named Reinforcement Learning.
Where Part 3.1 left us
Part 3.1, Learning from Experience learned the value of a given policy without a model, from episodes only (as opposed to Part 2, where we computed it exactly). Its two methods (MC and TD) share one update equation, an estimate moved by a step toward a target:
where is the state visited at time .
- Monte Carlo waits for the end of the episode, and its target is the return : unbiased, but noisy.
- Temporal differences (TD) update after every step, and the target is , based on the estimate of the next state: biased, but less noisy, and online.
From evaluating to acting, in a nutshell
That was prediction. This page is about control: finding a good policy, still without the model. The method is the same as in Part 2, called generalized policy iteration (GPI), in which we evaluate the policy, make it greedy, and repeat. But, without the model, two things will change from the earlier setup:
- Improving on Q: needs , so we will learn and use to get rid of the model.
- Adding a new ingredient, exploration: trying actions that we do not yet believe are best, to compensate for our uncertainty.
We will study:
- On-policy control: Monte Carlo control and SARSA, and the exploration problem.
- Off-policy control: importance sampling, then Q-learning.
- SARSA or Q-learning? The famous cliff example as a wrap-up.
1. Control, on-policy: Monte Carlo and SARSA
As a quick reminder, on-policy means that we improve the very policy we use to explore the environment; we will compare on-policy and off-policy in more details later.
1.1 Learning Q rather than V
The previous part taught us how to evaluate a given policy from experience only. But our recipe for improving a policy still needs the model . A simple trick allows us to keep our GPI paradigm: learning rather than saves the method.
First, notice that knowing is not enough to act. To be greedy with respect to it, we must look one step ahead (Part 1, section 4.1 shows it), recall that:
and that needs the model .
But, with the action value function , the same step is a lookup in the table:
The sum under the brace above is exactly : the averaging over is already done inside , so improving the policy only compares the values of a row of the Q-table, with no model.
The Q-table gives one number per state and action, and that is enough to make good decisions: this is why, without a model, we estimate directly. With this, GPI remains the same recipe, a loop of two steps:
From now on, evaluation estimates from episodes (Monte Carlo) or transitions (TD), and improvement reads the best action in a row of the Q-table.
1.2 Direct improvement and the exploration problem
But this approach introduces a new challenge, let’s introduce it with a small example. Two doors are in front of you, and you always open the one with the highest value so far.
Are you sure you chose the best door? The left one was tried once. A purely greedy agent will never open it again, and never find out that it might be better. With a deterministic policy, only one action per state is ever tried: the others never get a return, so they cannot be compared.
Think about how you could solve that; take a few seconds.
Two ways to solve this problem:
- Exploring starts: start each episode from a random pair , every pair having a nonzero probability. Every pair is then visited infinitely often in the limit. But this is rarely realistic: we can rarely choose where a real interaction starts.
- Soft policies: keep for every action, so that exploration is built into the policy itself.
The standard soft policy is -greedy.
With probability , play the greedy action; with probability , play an action drawn uniformly at random. With actions,
Every action keeps a probability of at least : such a policy is called -soft, and its exploration never stops.
1.3 Monte Carlo control
On-policy methods use one policy for everything: the agent acts with , and evaluates and improves that same (next section separates the two roles). On-policy Monte Carlo control is GPI with instead of , and averages of returns instead of expectations. It is the first-visit Monte Carlo prediction of Part 3.1, section 1.2, run on , with one extra line: the -greedy improvement.
Input: a small
- , , and -greedy with respect to
- repeat for each episode
- generate an episode with :
- for
- if the pair does not appear earlier in the episode
- evaluation: ,
- improvement: make -greedy with respect to
The version with exploring starts (MC ES) is the same loop, with each episode started from a random pair and a plain greedy improvement.
Two remarks make this approach work:
First, the improvement is still an improvement: for any -soft policy , the -greedy policy with respect to is at least as good, in every state (the proof is in the fold below, if you like maths).
Optional Why ε-greedy improves any ε-soft policy: the proof Math needed Compute: arithmetic, a small linear system, applying a formula of the pageend of high school Reason: expectations, inequalities, an argument in words: no new tools, but a chain of reasoningfirst year of university, with a first course in probability Prove: induction, limits, norms, fixed points: a proof, which can be skipped on a first readingabout two years of university math The level says which math is needed, not how long it takes.
The policy improvement theorem of Part 2 only needs in every state, where . Let be the number of actions. For the -greedy :
The weights are nonnegative, since is -soft, and they sum to . A maximum is at least any weighted average, so
By the policy improvement theorem, for every : is at least as good as , within the family of -soft policies.
Second, the evaluation does not need to be complete. Policy iteration in Part 2 evaluated each policy fully before improving it; here each episode only moves towards , and the next improvement already uses it. GPI only needs each evaluation step to go in the right direction: more, shorter zigzags, same destination. Switch between the two in the figure below.
On the best -soft policy, not on : the policy must keep exploring, so it keeps making random moves. To reach , must go to , slowly enough to keep exploring (GLIE, in the fold at the end of section 1.4).
1.4 SARSA: TD for control
Monte Carlo control inherits the weaknesses of Monte Carlo: high variance, and nothing learned before the end of the episode. The TD update fixes both, so the natural idea is to use TD in the control loop. To do so, we apply TD(0) to , keep the -greedy improvement, and update after every step. This is SARSA:
The name is the tuple that each update uses: .
The important detail is : it is the action really taken next, exploration included.
See what it looks like in the algorithm, on a small example:
Input: a step size , a small
- arbitrary, with
- repeat for each episode
- initialize ; choose in , -greedily with respect to
- repeat until is terminal
- take the action ; observe and
- choose in , -greedily with respect to
- ,
is chosen before the update, and it is the action played at the next step: this is what makes SARSA on-policy. Its target includes the cost of its own exploration, which makes it conservative, as section 3 will show on a cliff.
Another example, the Windy Gridworld shows why learning during the episode matters:
With SARSA, the first episodes are long, then they get shorter and shorter: SARSA learns during the episode. Monte Carlo would be stuck: a policy that never reaches the goal never ends its episode, so it never gets a return to learn from.
What to look at in the Space (“Play with it yourself”)
Step one transition at a time at first, and read the update: with everywhere, each step only lowers the pair it just left, by . Then play whole episodes and watch them get shorter. Switch to Monte Carlo: its first episodes can last thousands of steps (the Space cuts them at 5,000), since nothing is learned before they end.
SARSA converges to the best -soft policy, like Monte Carlo control, with much smaller and more frequent steps: each transition does one evaluation update and one improvement step, since the next action is chosen -greedily from the updated .
If settling for the best -soft policy rather than the optimal one annoys you, the fold below shows how these methods can still reach .
Optional GLIE: explore forever, but less and less Math needed Compute: arithmetic, a small linear system, applying a formula of the pageend of high school Reason: expectations, inequalities, an argument in words: no new tools, but a chain of reasoningfirst year of university, with a first course in probability Prove: induction, limits, norms, fixed points: a proof, which can be skipped on a first readingabout two years of university math The level says which math is needed, not how long it takes.
With a fixed , the agent keeps making random moves forever, so Monte Carlo control and SARSA reach only the best -soft policy. To reach , the exploration schedule must be greedy in the limit with infinite exploration (GLIE):
- Infinite exploration: every action is still tried, in every state, infinitely often;
- Greedy in the limit: in the end, the policy plays only the best action.
The typical choice is -greedy with after episode : goes to , but slowly enough to keep exploring. Monte Carlo control and SARSA need GLIE to reach , because they learn the of the policy they play. Q-learning, in the next section, does not: its target already uses the . For SARSA and Q-learning, the step size must also decrease, for example .
2. Control, off-policy: Q-learning
Q-learning is one of the most famous and influential algorithms in RL. This section gives a formal introduction to it; if you are not math-oriented, you might want to skip section 2.2.
2.1 Acting with one policy, learning about another
On-policy methods learn about the policy they follow, exploration included, but off-policy methods separate the two roles:
- the target policy is the one we want to evaluate or improve, usually greedy;
- the behavior policy is the one that generates the data, usually exploratory.
It might sound crazy to learn from another policy but think of learning chess by watching an amateur play. You never play yourself, yet you want the value of the best play, not of the amateur’s: is the amateur, is optimal play. Why bother?
Because it lets us reuse old data, or data collected by others, and because it lets the agent keep exploring while learning about the optimal policy.
Off-policy, only a fraction of the transitions are ones that would have played: the others must be reweighted, or ignored. That is the problem of the next section.
2.2 Returns from the wrong policy: importance sampling
Math needed Compute: arithmetic, a small linear system, applying a formula of the pageend of high school Reason: expectations, inequalities, an argument in words: no new tools, but a chain of reasoningfirst year of university, with a first course in probability Prove: induction, limits, norms, fixed points: a proof, which can be skipped on a first readingabout two years of university math The level says which math is needed, not how long it takes. A bit mathematical. If it is not your thing, you can skip to 2.3: Q-learning avoids importance sampling.
Monte Carlo prediction averages the returns it observes. Off-policy, these returns come from , so their average converges to the wrong value:
How can we solve this?
Some trajectories are more likely under than under : they should count more. Others are less likely under , or impossible: they should count less, or not at all.
The solution is called importance sampling: it keeps the returns collected with , and reweights each one by how much more likely its trajectory is under .
The idea is general. To estimate an expectation under a distribution with samples drawn from another distribution :
Taking the mean under is the same as taking the mean of samples drawn from , after multiplying each sample by the weight . Caution: this needs wherever , which a deterministic , for instance, does not satisfy.
One example is to get the mean of a fair die while rolling a loaded one:
| face | fair die | loaded die | weight |
|---|---|---|---|
| 1 to 5 | : too rare, counts more | ||
| 6 | : too frequent, counts less |
Check: .
See it live:
In reinforcement learning, the sample is the trajectory after , and its weight is the ratio of the trajectory probability under the two policies:
Note that the dynamics cancel: the ratio needs only the two policies, no model.
Then reweighting works:
This holds only under the coverage assumption that , or in words, must be able to play every action that may play. Otherwise some trajectories of never appear in the data, and no weight can bring them back (and we would divide by zero).
Over visits to , with ratios and returns , the estimate is the average of the reweighted returns, called ordinary importance sampling:
It is unbiased, but its variance can be huge, even infinite, since is a product of ratios. A variant, weighted importance sampling, solves this issue; it is defined in the exercise below, which compares the two. On a blackjack state, the weighted estimate is accurate from the first episodes, while the ordinary one needs many more.
Exercise 2.2 Importance sampling by hand Math needed Compute: arithmetic, a small linear system, applying a formula of the pageend of high school Reason: expectations, inequalities, an argument in words: no new tools, but a chain of reasoningfirst year of university, with a first course in probability Prove: induction, limits, norms, fixed points: a proof, which can be skipped on a first readingabout two years of university math The level says which math is needed, not how long it takes.
From a state , an episode is made of two decisions, each left (L) or right (R); rewards are random, and . We want for the target policy that always plays R, but the data come from the behavior policy that plays L or R with probability each, independently at each decision. Besides the ordinary estimate above, the weighted one divides by the sum of the ratios instead of by :
It is biased, with a bias that vanishes as grows, but its variance stays bounded: it is preferred in practice. Four episodes were observed:
| episode | actions | return |
|---|---|---|
| 1 | R, R | |
| 2 | L, R | |
| 3 | R, L | |
| 4 | R, R |
- Compute the importance-sampling ratio of each episode.
- Compute the ordinary importance-sampling estimate of , then the weighted one.
- The only episodes that could have produced returned and . Which of the two estimates is plausible? What is wrong with the other one?
- Give both estimates after episode 1 only. What does the weighted estimate always equal after a single episode with ? Is it biased?
- With episodes of decisions instead of , which values can take? Explain why the variance of the ordinary estimate grows so fast with .
- What goes wrong if never plays R? Which assumption does this break?
Hint
and , while : each R multiplies by , and a single L sets it to .
Hint
Ordinary: divide by the number of episodes, . Weighted: divide by the sum of the ratios.
Checkpoint what you should get
Ratios ; ordinary estimate , weighted estimate . After episode 1 only: and .
Solution
- Each R multiplies by , and any L sets it to : for the four episodes.
- Ordinary: . Weighted: .
- The weighted estimate, , is the average of the returns of the episodes compatible with . The ordinary estimate, , is larger than every return could have produced: it is unbiased on average, but a single estimate can land far from the truth (high variance).
- After episode 1: ordinary , weighted . After one episode with , the weighted estimate is exactly the observed return: the ratio cancels out. In general this return was drawn under , so its expectation is rather than : the weighted estimate is biased, and the bias vanishes as the number of episodes grows. Here is deterministic, so an episode with is exactly an episode could have played: in this special case the bias is harmless.
- is either , when all decisions are R (probability under ), or . The ordinary estimate is mostly a sum of zeros, with rare terms multiplied by : its variance grows roughly like . This is why, in the blackjack figure, ordinary importance sampling needs many episodes before its error drops, while the weighted one is accurate from the start.
- If never plays R, no episode ever follows : every is , the ordinary estimate is and the weighted one is undefined. This breaks the coverage assumption, .
What to notice the take-away
The ratio is a product, so it explodes or vanishes with the length of the episode. This is the practical weakness of off-policy Monte Carlo, and what Q-learning avoids.
2.3 Q-learning
Q-learning makes one choice that removes the ratios: its target policy is the greedy policy with respect to , .
Here is why that is enough, in three steps.
-
Start from the TD target, SARSA’s target, , is TD(0) applied to : it bootstraps on the value of the next action, sampled from the policy that acts. To learn about while acts, we want the next action as would play it, on average: . This is not a fixed policy: it is greedy with respect to the current , so it changes each time does.
-
A greedy policy has a single action, is for the best action and for all the others, so the expectation collapses to one term:
-
Nothing is left to sample, the is computed from the table, not drawn from a policy: the action that plays next is never used. No sample from means no ratio to correct it, hence no extra variance.
SARSA could not do the same directly: its is sampled from the policy that acts, so learning about another policy would need the ratio .
The update is now:
The agent acts with any exploratory , typically -greedy in , but its target uses the best next action, not the one played.
Q-learning is to value iteration what TD is to dynamic programming. Value iteration on (Part 2) applies the Bellman optimality backup, with the model:
Q-learning applies the same backup to one sampled transition instead of the sum over , and moves only a step toward it.
One update does both jobs of GPI: the evaluates and improves at once, so is pulled directly towards . Q-learning converges to and , whatever is, as long as every pair keeps being visited and the step sizes decrease. In doing so, it ignores the cost of exploring, which makes it aggressive, and it can learn from data collected by any policy: that is why it is the standard off-policy control algorithm.
See it in action on the same example as SARSA:
Input: a step size , a small
- arbitrary, with
- repeat for each episode
- initialize
- repeat until is terminal
- choose in , -greedily with respect to (the behavior policy )
- take the action ; observe and
Compared with SARSA, one line is gone: the next action is no longer chosen before the update, since the target does not use it.
Optional SARSA → Q-learning: the two algorithms as a diff, line by line
initialize S
- choose A in S, ε-greedily with respect to Q
repeat until S is terminal
+ choose A in S, ε-greedily with respect to Q
take the action A; observe R and S′
- choose A′ in S′, ε-greedily with respect to Q
- Q(S, A) ← Q(S, A) + α [R + γ Q(S′, A′) − Q(S, A)]
+ Q(S, A) ← Q(S, A) + α [R + γ max_a′ Q(S′, a′) − Q(S, A)]
- S ← S′, A ← A′
+ S ← S′
SARSA has to know its next action before it updates, because its target uses it; Q-learning picks each action at the top of the loop, after the previous update, with its behavior policy .
After enough learning, the table becomes the answer: it is one row per state, one column per action, and . The best entry of a row is then , and its column is the optimal action, , which we can read without any model.
Note a small drawback of the Q-table: when two entries of a row are close, say and , a small error in is enough to flip the greedy action.
3. Wrap-up: SARSA or Q-learning?
The two control algorithms of this page differ by one term of their target. Let’s see what this changes on an example where the agent must walk along a cliff.
See the two algorithms solving this problem below :
For once, the algorithms don’t converge to the same solution and learn two different paths:
-
Q-learning learns , so its greedy path is the shortest one, steps right along the edge of the cliff, even though its -greedy behavior still falls in from time to time.
-
SARSA learns the value of the policy it actually follows, random moves included: next to the cliff, a random move costs , so it learns that the edge is dangerous and keeps a safety margin, one or two rows away.
The paradox: during training, SARSA collects more reward per episode than Q-learning (about against in the book’s figure), because Q-learning keeps walking along the edge and keeps falling.
Side by side, everything follows from the difference of target:
What to look at in the Space (“Compare them live”)
Run the comparison with the book’s settings, and : SARSA’s curve ends above Q-learning’s, while Q-learning’s greedy path is the shorter one. The Windy Gridworld, in the environment menu, shows the other side: Monte Carlo stuck on its long first episodes.
Rule of thumb: SARSA when mistakes during learning are costly, Q-learning when only the final policy matters.
Exercise 3.1 SARSA vs Q-learning, one update by hand Math needed Compute: arithmetic, a small linear system, applying a formula of the pageend of high school Reason: expectations, inequalities, an argument in words: no new tools, but a chain of reasoningfirst year of university, with a first course in probability Prove: induction, limits, norms, fixed points: a proof, which can be skipped on a first readingabout two years of university math The level says which math is needed, not how long it takes.
An agent acts -greedily with in a gridworld with actions (up, right, down, left), and . Its current estimates are and
| up | right | down | left | |
|---|---|---|---|---|
In state it plays right, gets and lands in . In , the -greedy policy then draws the next action : an exploratory move.
- With which probability does the -greedy policy play right in ? down?
- Compute the new value of after a SARSA update.
- Same question with a Q-learning update, starting again from .
- Same two questions if the policy had drawn instead. What do you notice?
- Suppose action selection is fully greedy (). Is Q-learning then exactly the same algorithm as SARSA? Will they make exactly the same action selections and updates? (Sutton and Barto, Exercise 6.12.)
- On Cliff Walking, Q-learning learns the path along the cliff and SARSA the safer one. Using questions 2 and 3, explain in two sentences why SARSA nevertheless gets more reward per episode during training.
Hint
The greedy action in is the one with the largest . With actions, it is played with probability , each other action with .
Hint
SARSA’s target uses for the action really drawn; Q-learning’s uses , whatever was drawn.
Hint
For question 5, look at the order of the operations in each algorithm: when is the next action chosen, before or after the update of ? And what if ?
Checkpoint what you should get
for right, for down. SARSA gives , Q-learning ; with , both give .
Solution
- The greedy action in is right (). With : , and each other action, down included, has .
- SARSA uses the action really drawn, : target , so .
- Q-learning uses the best action in : target , so .
- With , SARSA’s target is : both updates give . The two algorithms differ only on the steps where the next action is exploratory; on those steps SARSA feels the cost of exploring, and Q-learning ignores it.
- Almost, but not exactly. With , both act greedily and both targets use . The difference is the order: SARSA picks before updating , and plays it; Q-learning updates first, then picks the action in with the updated . When , the update can change the greedy action in , and the two algorithms then select different actions and make different updates.
- SARSA’s targets include the of the exploratory steps that fall off the cliff, as in question 2, so it learns that the edge is dangerous under its own -greedy behavior and walks away from it. Q-learning’s targets ignore exploration, as in question 3, so it walks along the edge, where its of random moves regularly throw it into the cliff: its greedy path is better, its reward during training is worse.
What to notice the take-away
One exploratory step is enough to separate the two algorithms: SARSA’s estimate dropped to , Q-learning’s rose to . Summed over thousands of steps next to a cliff, this is the whole difference between a safe path and the optimal one.
In a few lines
We finally learned to make good decisions (or almost the best ones) from experience only, congrats 😁
This rests on a few building blocks:
- Control: learn , so that improvement needs no model.
- Exploration is essential; -greedy is the simple baseline.
- SARSA: on-policy, conservative; Q-learning: off-policy, learns .
- Off-policy Monte Carlo needs importance sampling; Q-learning avoids it.
- Tractable only if the environment is fast to evaluate: learning takes many episodes, so a simulator, not the real system.
So, what’s next for solving real-world problems?
Every method of Parts 3.1 and 3.2 stores one number per state (V-table), or per state and action (Q-table), in a table. Part 4: From Discrete to Continuous takes up what happens when that table is too large, or when the states are continuous. To handle this, the table must be replaced by a function: deep Q-networks, policy gradient and actor-critic are our next targets. And most importantly, we will apply them on a real system 👀🤖