TD control: SARSA, Q-learning and the maximization bias
Before this lesson: lesson 02 (Bellman optimality operator, policy improvement, generalized policy iteration), lesson 03 (ε-greedy exploration, incremental means), lesson 04 (TD(0) and the TD error); Jensen's inequality (information theory 03). Time: about 70 minutes, plus the notebook.
Why this matters #
Q-learning is the simplest RL method that learns to act from experience alone, and it is the base of DQN, the network that learned to play Atari games from pixels (lesson 06). The difference between on-policy and off-policy learning, which you first meet here, decides which data an algorithm may use: off-policy methods can learn from old data, from other agents or from logs, on-policy methods cannot without corrections. The maximization bias explains why every modern value-based method has some "double" trick: double DQN, and the clipped double Q-learning of TD3 and SAC (lesson 08). It also explains why Q-learning on a fixed dataset (offline RL) overestimates so badly.
1. Predict first #
2. The picture #
From prediction to control: generalized policy iteration with #
Lesson 02 showed generalized policy iteration (GPI): evaluate the policy a little, improve it a little, and repeat. Two changes make GPI work without a model.
1. Learn , not . Greedy improvement with needs the model: . With action values, the improvement step is just . No , no .
2. Keep exploring. A greedy policy never tries the actions it thinks are worse, so it never learns that they may be better. So we act ε-greedily, as in the bandits of lesson 03: with probability take a greedy action, otherwise a uniformly random action. With actions and one greedy action,
The greedy action also gets its share of the random choice. With 4 actions and , the greedy action has probability , not ; each other action has . A policy with for every action is called ε-soft.
So the loop of every method in this lesson is: in state , pick ε-greedily from ; observe and ; move towards a one-step target :
The policy improves by itself: it is always ε-greedy with respect to the newest .
Three targets for one transition #
The three methods use the same reward and differ only in how they value :
- SARSA: the action the agent really takes next: . The name lists the five things the update uses: .
- Expected SARSA: the average over the agent's own policy: .
- Q-learning: the best action, whatever the agent does next: .
When the episode ends at , all three targets are just (the value after the end is 0).
Switch the next action and move the sliders. The blue bars are and , with their ε-greedy probabilities in orange. The three targets are SARSA, expected SARSA and Q-learning. Only the SARSA target changes when you switch . Press "Sample a′ 200 times": the dashed line, the mean of many SARSA targets, lands on the expected SARSA target. Set and expected SARSA becomes Q-learning.
Cliff walking: careful or bold? #
Cliff walking (Sutton and Barto, Example 6.6) is a grid. The agent starts at S (bottom left) and must reach G (bottom right). The ten cells between them are a cliff. Every step gives ; a step into the cliff gives and sends the agent back to S, and the episode goes on. There is no discounting (). The shortest path walks along the edge of the cliff: 13 steps, return .
Predict the two paths first, then press "Train 500 episodes". The grid shows run 1 of the selected method: the shading is (blue, darker is higher), the small arrow is the greedy action, and the orange line is the greedy path from S. The chart shows the online return, the total reward per episode while the agent explores (10 runs, smoothed). Compare Q-learning, SARSA and expected SARSA: which one has the shortest greedy path, and which one collects the most reward? Then set and train again.
What you see (and what Sutton and Barto report):
- Q-learning learns . Its greedy path walks along the edge: 13 steps.
- SARSA and expected SARSA learn the values of the ε-greedy policy they follow. Next to the cliff, a random step "down" (probability in each step) costs . So states next to the edge get low values, and the greedy path keeps a distance from the cliff.
- Online return: SARSA and expected SARSA collect more reward per episode (about and in the widget, episodes 400–500) than Q-learning (about ), because Q-learning's random steps on the edge often fall into the cliff.
- With the three methods are the same (the ε-greedy policy is greedy), and all learn the edge path here, because the initial values are optimistic and drive exploration.
The agent explores with on cliff walking. Which statement is true after training?
Q-learning's target uses the max, so it learns and the 13-step edge path. But the agent still acts ε-greedily, and on the edge each random "down" step costs . SARSA's target includes these random steps, so SARSA learns lower values next to the cliff, keeps away from it and loses less reward while it explores. The data look alike, but the targets differ.
3. Definitions and main results #
On-policy and off-policy #
Two policies play a role in learning. The behaviour policy chooses the actions that produce the data. The target policy is the policy whose values we learn.
- A method is on-policy if the target policy is the behaviour policy: it evaluates and improves the same policy that acts. SARSA is on-policy: its target uses , so it learns of the ε-greedy policy.
- A method is off-policy if the target policy differs from the behaviour policy. Q-learning is off-policy: the data come from the ε-greedy policy, but the target uses the greedy action, so it learns .
Expected SARSA can be either. With in its sum it is on-policy. With a different target policy it is off-policy; with the greedy target policy, , and expected SARSA is Q-learning.
Why does Q-learning need no importance sampling, unlike off-policy Monte Carlo (lesson 04)? Its target uses only . The action is given (we learn for that action), and come from the environment, not from the policy. The next action is not sampled at all: the max replaces it. So the target has the same distribution whatever policy chose .
To make one update, which of these does Q-learning need from the agent's experience?
The Q-learning target uses only the reward and the next state; the max replaces the next action. SARSA needs (that is the last "A" in its name). No importance weight is needed, because the target does not depend on how was chosen. Only Monte Carlo methods wait for the return.
The three updates in one table #
All three use , with when the episode ends at :
| method | target | needs the next action ? | learns |
|---|---|---|---|
| SARSA | , = the next action taken | yes | (on-policy) |
| expected SARSA | no | ; less variance than SARSA | |
| Q-learning | no | (off-policy) |
Each target is one sample of a Bellman operator. Recall the operators of lesson 02, written for :
For a fixed table , the Q-learning target has expectation : only and are random. So Q-learning is sampled value iteration. The SARSA target and the expected SARSA target both have expectation : they are sampled policy evaluation. Expected SARSA removes one source of noise, the random choice of , so its target has lower variance. This is why it can use larger step sizes (on cliff walking it works even with ).
For one transition, , , and in the two actions have . The policy is ε-greedy with , and the agent's next action is . What are the SARSA, expected SARSA and Q-learning targets?
The probabilities are and (the greedy action gets ). SARSA: . Expected SARSA: . Q-learning: . The option with uses the plain average instead of the policy's probabilities.
ε-greedy improvement and GLIE #
Is acting ε-greedily with respect to really an improvement? Yes, among ε-soft policies.
Theorem (ε-greedy policy improvement; Sutton and Barto §5.4). Let be ε-soft, and let be ε-greedy with respect to . Then for every state .
Proof (one line of algebra, then lesson 02)
- By the policy improvement theorem of lesson 02, it is enough to show for every .
- Write . By the definition of , .
- The weights are (because is ε-soft) and sum to . A maximum is at least any weighted average, so .
- Put step 3 into step 2: .
So GPI with ε-greedy policies converges to the best ε-soft policy, not to the optimal policy. To reach , exploration must fade out, but not too fast. A schedule is GLIE (greedy in the limit with infinite exploration) if
- every state–action pair is visited infinitely often, and
- the policy becomes greedy in the limit, for .
For example, ε-greedy with in episode is GLIE. Under GLIE and suitable step sizes, tabular SARSA converges to with probability 1 (Singh, Jaakkola, Littman and Szepesvári, 2000).
Convergence of Q-learning #
Theorem (Watkins and Dayan, 1992). Take a finite MDP with bounded rewards and . Suppose that every pair is updated infinitely often, and that the step sizes of each pair satisfy the Robbins–Monro conditions
Then tabular Q-learning converges to with probability 1.
The behaviour policy does not appear in the theorem, apart from visiting every pair: this is what off-policy means. The first condition lets the steps add up to any distance; the second makes the noise die out. For example, , where counts the updates of the pair, satisfies both. A constant violates the second condition: then keeps moving around but stays close when is small. The proof writes Q-learning as a noisy version of and uses the contraction of from lesson 02 (stochastic approximation; see Jaakkola, Jordan and Singh, 1994).
Theorem: the maximization bias #
Q-learning's target takes a max over estimates that contain noise. This creates a systematic error.
Theorem (maximization bias). Let be unbiased estimates of , that is . Then
and the inequality is usually strict.
Proof.
- For every : .
- Take expectations: , for every .
- The left side does not depend on , so it is also .
The same result follows from Jensen's inequality, because is convex (information theory 03). Why is it usually strict? Equality needs almost surely for a best . With noise, some other estimate is often the largest, and then the max is above .
In Q-learning. is a max of noisy estimates, so the target is too high on average, and bootstrapping carries the error to earlier states. When all actions are equally good, the bias is largest; when one action is much better than the rest, the max almost always picks it and the bias is small.
Predict first, then press "Repeat 1000 times". Ten actions all have true value 0. Each estimate is the mean of samples of . The orange histogram is the single estimator : its mean is about , not 0. The violet histogram is the double estimator: choose with the blue set, read the value from the independent violet set. Its mean is 0. Make (no choice, no bias) and make large (less noise, less bias).
The double estimator and double Q-learning #
The bias comes from using the same noise to choose the maximiser and to evaluate it: the max picks the estimate whose noise happens to be large. The fix is to separate the two jobs.
Double estimator (van Hasselt, 2010). Use two independent sets of unbiased estimates and . Choose with the first and evaluate it with the second: return .
Why it is not biased upward. depends only on , and is independent of . So, given , the expectation of is , and
It can be biased downward (when picks a worse action), but never upward.
Double Q-learning keeps two tables and . At each step, with probability update :
otherwise update with the roles of and swapped. The agent acts ε-greedily with respect to . Each sample updates only one table, so the two tables stay (roughly) independent. Double DQN (lesson 06) applies the same idea with the online and target networks.
Sutton and Barto, Example 6.7. From state A, "right" ends the episode with reward 0; "left" goes to state B with reward 0. From B, each of 10 actions ends the episode with a reward drawn from . So "left" is worse on average (). With the best possible frequency of "left" is . Q-learning chooses "left" in most early episodes (over 80% around episode 10 in our runs), because is overestimated; double Q-learning comes close to 5%. The notebook reproduces this.
are independent unbiased estimates of five action values that are all equal to . What can you say about ?
By the theorem, . It is strictly larger here: with noise, the largest of five estimates is above its own mean most of the time. Unbiased parts do not give an unbiased max. Only the double estimator, which chooses with one sample and evaluates with another, removes the upward bias.
Answers to section 1. (1) For SARSA, yes: it learns the values of the policy it follows, random steps included, and so it learns to keep away from the cliff. Q-learning's values ignore its own exploration. Which is right depends on the goal: if the agent will keep exploring (or a robot will keep slipping), SARSA's values are the honest ones. (2) Clearly above 0: about (section 4).
4. Worked example #
(a) One transition, three targets. , , , . In there are two actions with , and .
- ε-greedy probabilities in : action 2 is greedy, so and .
- The agent's next action is the exploratory one, (value 1.0).
- SARSA: , so .
- Q-learning: , so .
- Expected SARSA: , so and .
SARSA is pulled down by the exploratory action; Q-learning ignores it; expected SARSA uses its probability instead of the sample. If the agent had picked , SARSA would give , the same as Q-learning. Averaged over , SARSA's target is : exactly the expected SARSA target.
(b) Why Q-learning loses reward on the cliff. On the edge path, the agent spends 11 steps in cells where one action leads into the cliff (S and the ten cells above the cliff). In each of them, the random action is "the wrong one" with probability . So the chance to fall at least once in one pass is
and each fall costs and a restart. Policy evaluation on the grid gives exact numbers: the ε-greedy policy around (what Q-learning's agent does in the long run) has expected return per episode; the best ε-greedy policy, which keeps two rows away from the cliff (15 steps), has . This is the policy that SARSA's values aim for; expected SARSA finds it in our runs, and SARSA with often takes the top row (17 steps).
(c) The size of the maximization bias. Ten actions, all with true value 0. Each estimate is the mean of 10 samples from , so it is , with standard deviation .
- The expected maximum of 10 independent standard normals is (the density of the max of 10 is ).
- Scale by the standard deviation: .
Every true value is 0, but the max is on average. The double estimator gives 0 on average.
5. In code #
The cells below check the worked example. The notebook adds the full SARSA and Q-learning agents on cliff walking and double Q-learning on Example 6.7.
import numpy as np
from scipy import integrate, stats
def epsilon_greedy_probs(q, eps):
p = np.full(len(q), eps / len(q))
best = np.flatnonzero(q == q.max())
p[best] += (1 - eps) / len(best) # ties share the greedy mass
return p
# (a) one transition
r, gamma, alpha, q_next, eps = 1.0, 0.9, 0.1, np.array([1.0, 3.0]), 0.2
pi = epsilon_greedy_probs(q_next, eps)
print(pi) # [0.1 0.9]
y_sarsa = r + gamma * q_next[0] # a' = a_1, the exploratory action
y_exp = r + gamma * pi @ q_next
y_q = r + gamma * q_next.max()
print(alpha * np.array([y_sarsa, y_exp, y_q])) # [0.19 0.352 0.37 ]
# (b) chance to fall at least once on the edge path
print(1 - 0.975 ** 11) # 0.2431
# (c) maximization bias: E[max of k standard normals] = ∫ x k φ(x) Φ(x)^(k-1) dx
k = 10
e_max = integrate.quad(lambda x: x * k * stats.norm.pdf(x) * stats.norm.cdf(x) ** (k - 1), -np.inf, np.inf)[0]
print(e_max, e_max / np.sqrt(10)) # 1.5388 0.4866
rng = np.random.default_rng(0)
A = rng.normal(0, 1, (100_000, 10, 10)).mean(axis=2) # 100k repetitions, 10 actions, 10 samples each
B = rng.normal(0, 1, (100_000, 10, 10)).mean(axis=2) # an independent second set
single = A.max(axis=1)
double = B[np.arange(len(B)), A.argmax(axis=1)]
print(single.mean().round(3), double.mean().round(3)) # 0.487 0.0 (up to Monte Carlo noise)
6. Where it shows up #
- Deep Q-learning. DQN is Q-learning with a neural network, a replay buffer and a target network; double DQN uses the double estimator (lesson 06).
- Actor-critic methods for continuous control. TD3 and SAC train two critics and use the smaller of the two in the target ("clipped double Q"), a direct answer to the maximization bias (lesson 08).
- Learning from logs. Because it is off-policy, Q-learning can learn from data collected by another policy: recommendation, ad placement, resource allocation. On a fixed dataset the max picks actions the data never tried, the extreme case of the maximization bias (offline RL, lesson 06).
- Safe exploration. SARSA's caution is useful when exploration is costly during learning: a robot or a control system that must not fall while it learns. Expected SARSA is a common default for tabular problems.
- ML for science. Value-based RL is used for sequential experimental design and for the control of physical systems, where each step is an experiment or a control action. There the reward is often a noisy measurement, so the maximization bias makes the learned values too optimistic; double estimators or an evaluation on fresh data give honest numbers.
7. Common mistakes #
- Wrong in SARSA. It must be the action you actually take next, and you must then execute that same action. Choosing a fresh action for the next step makes it a different algorithm.
- Bootstrapping at the end. At a terminal transition the target is . A target with a terminal adds a value that should be 0.
- Wrong ε-greedy probabilities. The greedy action has , not . With ties, the greedy mass is shared among the tied actions.
- Mixing up greedy path and online return. Q-learning's greedy path is better on cliff walking, but its online return is worse. Say which one you mean.
- "Q-learning needs importance sampling because it is off-policy." One-step Q-learning does not: its target does not depend on which policy chose . (Multi-step off-policy targets do need corrections.)
- Updating both tables with the same sample in double Q-learning. Then they are no longer independent and the bias comes back. Update one table per sample, chosen at random.
- Mixing reward conventions. Here follows ; Sutton and Barto write . The updates are the same.
8. Check yourself #
- Why does control without a model learn and not ?
Answer
The greedy step with needs the model: . With the greedy step is , with no and no . - With 5 actions and , what are the ε-greedy probabilities? And with two tied greedy actions?
Answer
One greedy action: for it and for each other action. Two tied greedy actions: each gets , the other three get each (sum ). - Why is Q-learning off-policy and SARSA on-policy?
Answer
Q-learning's target uses , the value of the greedy policy, whatever the behaviour policy does, so it learns from ε-greedy data. SARSA's target uses the action the behaviour policy really takes, so it learns the values of that policy. - Expected SARSA uses the greedy policy as its target policy. What algorithm is it?
Answer
Q-learning: under the greedy policy, . - Does satisfy the Robbins–Monro conditions? And ?
Answer
Neither. For the first condition holds (), but , so the second fails: the noise never dies out. For , , so the first fails: the steps cannot add up to any distance. satisfies both for . - Show in one line that , and say why the double estimator is not biased upward.
Answer
for every ; take expectations, then the max over . The double estimator chooses with and evaluates with an independent , so .
Write the SARSA, expected SARSA and Q-learning targets.
SARSA: with the next action taken. Expected SARSA: . Q-learning: . All are at the end of an episode.
What is the difference between an on-policy and an off-policy method?
On-policy: the policy whose values are learned is the policy that acts (SARSA). Off-policy: the target policy differs from the behaviour policy (Q-learning learns the greedy policy from ε-greedy data).
What probability does ε-greedy give to the greedy action, with actions and no ties?
; every other action gets .
Compute the expected SARSA target for , , , .
, so .
Under which conditions does tabular Q-learning converge to ?
Every pair is updated infinitely often, and the step sizes satisfy and (finite MDP, bounded rewards, ).
Why does Q-learning have a worse online return than SARSA on cliff walking?
It learns the edge path of , but it still explores ε-greedily; on the edge, random steps fall into the cliff (). SARSA's values include this risk, so it walks a safer path.
State the maximization-bias inequality.
For unbiased estimates of : , usually strictly.
Why is the double estimator not biased upward?
It chooses with one set and evaluates with an independent set, so .
What is GLIE?
Greedy in the limit with infinite exploration: every state–action pair is visited infinitely often and the policy becomes greedy in the limit (for example ).
Ten actions all have true value 0; each estimate is . About how large is the expected max?
.
9. Interview angle #
- "SARSA vs Q-learning?" On-policy vs off-policy target; SARSA learns the values of the exploring policy, Q-learning learns . Tell the cliff-walking story: Q-learning's greedy path is optimal, SARSA's online return is better.
- "Why is Q-learning off-policy, and why does it not need importance sampling?" The target uses the max, not the behaviour action; is conditioned on and come from the environment.
- "Where does overestimation in Q-learning come from, and how do you fix it?" The max over noisy estimates (Jensen), carried backwards by bootstrapping. Double Q-learning, double DQN, clipped double Q.
- "When does tabular Q-learning converge?" Every pair visited infinitely often and Robbins–Monro step sizes; it is stochastic approximation of the contraction .
- "Why does expected SARSA have lower variance than SARSA?" It averages over exactly instead of sampling it; both have the same expected target.
10. Practice #
The notebook for this lesson runs in Colab. It has five exercises, each with a check cell and a folded solution:
epsilon_greedy_probs: the exact action distribution of ε-greedy, with ties; compare with sampled frequencies.q_learningandsarsaon cliff walking: reproduce the greedy paths and the online-return plot.expected_sarsa: check that its greedy path is safe and its online return is the best of the three.max_estimates: single and double estimators by simulation; the single one averages , the double one 0.double_q_learningon Example 6.7: the fraction of "left" actions with Q-learning and with double Q-learning.
11. Watch and read #
- Richard Sutton and Andrew Barto, Reinforcement Learning: An Introduction, 2nd ed., free PDF: §5.3–5.4 (ε-soft policies and the ε-greedy improvement theorem), §6.4–6.7 (SARSA, Q-learning, expected SARSA, maximization bias and double learning). Example 6.6 is cliff walking, Example 6.7 the maximization-bias MDP.
- Hado van Hasselt, Double Q-learning, NeurIPS 2010: the double estimator and its bias.
- Shangtong Zhang, Python code for Sutton and Barto, cliff walking: compare it with your notebook after you finish the exercises.
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.
No Google account needed: Python runs inside your browser. The first start downloads about 40 MB; your changes are saved in this browser only.