Learning to Act

Reinforcement learning, part 3.2: control without a model, SARSA and Q-learning

Author

Published

Nov. 2026

PDF

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 π\pi 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 α\alpha toward a target:

V(St)←V(St)+α [ target−V(St) ]V(S_t) \leftarrow V(S_t) + \alpha\,\big[\,\text{target} - V(S_t)\,\big]

where StS_t is the state visited at time tt.

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:

We will study:

  1. On-policy control: Monte Carlo control and SARSA, and the exploration problem.
  2. Off-policy control: importance sampling, then Q-learning.
  3. 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 pp. A simple trick allows us to keep our GPI paradigm: learning QQ rather than VV saves the method.

First, notice that knowing v∗v_* 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:

π∗(s)=arg⁡max⁡a∑s′,rp(s′,r∣s,a) [r+γ v∗(s′)]⏟q∗(s,a)\pi_*(s) = \arg\max_a \underbrace{\sum_{s', r} p(s', r \mid s, a)\,\big[r + \gamma\, v_*(s')\big]}_{q_*(s, a)}

and that needs the model pp.

But, with the action value function QQ, the same step is a lookup in the q∗q_* table:

π∗(s)=arg⁡max⁡aq∗(s,a)\pi_*(s) = \arg\max_a q_*(s, a)

The sum under the brace above is exactly q∗(s,a)q_*(s, a): the averaging over pp is already done inside q∗q_*, so improving the policy only compares the mm 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 QQ directly. With this, GPI remains the same recipe, a loop of two steps:

π →evaluation Q≈qπ →improvement π′(s)=arg⁡max⁡aQ(s,a) ⟶ ⋯\pi \ \xrightarrow{\textbf{evaluation}} \ Q \approx q_\pi \ \xrightarrow{\textbf{improvement}} \ \pi'(s) = \arg\max_a Q(s, a) \ \longrightarrow \ \cdots

From now on, evaluation estimates QQ 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.

Two doors, chosen greedily
Always open the door with the highest value so far. Left gives 0 once; right gives +1, +3, +2, so V(right) = +2 and right is opened again and again. One sample says little about the left door, but a greedy agent will never open it again to find out.

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 (s,a)(s, a), 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 π(a∣s)>0\pi(a \mid s) > 0 for every action, so that exploration is built into the policy itself.

The standard soft policy is ε\varepsilon-greedy.

ε-greedy policy

With probability 1−ε1 - \varepsilon, play the greedy action; with probability ε\varepsilon, play an action drawn uniformly at random. With mm actions,

π(a∣s)={1−ε+εmif a=arg⁡max⁡a′Q(s,a′)εmotherwise\pi(a \mid s) = \begin{cases} 1 - \varepsilon + \dfrac{\varepsilon}{m} & \text{if } a = \arg\max_{a'} Q(s, a') \\[2mm] \dfrac{\varepsilon}{m} & \text{otherwise} \end{cases}
ε-greedy, two shares
Four actions; a2 has the largest Q. Each draw first exploits, with probability 1 − ε, which always plays a2; or explores, with probability ε, which picks one of the 4 actions uniformly, a2 included. So a2 gets 1 − ε + ε/4 and every other action ε/4. The black ticks are the observed frequencies; move ε to change the shares.

Every action keeps a probability of at least εm\frac{\varepsilon}{m}: such a policy is called ε\varepsilon-soft, and its exploration never stops.

1.3 Monte Carlo control

On-policy methods use one policy for everything: the agent acts with π\pi, and evaluates and improves that same π\pi (next section separates the two roles). On-policy Monte Carlo control is GPI with QQ instead of VV, and averages of returns instead of expectations. It is the first-visit Monte Carlo prediction of Part 3.1, section 1.2, run on QQ, with one extra line: the ε\varepsilon-greedy improvement.

Algorithm On-policy first-visit Monte Carlo control

Input: a small ε>0\varepsilon > 0

  • Q(s,a)←0Q(s, a) \leftarrow 0, N(s,a)←0N(s, a) \leftarrow 0, and π\pi ε\varepsilon-greedy with respect to QQ
  • repeat for each episode
    • generate an episode with π\pi: S0,A0,R1,…,ST−1,AT−1,RTS_0, A_0, R_1, \dots, S_{T-1}, A_{T-1}, R_T
    • G←0G \leftarrow 0
    • for t=T−1,T−2,…,0t = T-1, T-2, \dots, 0
      • G←γ G+Rt+1G \leftarrow \gamma\, G + R_{t+1}
      • if the pair (St,At)(S_t, A_t) does not appear earlier in the episode
        • evaluation: N(St,At)←N(St,At)+1N(S_t, A_t) \leftarrow N(S_t, A_t) + 1,  Q(St,At)←Q(St,At)+1N(St,At)[G−Q(St,At)]\ Q(S_t, A_t) \leftarrow Q(S_t, A_t) + \frac{1}{N(S_t, A_t)}\big[G - Q(S_t, A_t)\big]
        • improvement: make π(⋅∣St)\pi(\cdot \mid S_t) ε\varepsilon-greedy with respect to Q(St,⋅)Q(S_t, \cdot)
Monte Carlo control on the two doors of section 1.2, seen as a one-state problem: every episode is a single opening, so T = 1 and G = R1. ε = 0.2: the greedy door gets 0.9, the other 0.1. Each door shows its true value q, which the agent does not know: Q should approach it. Evaluation (orange) averages the returns into Q; improvement (green) makes π ε-greedy with respect to the new Q. After an exploratory opening of the left door returns +5, Q(left) passes Q(right) and the policy switches doors: the exploration the greedy agent lacked.

The version with exploring starts (MC ES) is the same loop, with each episode started from a random pair (S0,A0)(S_0, A_0) and a plain greedy improvement.

Two remarks make this approach work:

First, the improvement is still an improvement: for any ε\varepsilon-soft policy π\pi, the ε\varepsilon-greedy policy π′\pi' with respect to qπq_\pi is at least as good, vπ′(s)≥vπ(s)v_{\pi'}(s) \geq v_\pi(s) 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 qπ(s,π′(s))≥vπ(s)q_\pi(s, \pi'(s)) \geq v_\pi(s) in every state, where qπ(s,π′(s))=∑aπ′(a∣s) qπ(s,a)q_\pi(s, \pi'(s)) = \sum_a \pi'(a \mid s)\, q_\pi(s, a). Let mm be the number of actions. For the ε\varepsilon-greedy π′\pi':

qπ(s,π′(s))=εm∑aqπ(s,a)+(1−ε)max⁡aqπ(s,a)q_\pi(s, \pi'(s)) = \frac{\varepsilon}{m} \sum_a q_\pi(s, a) + (1 - \varepsilon) \max_a q_\pi(s, a)

The weights wa=π(a∣s)−ε/m1−εw_a = \frac{\pi(a \mid s) - \varepsilon / m}{1 - \varepsilon} are nonnegative, since π\pi is ε\varepsilon-soft, and they sum to 11. A maximum is at least any weighted average, so

qπ(s,π′(s))≥εm∑aqπ(s,a)+(1−ε)∑aπ(a∣s)−ε/m1−ε qπ(s,a)=∑aπ(a∣s) qπ(s,a)=vπ(s)\begin{aligned} q_\pi(s, \pi'(s)) &\geq \frac{\varepsilon}{m} \sum_a q_\pi(s, a) + (1 - \varepsilon) \sum_a \frac{\pi(a \mid s) - \varepsilon / m}{1 - \varepsilon}\, q_\pi(s, a) \\ &= \sum_a \pi(a \mid s)\, q_\pi(s, a) = v_\pi(s) \end{aligned}

By the policy improvement theorem, vπ′(s)≥vπ(s)v_{\pi'}(s) \geq v_\pi(s) for every ss: π′\pi' is at least as good as π\pi, within the family of ε\varepsilon-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 QQ towards qπq_\pi, 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.

Evaluation and improvement, in zigzag
Q = qπ evaluationπ = greedy(Q) improvementQ₀, π₀q*, π*

As in Sutton and Barto (section 4.6): two lines meet at q*, π*. The upper line is evaluation, Q = qπ; the lower one is improvement, π = greedy(Q). Full evaluation (policy iteration, Part 2): every orange arrow reaches the upper line. Partial evaluation (Monte Carlo control, one episode per evaluation): the orange arrows stop short of it, the green ones still reach the greedy line, and there are more, shorter zigzags to the same point.
Caution: where does it land?

On the best ε\varepsilon-soft policy, not on π∗\pi_*: the policy must keep exploring, so it keeps making random moves. To reach π∗\pi_*, ε\varepsilon must go to 00, 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 Q(S,A)Q(S, A), keep the ε\varepsilon-greedy improvement, and update after every step. This is SARSA:

Q(St,At)⏟new estimate←Q(St,At)⏟old estimate+α [Rt+1+γ Q(St+1,At+1)⏟target−Q(St,At)]⏟TD error\underbrace{Q(S_t, A_t)}_{\text{new estimate}} \leftarrow \underbrace{Q(S_t, A_t)}_{\text{old estimate}} + \alpha\,\underbrace{\big[\underbrace{R_{t+1} + \gamma\, Q(S_{t+1}, A_{t+1})}_{\text{target}} - Q(S_t, A_t)\big]}_{\text{TD error}}

The name is the tuple that each update uses: (St,At,Rt+1,St+1,At+1)(S_t, A_t, R_{t+1}, S_{t+1}, A_{t+1}).

The important detail is At+1A_{t+1}: it is the action really taken next, exploration included.

See what it looks like in the algorithm, on a small example:

Algorithm SARSA

Input: a step size α∈(0,1]\alpha \in (0, 1], a small ε>0\varepsilon > 0

  • Q(s,a)Q(s, a) arbitrary, with Q(terminal,⋅)=0Q(\text{terminal}, \cdot) = 0
  • repeat for each episode
    • initialize SS; choose AA in SS, ε\varepsilon-greedily with respect to QQ
    • repeat until SS is terminal
      • take the action AA; observe RR and S′S'
      • choose A′A' in S′S', ε\varepsilon-greedily with respect to QQ
      • Q(S,A)←Q(S,A)+α [R+γ Q(S′,A′)−Q(S,A)]Q(S, A) \leftarrow Q(S, A) + \alpha\,\big[R + \gamma\, Q(S', A') - Q(S, A)\big]
      • S←S′S \leftarrow S',  A←A′\ A \leftarrow A'
 
−1 per step, −10 for the pit · α = 0.5, γ = 1, ε-greedy
 
 
SARSA step by step on a 2 × 3 grid (−1 per step, −10 for the pit, α = 0.5, γ = 1), with the line being run highlighted. Each cell shows its four values Q(s, ·) and its greedy action. In the first episode, the agent walks into the pit: Q(start, →) drops and the greedy action of the start flips from → to ↑, which is policy improvement. In the second, the next action A′ is a random move toward the pit, and SARSA's target reads its value, Q(S′, A′) = −6: exploration is part of what SARSA learns.

A′A' 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:

SARSA in the wind
Open in a new tab ↗
SARSA on the Windy Gridworld with the book's settings, ε = 0.1 and α = 0.5, computed in your browser and replayed. Left: the wind under each column, the shortest path (light gray, the goal), the current episode (orange), and the greedy path, redrawn every 5 episodes (green). Right: the episodes completed against the time steps spent. The first episode takes 468 steps; the curve starts flat, then gets steeper as the episodes get shorter: SARSA learns during the episodes themselves. After 170 episodes, the greedy path is the shortest one, 15 steps. “Play with it yourself” opens the course Space below the figure, on the same environment.

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 Q=0Q = 0 everywhere, each step only lowers the pair it just left, by α×1=0.5\alpha \times 1 = 0.5. 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 ε\varepsilon-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 ε\varepsilon-greedily from the updated QQ.

If settling for the best ε\varepsilon-soft policy rather than the optimal one annoys you, the fold below shows how these methods can still reach π∗\pi_*.

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 ε\varepsilon, the agent keeps making random moves forever, so Monte Carlo control and SARSA reach only the best ε\varepsilon-soft policy. To reach π∗\pi_*, the exploration schedule must be greedy in the limit with infinite exploration (GLIE):

  1. Infinite exploration: every action is still tried, in every state, infinitely often;
  2. Greedy in the limit: in the end, the policy plays only the best action.

The typical choice is ε\varepsilon-greedy with εk=1k\varepsilon_k = \frac{1}{k} after episode kk: ε\varepsilon goes to 00, but slowly enough to keep exploring. Monte Carlo control and SARSA need GLIE to reach q∗q_*, because they learn the QQ of the policy they play. Q-learning, in the next section, does not: its target already uses the max⁡\max. For SARSA and Q-learning, the step size must also decrease, for example α=1N(s,a)\alpha = \frac{1}{N(s, a)}.

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:

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: μ\mu is the amateur, π\pi 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.

Two roles: behavior and target
The behavior policy μ, the amateur, plays one move per step (top row). Below, the move the target policy π, optimal play, would have played in the same position. Where they agree, the step says something directly about π; where they differ, it does not. On-policy the two rows would always agree; off-policy, only a fraction of the steps do.

Off-policy, only a fraction of the transitions are ones that π\pi 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 μ\mu, so their average converges to the wrong value:

1N∑i=1NGi ⟶ Eμ[Gt∣St=s]=vμ(s) ≠ vπ(s)\frac{1}{N} \sum_{i=1}^N G_i \ \longrightarrow \ \mathbb{E}_\mu\big[G_t \mid S_t = s\big] = \boxed{v_\mu(s) \ \neq \ v_\pi(s)}

How can we solve this?

Some trajectories are more likely under π\pi than under μ\mu: they should count more. Others are less likely under π\pi, or impossible: they should count less, or not at all.

The solution is called importance sampling: it keeps the returns collected with μ\mu, and reweights each one by how much more likely its trajectory is under π\pi.

The idea is general. To estimate an expectation under a distribution pp with samples drawn from another distribution qq:

EX∼p[f(X)]=∑xp(x) f(x)=∑xq(x) p(x)q(x) f(x)=EX∼q[p(X)q(X) f(X)]\mathbb{E}_{X \sim p}\big[f(X)\big] = \sum_x p(x)\, f(x) = \sum_x q(x)\, \frac{p(x)}{q(x)}\, f(x) = \mathbb{E}_{X \sim q}\left[\frac{p(X)}{q(X)}\, f(X)\right]

Taking the mean under pp is the same as taking the mean of samples drawn from qq, after multiplying each sample by the weight p(x)q(x)\frac{p(x)}{q(x)}. Caution: this needs q(x)>0q(x) > 0 wherever p(x)>0p(x) > 0, which a deterministic qq, for instance, does not satisfy.

One example is to get the mean of a fair die while rolling a loaded one:

facefair die p(x)p(x)loaded die q(x)q(x)weight p(x)q(x)\frac{p(x)}{q(x)}
1 to 516\frac{1}{6}110\frac{1}{10}53\frac{5}{3}: too rare, counts more
616\frac{1}{6}12\frac{1}{2}13\frac{1}{3}: too frequent, counts less

Check: 12×13×6+110×53×(1+2+3+4+5)=1+2.5=3.5\frac{1}{2} \times \frac{1}{3} \times 6 + \frac{1}{10} \times \frac{5}{3} \times (1 + 2 + 3 + 4 + 5) = 1 + 2.5 = 3.5.

See it live:

Rolling a loaded die to average a fair one
 
 
 
Rolls of the loaded die, q(6) = 1/2 and q(x) = 1/10 for the other faces. Blue: the plain average of the rolls, which settles at the loaded die's mean, 0.5 × 6 + 0.1 × 15 = 4.5. Orange: each roll multiplied by its weight, 1/3 for a six and 5/3 otherwise, then averaged; it settles at the fair die's 3.5, more noisily.

In reinforcement learning, the sample is the trajectory after StS_t, and its weight is the ratio of the trajectory probability under the two policies:

ρt:T−1=∏k=tT−1π(Ak∣Sk) p(Sk+1∣Sk,Ak)∏k=tT−1μ(Ak∣Sk) p(Sk+1∣Sk,Ak)=∏k=tT−1π(Ak∣Sk)μ(Ak∣Sk)\rho_{t:T-1} = \frac{\prod_{k=t}^{T-1} \pi(A_k \mid S_k)\, p(S_{k+1} \mid S_k, A_k)}{\prod_{k=t}^{T-1} \mu(A_k \mid S_k)\, p(S_{k+1} \mid S_k, A_k)} = \boxed{\prod_{k=t}^{T-1} \frac{\pi(A_k \mid S_k)}{\mu(A_k \mid S_k)}}

Note that the dynamics cancel: the ratio needs only the two policies, no model.

Then reweighting works:

Eμ⏟average over the episodes of μ[ ρt:T−1⏟weight  Gt⏟return observed ∣ St=s]  =  vπ(s)⏟value under π\underbrace{\mathbb{E}_\mu}_{\text{average over the episodes of } \mu}\Big[\,\underbrace{\rho_{t:T-1}}_{\text{weight}}\;\underbrace{G_t}_{\text{return observed}} \,\Big|\, S_t = s\Big] \;=\; \underbrace{v_\pi(s)}_{\text{value under } \pi}

This holds only under the coverage assumption that π(a∣s)>0⇒μ(a∣s)>0\pi(a \mid s) > 0 \Rightarrow \mu(a \mid s) > 0, or in words, μ\mu must be able to play every action that π\pi may play. Otherwise some trajectories of π\pi never appear in the data, and no weight can bring them back (and we would divide by zero).

Over NN visits to ss, with ratios ρi\rho_i and returns GiG_i, the estimate is the average of the reweighted returns, called ordinary importance sampling:

V(s)=1N∑i=1Nρi GiV(s) = \frac{1}{N} \sum_{i=1}^N \rho_i\, G_i

It is unbiased, but its variance can be huge, even infinite, since ρ\rho 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 ss, an episode is made of two decisions, each left (L) or right (R); rewards are random, and γ=1\gamma = 1. We want vπ(s)v_\pi(s) for the target policy π\pi that always plays R, but the data come from the behavior policy μ\mu that plays L or R with probability 12\frac{1}{2} each, independently at each decision. Besides the ordinary estimate above, the weighted one divides by the sum of the ratios instead of by NN:

V(s)=∑i=1Nρi Gi∑i=1NρiV(s) = \frac{\sum_{i=1}^N \rho_i\, G_i}{\sum_{i=1}^N \rho_i}

It is biased, with a bias that vanishes as NN grows, but its variance stays bounded: it is preferred in practice. Four episodes were observed:

episodeactionsreturn GG
1R, R22
2L, R00
3R, L11
4R, R11
  1. Compute the importance-sampling ratio ρ=∏kπ(Ak∣Sk)μ(Ak∣Sk)\rho = \prod_k \frac{\pi(A_k \mid S_k)}{\mu(A_k \mid S_k)} of each episode.
  2. Compute the ordinary importance-sampling estimate of vπ(s)v_\pi(s), then the weighted one.
  3. The only episodes that π\pi could have produced returned 22 and 11. Which of the two estimates is plausible? What is wrong with the other one?
  4. Give both estimates after episode 1 only. What does the weighted estimate always equal after a single episode with ρ>0\rho > 0? Is it biased?
  5. With episodes of TT decisions instead of 22, which values can ρ\rho take? Explain why the variance of the ordinary estimate grows so fast with TT.
  6. What goes wrong if μ\mu never plays R? Which assumption does this break?
Hint

π(R)=1\pi(\text{R}) = 1 and π(L)=0\pi(\text{L}) = 0, while μ(R)=μ(L)=12\mu(\text{R}) = \mu(\text{L}) = \frac{1}{2}: each R multiplies ρ\rho by 22, and a single L sets it to 00.

Hint

Ordinary: divide by the number of episodes, 44. Weighted: divide by the sum of the ratios.

Checkpoint what you should get

Ratios 4,0,0,44, 0, 0, 4; ordinary estimate 33, weighted estimate 1.51.5. After episode 1 only: 88 and 22.

Solution
  1. Each R multiplies ρ\rho by 11/2=2\frac{1}{1/2} = 2, and any L sets it to 00: ρ=4,0,0,4\rho = 4, 0, 0, 4 for the four episodes.
  2. Ordinary: 4×2+0+0+4×14=124=3\frac{4 \times 2 + 0 + 0 + 4 \times 1}{4} = \frac{12}{4} = 3. Weighted: 4×2+4×14+4=128=1.5\frac{4 \times 2 + 4 \times 1}{4 + 4} = \frac{12}{8} = 1.5.
  3. The weighted estimate, 1.51.5, is the average of the returns of the episodes compatible with π\pi. The ordinary estimate, 33, is larger than every return π\pi could have produced: it is unbiased on average, but a single estimate can land far from the truth (high variance).
  4. After episode 1: ordinary 4×21=8\frac{4 \times 2}{1} = 8, weighted 4×24=2\frac{4 \times 2}{4} = 2. After one episode with ρ>0\rho > 0, the weighted estimate is exactly the observed return: the ratio cancels out. In general this return was drawn under μ\mu, so its expectation is vμ(s)v_\mu(s) rather than vπ(s)v_\pi(s): the weighted estimate is biased, and the bias vanishes as the number of episodes grows. Here π\pi is deterministic, so an episode with ρ>0\rho > 0 is exactly an episode π\pi could have played: in this special case the bias is harmless.
  5. ρ\rho is either 2T2^T, when all TT decisions are R (probability 2−T2^{-T} under μ\mu), or 00. The ordinary estimate is mostly a sum of zeros, with rare terms multiplied by 2T2^T: its variance grows roughly like 2T2^T. 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.
  6. If μ\mu never plays R, no episode ever follows π\pi: every ρ\rho is 00, the ordinary estimate is 00 and the weighted one is undefined. This breaks the coverage assumption, π(a∣s)>0⇒μ(a∣s)>0\pi(a \mid s) > 0 \Rightarrow \mu(a \mid s) > 0.
What to notice the take-away

The ratio ρ\rho 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 QQ, π(s)=arg⁡max⁡aQ(s,a)\pi(s) = \arg\max_{a} Q(s, a).

Q-learning, the roles
The behavior policy μ, any exploratory policy, plays and produces the transitions; each one updates Q. The target policy π is greedy with respect to the current Q: watch it flip when an update changes which Q(S′, ·) is largest. The update's target reads π through a max over the next actions.

Here is why that is enough, in three steps.

  1. Start from the TD target, SARSA’s target, Rt+1+γ Q(St+1,At+1)R_{t+1} + \gamma\, Q(S_{t+1}, A_{t+1}), is TD(0) applied to QQ: it bootstraps on the value of the next action, sampled from the policy that acts. To learn about π\pi while μ\mu acts, we want the next action as π\pi would play it, on average: Rt+1+γ EA′∼π[Q(St+1,A′)]R_{t+1} + \gamma\, \mathbb{E}_{A' \sim \pi}\big[Q(S_{t+1}, A')\big]. This π\pi is not a fixed policy: it is greedy with respect to the current QQ, so it changes each time QQ does.

  2. A greedy policy has a single action, π(a′∣s′)\pi(a' \mid s') is 11 for the best action and 00 for all the others, so the expectation collapses to one term:

    EA′∼π[Q(s′,A′)]=∑a′π(a′∣s′) Q(s′,a′)=max⁡a′Q(s′,a′)\mathbb{E}_{A' \sim \pi}\big[Q(s', A')\big] = \sum_{a'} \pi(a' \mid s')\, Q(s', a') = \max_{a'} Q(s', a')
  3. Nothing is left to sample, the max⁡\max is computed from the table, not drawn from a policy: the action that μ\mu plays next is never used. No sample from π\pi means no ratio πμ\frac{\pi}{\mu} to correct it, hence no extra variance.

SARSA could not do the same directly: its At+1A_{t+1} is sampled from the policy that acts, so learning about another policy would need the ratio π(At+1∣St+1)μ(At+1∣St+1)\frac{\pi(A_{t+1} \mid S_{t+1})}{\mu(A_{t+1} \mid S_{t+1})}.

The update is now:

Q(St,At)←Q(St,At)+α [Rt+1+γmax⁡a′Q(St+1,a′)⏟target−Q(St,At)]Q(S_t, A_t) \leftarrow Q(S_t, A_t) + \alpha\,\big[\underbrace{R_{t+1} + \gamma \max_{a'} Q(S_{t+1}, a')}_{\text{target}} - Q(S_t, A_t)\big]

The agent acts with any exploratory μ\mu, typically ε\varepsilon-greedy in QQ, 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 QQ (Part 2) applies the Bellman optimality backup, with the model:

qk+1(s,a)=∑s′,rp(s′,r∣s,a) [r+γmax⁡a′qk(s′,a′)]q_{k+1}(s, a) = \sum_{s', r} p(s', r \mid s, a)\,\big[r + \gamma \max_{a'} q_k(s', a')\big]

Q-learning applies the same backup to one sampled transition (St,At,Rt+1,St+1)(S_t, A_t, R_{t+1}, S_{t+1}) instead of the sum over pp, and moves QQ only a step α\alpha toward it.

One update does both jobs of GPI: the max⁡\max evaluates and improves at once, so QQ is pulled directly towards q∗q_*. Q-learning converges to q∗q_* and π∗\pi_*, whatever μ\mu is, as long as every pair (s,a)(s, a) 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:

Algorithm Q-learning

Input: a step size α∈(0,1]\alpha \in (0, 1], a small ε>0\varepsilon > 0

  • Q(s,a)Q(s, a) arbitrary, with Q(terminal,⋅)=0Q(\text{terminal}, \cdot) = 0
  • repeat for each episode
    • initialize SS
    • repeat until SS is terminal
      • choose AA in SS, ε\varepsilon-greedily with respect to QQ (the behavior policy μ\mu)
      • take the action AA; observe RR and S′S'
      • Q(S,A)←Q(S,A)+α [R+γmax⁡a′Q(S′,a′)−Q(S,A)]Q(S, A) \leftarrow Q(S, A) + \alpha\,\big[R + \gamma \max_{a'} Q(S', a') - Q(S, A)\big]
      • S←S′S \leftarrow S'
 
−1 per step, −10 for the pit · α = 0.5, γ = 1, ε-greedy
 
 
Q-learning on the same grid, with the same moves as the SARSA figure of section 1.4; only the target changes. The target reads the best entry of the next state, maxa′ Q(S′, a′), whatever is played next. On the step where the next move is a random one toward the pit, SARSA's estimate dropped to −5; Q-learning's rises to −2.5.

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 μ\mu.

After enough learning, the table becomes the answer: it is one row per state, one column per action, and Q≈q∗Q \approx q_*. The best entry of a row is then v∗(s)=max⁡aq∗(s,a)v_*(s) = \max_a q_*(s, a), and its column is the optimal action, π∗(s)=arg⁡max⁡aq∗(s,a)\pi_*(s) = \arg\max_a q_*(s, a), which we can read without any model.

Note a small drawback of the Q-table: when two entries of a row are close, say 5.25.2 and 5.05.0, a small error in QQ 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 :

SARSA or Q-learning on the cliff
Both algorithms trained with the book's settings, ε = 0.1 and α = 0.5, computed in your browser. Top: the greedy path each one has learned. Bottom: the sum of rewards per episode during training, averaged over 50 runs (Sutton and Barto, Figure 6.4). Q-learning's path is the shorter one, but its ε-greedy behavior falls off the edge from time to time: during training, SARSA collects more reward.

For once, the algorithms don’t converge to the same solution and learn two different paths:

The paradox: during training, SARSA collects more reward per episode than Q-learning (about −25-25 against −50-50 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:

SARSA or Q-learning, side by side
SARSAon-policy
bootstrap targetR + γ Q(S′, A′)A′: the action played next
learns the value ofthe ε-greedy policy it follows, exploration included
explores withthe ε-soft π it evaluates
converges tothe best ε-soft policy
needs ε → 0 for q*yes (GLIE)
in the GPI picturesmall zigzags, one per transition; with a fixed ε, they stop at the best ε-soft policy
on the cliffconservative: a safer path, away from the edge
reuses data from other policiesno
Q-learningoff-policy
bootstrap targetR + γ maxa Q(S′, a)the best action, played or not
learns the value ofthe greedy policy, whatever it plays
explores withany μ that visits every (s, a)
converges toq*, and π*
needs ε → 0 for q*no
in the GPI pictureπ stays greedy: the path follows the greedy line, in small noisy steps, to q*, π*
on the cliffaggressive: the shortest path, along the edge
reuses data from other policiesyes
Open in a new tab ↗
The two control algorithms differ by one term of their target; everything else on these cards follows from it. The GPI pictures follow the course slides: SARSA makes small zigzags between Q = qπ and its ε-greedy line and, with a fixed ε, stops at the best ε-soft policy; Q-learning keeps π greedy and follows the greedy line to q*, π*. “Compare them live” opens the course Space below the cards.
What to look at in the Space (“Compare them live”)

Run the comparison with the book’s settings, ε=0.1\varepsilon = 0.1 and α=0.5\alpha = 0.5: 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 ε\varepsilon-greedily with ε=0.1\varepsilon = 0.1 in a gridworld with 44 actions (up, right, down, left), α=0.5\alpha = 0.5 and γ=1\gamma = 1. Its current estimates are Q(s,right)=−5Q(s, \text{right}) = -5 and

uprightdownleft
Q(s′,⋅)Q(s', \cdot)−3-3−2-2−10-10−4-4

In state ss it plays right, gets R=−1R = -1 and lands in s′s'. In s′s', the ε\varepsilon-greedy policy then draws the next action A′=downA' = \text{down}: an exploratory move.

  1. With which probability does the ε\varepsilon-greedy policy play right in s′s'? down?
  2. Compute the new value of Q(s,right)Q(s, \text{right}) after a SARSA update.
  3. Same question with a Q-learning update, starting again from Q(s,right)=−5Q(s, \text{right}) = -5.
  4. Same two questions if the policy had drawn A′=rightA' = \text{right} instead. What do you notice?
  5. Suppose action selection is fully greedy (ε=0\varepsilon = 0). 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.)
  6. 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 s′s' is the one with the largest Q(s′,⋅)Q(s', \cdot). With m=4m = 4 actions, it is played with probability 1−ε+εm1 - \varepsilon + \frac{\varepsilon}{m}, each other action with εm\frac{\varepsilon}{m}.

Hint

SARSA’s target uses Q(s′,A′)Q(s', A') for the action really drawn; Q-learning’s uses max⁡aQ(s′,a)\max_a Q(s', a), 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 Q(S,A)Q(S, A)? And what if S′=SS' = S?

Checkpoint what you should get

0.9250.925 for right, 0.0250.025 for down. SARSA gives −8-8, Q-learning −4-4; with A′=rightA' = \text{right}, both give −4-4.

Solution
  1. The greedy action in s′s' is right (−2-2). With m=4m = 4: P(right)=1−ε+ε4=0.925P(\text{right}) = 1 - \varepsilon + \frac{\varepsilon}{4} = 0.925, and each other action, down included, has ε4=0.025\frac{\varepsilon}{4} = 0.025.
  2. SARSA uses the action really drawn, A′=downA' = \text{down}: target −1+Q(s′,down)=−1−10=−11-1 + Q(s', \text{down}) = -1 - 10 = -11, so Q(s,right)=−5+0.5 (−11+5)=−8Q(s, \text{right}) = -5 + 0.5\,(-11 + 5) = -8.
  3. Q-learning uses the best action in s′s': target −1+max⁡aQ(s′,a)=−1−2=−3-1 + \max_a Q(s', a) = -1 - 2 = -3, so Q(s,right)=−5+0.5 (−3+5)=−4Q(s, \text{right}) = -5 + 0.5\,(-3 + 5) = -4.
  4. With A′=rightA' = \text{right}, SARSA’s target is −1+(−2)=−3-1 + (-2) = -3: both updates give −4-4. 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.
  5. Almost, but not exactly. With ε=0\varepsilon = 0, both act greedily and both targets use max⁡aQ(S′,a)\max_a Q(S', a). The difference is the order: SARSA picks A′A' before updating Q(S,A)Q(S, A), and plays it; Q-learning updates Q(S,A)Q(S, A) first, then picks the action in S′S' with the updated QQ. When S′=SS' = S, the update can change the greedy action in S′S', and the two algorithms then select different actions and make different updates.
  6. SARSA’s targets include the −100-100 of the exploratory steps that fall off the cliff, as in question 2, so it learns that the edge is dangerous under its own ε\varepsilon-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 10%10\% 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 −8-8, Q-learning’s rose to −4-4. 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:

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 Q(s,a)Q(s, a) 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 👀🤖