Chapter 6 · Book pp. 119–140

Temporal-Difference Learning

"If one had to identify one idea as central and novel to RL, it would undoubtedly be TD learning." TD combines Monte Carlo (learn from raw experience, no model) with DP (bootstrap — update from other estimates without waiting for the final outcome).

TD(0) TD error δ Batch TD = certainty equivalence Sarsa Q-learning Expected Sarsa Double Q-learning Afterstates
Exam focus for this chapter

6.1 TD prediction

$$V(S_t) \leftarrow V(S_t) + \alpha\big[\,G_t - V(S_t)\,\big]$$
Constant-α MC (every-visit) — must wait for Gt(6.1)
$$V(S_t) \leftarrow V(S_t) + \alpha\big[\,R_{t+1} + \gamma V(S_{t+1}) - V(S_t)\,\big]$$
TD(0) / one-step TD — update on the next step(6.2)

MC target: $G_t$. TD target: $R_{t+1}+\gamma V(S_{t+1})$. TD(0) is the special case of n-step TD (Ch 7) and TD(λ) (Ch 12).

Tabular TD(0) for estimating vπon-policyno modelbootstrapsonline
Input: the policy π to be evaluated
Algorithm parameter: step size α ∈ (0, 1]
Initialize V(s), for all s ∈ S⁺, arbitrarily except that V(terminal) = 0
Loop for each episode:
    Initialize S
    Loop for each step of episode:
        A ← action given by π for S
        Take action A, observe R, S'
        V(S) ← V(S) + α [R + γ V(S') − V(S)]
        S ← S'
    until S is terminal
Three targets, three kinds of estimate
$$v_\pi(s) \doteq \E_\pi[G_t\mid S_t=s] \quad (6.3) \qquad\qquad = \E_\pi[R_{t+1}+\gamma v_\pi(S_{t+1})\mid S_t=s] \quad (6.4)$$

TD and MC updates are sample updates (one sampled successor); DP uses expected updates (full distribution of successors).

$$\delta_t \doteq R_{t+1} + \gamma V(S_{t+1}) - V(S_t)$$
TD error — the error in V(St), available only at time t+1(6.5)
$$G_t - V(S_t) = \delta_t + \gamma\delta_{t+1} + \gamma^2\delta_{t+2} + \dots + \gamma^{T-t-1}\delta_{T-1} = \sum_{k=t}^{T-1}\gamma^{k-t}\delta_k$$
MC error = discounted sum of TD errors (if V is fixed during the episode)(6.6)

Exercise 6.1 — if $V$ changes during the episode ($V_t$ used at time $t$), the identity gains a correction: $G_t - V_t(S_t) = \sum_{k=t}^{T-1}\gamma^{k-t}\delta_k + \sum_{k=t}^{T-1}\gamma^{k-t+1}\big[V_{k+1}(S_{k+1})-V_k(S_{k+1})\big]$. It is small when α is small.

Example 6.1 — driving home

StateElapsed (min)Predicted time to goPredicted total
leaving office, Friday 6:0003030
reach car, raining53540
exiting highway201535
2ndary road, behind truck301040
entering home street40343
arrive home43043

MC (α = 1) moves every prediction toward the actual outcome 43 — but only after arriving home (e.g. at "exiting highway" the error $G_t-V(S_t)=23-15=8$; with α = ½ the estimate rises by 4). TD moves each prediction toward the next prediction, immediately: changes are proportional to the temporal differences between successive predictions. If stuck in a jam 25 minutes in, TD already shifts the 30-minute estimate toward 50.

Exercise 6.2 — after moving to a new building (same highway entrance), the later states' predictions are already accurate. TD updates for the new early states bootstrap from those good estimates and learn quickly; MC must wait for full returns and absorbs all the noise of the trip. The same happens in the original scenario whenever part of the trajectory is already well-learned.

6.2 Advantages of TD prediction methods

vs.TD's advantage
DPNeeds no model of rewards or next-state distributions.
MCOnline, fully incremental: wait one step, not until episode end. Crucial for very long episodes and continuing tasks. Learns from every transition regardless of later (exploratory) actions — MC off-policy must ignore/discount such episodes.
SoundnessFor any fixed π, TD(0) converges to $v_\pi$ — in the mean for a sufficiently small constant α, and with probability 1 if α decreases per the stochastic-approximation conditions (2.7).
SpeedNo proof either is faster, but in practice TD usually converges faster than constant-α MC on stochastic tasks.

Example 6.2 — random walk

A Markov reward process (MRP — an MDP without actions): states A B C D E, start at C, move left/right with prob. ½; terminate at either end; reward +1 only on the right exit. True values: $\tfrac16,\tfrac26,\tfrac36,\tfrac46,\tfrac56$. Initial $V(s)=0.5$.

Try it: Example 6.2 — TD(0) vs constant-α MC

Values learned by TD(0), α = 0.1, single run

RMS error averaged over states and runs

Ex 6.3 — The first episode changed only V(A). What happened, and by exactly how much did it change?

The episode terminated on the left, from A. All intermediate TD errors were 0 (rewards 0, all values 0.5), so only the last transition A → terminal (value 0, reward 0) gave $\delta=0+0-0.5$. $\Delta V(A)=\alpha\delta=0.1\times(-0.5)=\mathbf{-0.05}$ (to 0.45).

Ex 6.4 — Would a wider range of α change which algorithm is better?

Unlikely. Small α makes both slow; large α makes both noisy. TD is better across the whole range, and there is no fixed α at which MC would become significantly better — MC's targets (full returns) simply have more variance.

Ex 6.5 — Why does TD's RMS error go down then up at high α?

Early updates move values toward the truth; once near it, a large constant α keeps values fluctuating with recent episodes (noise floor ∝ α), and correlated bootstrapped errors (e.g. A and E values pulled together) push RMS up again. It depends on initialisation: starting at 0.5 is already exactly right for C and close for others, which makes the early dip and later rise visible.

Ex 6.6 — Two ways to compute the true values $\frac16,\dots,\frac56$?

(1) Solve the Bellman equations $v(s)=\tfrac12v(s-1)+\tfrac12v(s+1)$ (+ boundary rewards) as a linear system, or by DP iterative policy evaluation. (2) Gambler's-ruin reasoning: probability of exiting right from position $k$ of 5 is $k/6$. (3) MC simulation. Most likely the analytical/linear-system solution — exact and cheap for 5 states.

6.3 Optimality of TD(0) — batch updating

Batch updating: with a finite amount of experience, present it repeatedly; compute the increments for every step but change V only once per pass, by their sum; repeat until convergence. Then:

Example 6.4 — you are the predictor

Eight episodes: A,0,B,0; B,1 six times; B,0 once. B was visited 8 times and returned 1 six times, so everyone agrees $V(B)=\tfrac34$. But what is $V(A)$?

Batch TD: $V(A)=\tfrac34$

100% of the time A went to B with reward 0, and B is worth ¾ ⇒ A is worth ¾. This is the answer from first modelling the process. Expected to generalise better to future data if the process is Markov.

Batch MC: $V(A)=0$

A was seen once, followed by return 0. Gives zero error on the training data — but ignores the Markov structure.

Why TD is often faster

Batch TD computes the certainty-equivalence estimate, which explains its advantage under batch training (Fig 6.2) and perhaps also non-batch TD's speed: it moves toward a better estimate. Computing certainty equivalence directly needs $O(n^2)$ memory and $O(n^3)$ computation for $n$ states; TD approximates it with $O(n)$ memory — for large state spaces TD may be the only feasible way.

Try it: Figure 6.2 — batch TD vs batch MC on the random walk

After each new episode, the batch solution is computed exactly: MC → average return after each visited state; TD → value function of the maximum-likelihood model (what batch TD(0) converges to).

Exercise 6.7 — off-policy TD(0): $V(S_t)\leftarrow V(S_t)+\alpha\rho_{t:t}\big[R_{t+1}+\gamma V(S_{t+1})-V(S_t)\big]$, with $\rho_{t:t}=\pi(A_t|S_t)/b(A_t|S_t)$.

6.4 Sarsa: on-policy TD control

Follow GPI with TD for evaluation. Learn action values $q_\pi$ by considering transitions from state–action pair to state–action pair:

$$Q(S_t,A_t)\leftarrow Q(S_t,A_t)+\alpha\big[R_{t+1}+\gamma Q(S_{t+1},A_{t+1})-Q(S_t,A_t)\big]$$
Sarsa update — uses the quintuple (S, A, R, S′, A′)(6.7)

$Q(\text{terminal},\cdot)=0$. Convergence w.p. 1 to an optimal policy and $q_*$ requires (2.7) step sizes, all pairs visited infinitely often, and the policy converging to greedy in the limit (e.g. ε-greedy with ε = 1/t) — GLIE.

Sarsa (on-policy TD control) for estimating Q ≈ q*on-policybootstrapsno model
Algorithm parameters: step size α ∈ (0, 1], small ε > 0
Initialize Q(s,a), for all s ∈ S⁺, a ∈ A(s), arbitrarily except that Q(terminal,·) = 0
Loop for each episode:
    Initialize S
    Choose A from S using policy derived from Q (e.g., ε-greedy)
    Loop for each step of episode:
        Take action A, observe R, S'
        Choose A' from S' using policy derived from Q (e.g., ε-greedy)
        Q(S,A) ← Q(S,A) + α [R + γ Q(S',A') − Q(S,A)]
        S ← S'; A ← A'
    until S is terminal

Example 6.5 — windy gridworld

7×10 grid, upward wind per column 0 0 0 1 1 1 2 2 1 0; reward −1 per step; undiscounted. ε-greedy Sarsa (ε = 0.1, α = 0.5, Q = 0). The greedy policy becomes optimal (15 steps); ε-exploration keeps the average around 17. MC cannot easily be used: termination is not guaranteed for all policies — an episode could last forever. Online methods learn during the episode that such policies are bad.

Try it: Example 6.5 and Exercises 6.9–6.10 — Sarsa on the windy gridworld
Greedy trajectory after learning

6.5 Q-learning: off-policy TD control

$$Q(S_t,A_t)\leftarrow Q(S_t,A_t)+\alpha\Big[R_{t+1}+\gamma\max_a Q(S_{t+1},a)-Q(S_t,A_t)\Big]$$
Q-learning update (Watkins, 1989)(6.8)
Q-learning (off-policy TD control) for estimating π ≈ π*off-policybootstrapsno model
Algorithm parameters: step size α ∈ (0, 1], small ε > 0
Initialize Q(s,a), for all s ∈ S⁺, a ∈ A(s), arbitrarily except that Q(terminal,·) = 0
Loop for each episode:
    Initialize S
    Loop for each step of episode:
        Choose A from S using policy derived from Q (e.g., ε-greedy)
        Take action A, observe R, S'
        Q(S,A) ← Q(S,A) + α [R + γ max_a Q(S',a) − Q(S,A)]
        S ← S'
    until S is terminal
Exercise 6.12 — with greedy action selection, are Sarsa and Q-learning identical? Almost, but not exactly. Sarsa chooses A′ before updating Q(S,A); Q-learning chooses its next action after the update. If S′ = S, the update can change which action is greedy, so the two can select different actions and make different updates.

Example 6.6 — cliff walking

4×12 grid; −1 per step; stepping into the cliff gives −100 and teleports to start. ε-greedy, ε = 0.1.

Try it: Example 6.6 — Sarsa vs Q-learning vs Expected Sarsa

6.6 Expected Sarsa

$$Q(S_t,A_t)\leftarrow Q(S_t,A_t)+\alpha\Big[R_{t+1}+\gamma\sum_a\pi(a\mid S_{t+1})Q(S_{t+1},a)-Q(S_t,A_t)\Big]$$
Expected Sarsa update(6.9)
Backup diagrams (Fig 6.4 and §6.4). Roots of the control methods are state–action pairs (solid dots).

Figure 6.3 — sensitivity to α

Interim performance (first 100 episodes) and asymptotic performance on cliff walking, ε = 0.1: Expected Sarsa is best across α and flat up to α = 1; Sarsa's asymptotic performance degrades at large α; Q-learning's online return is lowest (walks the edge).

Try it: interim performance vs α (Figure 6.3, interim curves)

6.7 Maximization bias and double learning

Control algorithms build target policies with a max (Q-learning's greedy target; ε-greedy in Sarsa). Using the max of noisy estimates as an estimate of the max of true values gives a positive bias: if all $q(s,a)=0$ but $Q(s,a)$ are noisy, $\max_aQ(s,a)>0$. This is maximization bias.

Example 6.7

From A: right → terminal, reward 0. left → B, reward 0; from B many actions all terminate with reward $\sim\mathcal N(-0.1,1)$. So left is a mistake (expected −0.1), yet Q-learning initially strongly favours it and, even asymptotically, takes it ≈5% more than optimal (ε = 0.1, α = 0.1, γ = 1).

Double learning

The problem: the same samples are used to pick the maximising action and to estimate its value. Split them: learn two independent estimates $Q_1,Q_2$; use one to pick $A^*=\argmax_aQ_1(a)$ and the other to evaluate it, $Q_2(A^*)$ — unbiased: $\E[Q_2(A^*)]=q(A^*)$. Only one estimate is updated per step: double memory, same computation per step.

$$Q_1(S_t,A_t)\leftarrow Q_1(S_t,A_t)+\alpha\Big[R_{t+1}+\gamma\,Q_2\big(S_{t+1},\argmax_aQ_1(S_{t+1},a)\big)-Q_1(S_t,A_t)\Big]$$
Double Q-learning update (with prob. ½; else swap Q₁ and Q₂)(6.10)
Double Q-learning, for estimating Q₁ ≈ Q₂ ≈ q*off-policybootstrapsunbiased max
Algorithm parameters: step size α ∈ (0, 1], small ε > 0
Initialize Q₁(s,a) and Q₂(s,a), for all s ∈ S⁺, a ∈ A(s), such that Q(terminal,·) = 0
Loop for each episode:
    Initialize S
    Loop for each step of episode:
        Choose A from S using the policy ε-greedy in Q₁ + Q₂
        Take action A, observe R, S'
        With 0.5 probability:
            Q₁(S,A) ← Q₁(S,A) + α (R + γ Q₂(S', argmax_a Q₁(S',a)) − Q₁(S,A))
        else:
            Q₂(S,A) ← Q₂(S,A) + α (R + γ Q₁(S', argmax_a Q₂(S',a)) − Q₂(S,A))
        S ← S'
    until S is terminal
Exercise 6.13 — Double Expected Sarsa (ε-greedy target): with prob. ½, $Q_1(S,A)\leftarrow Q_1(S,A)+\alpha\big[R+\gamma\sum_a\pi_1(a|S')\,Q_2(S',a)-Q_1(S,A)\big]$ where $\pi_1$ is ε-greedy w.r.t. $Q_1$; otherwise the same with 1 and 2 swapped.
Try it: Figure 6.5 — Q-learning vs Double Q-learning

6.8 Games, afterstates, and other special cases

The tic-tac-toe learner of Chapter 1 learned neither $v$ nor $q$ but an afterstate value function: values of positions after the agent's move. Useful when we know the immediate effect of our actions but not the rest of the dynamics (we know the resulting board, not the opponent's reply).

6.9 Summary — comparison of the TD control methods

MethodTargetOn/off-policyLearnsNotes
TD(0)$R+\gamma V(S')$on (prediction)$v_\pi$Prediction only
Sarsa$R+\gamma Q(S',A')$, $A'\sim\pi$on$q_\pi$ of ε-greedy π (→ $q_*$ under GLIE)Accounts for exploration ⇒ safe path on the cliff; variance from sampling $A'$
Q-learning$R+\gamma\max_aQ(S',a)$off$q_*$ regardless of behaviourOptimal path but worse online return with ε-greedy; maximization bias
Expected Sarsa$R+\gamma\sum_a\pi(a|S')Q(S',a)$on or off$q_\pi$ (greedy π ⇒ Q-learning)Lower variance than Sarsa; tolerates α = 1 in deterministic tasks; more computation
Double Q-learning$R+\gamma Q_2(S',\argmax_aQ_1(S',a))$off$q_*$Removes maximization bias; 2× memory
DPMCTD
Model neededYesNoNo
BootstrapsYesNoYes
SamplesNo (expected)YesYes
Online / step-by-step—No (end of episode)Yes
Continuing tasksYesNoYes
Target variancenoneHigh (whole return)Low (one reward + estimate)
Bias—Unbiased targetBiased target (depends on current V)
Batch solution—Min. training MSECertainty equivalence
Sensitive to non-Markov statesYesLessMore

Hyperparameters in this chapter

ParameterEffectNotes from the book
αLarge: fast but noisy; small: slow but accurate. Constant α ⇒ convergence only in the mean; decreasing per (2.7) ⇒ w.p. 1.Random walk: TD best around 0.05–0.1, MC needs smaller (0.01–0.04). Batch TD answer is independent of α. Expected Sarsa can use α = 1 in deterministic tasks; Sarsa cannot.
εExploration of the behaviour policyCauses Q-learning's cliff falls; Sarsa adapts its path to ε. Decay ε → 0 (GLIE) for convergence to optimal.
Initial Q / VStarting estimates; bias that decaysRandom walk init 0.5. Optimistic Q drives exploration (Ch 2).
γHorizon of the targetMost examples undiscounted episodic.

Self-test

Why is TD called a bootstrapping method, and why is the TD target an estimate for two reasons?

Its target uses the current estimate $V(S_{t+1})$ (bootstrapping). It samples the expectation (one transition instead of the full distribution) and it uses $V$ instead of the true $v_\pi$.

When is the TD error $\delta_t$ available, and what is it the error in?

It is the error in $V(S_t)$, but it depends on $R_{t+1}$ and $S_{t+1}$, so it is available only at time $t+1$.

Ex 6.8 — Show the action-value version of (6.6).

With $\delta_t=R_{t+1}+\gamma Q(S_{t+1},A_{t+1})-Q(S_t,A_t)$ and fixed Q: $G_t-Q(S_t,A_t)=R_{t+1}+\gamma G_{t+1}-Q(S_t,A_t)+\gamma Q(S_{t+1},A_{t+1})-\gamma Q(S_{t+1},A_{t+1})=\delta_t+\gamma(G_{t+1}-Q(S_{t+1},A_{t+1}))=\dots=\sum_{k=t}^{T-1}\gamma^{k-t}\delta_k$ (with $Q(\text{terminal},\cdot)=0$).

What does batch TD(0) converge to, and why is it often better than batch MC?

The certainty-equivalence estimate (correct values for the maximum-likelihood model). It exploits the Markov structure, so it generalises better to future data, whereas batch MC only minimises error on the training returns.

In cliff walking, which method gets higher reward per episode during learning, and which learns the optimal policy's values?

Sarsa gets higher online reward (safe path). Q-learning learns the optimal (edge) path's values, but its ε-greedy behaviour sometimes falls off the cliff.

Why can't MC be used easily on the windy gridworld?

Termination isn't guaranteed for every policy; a policy that keeps the agent in place makes an episode last forever, so MC would never get a return to learn from.

What is maximization bias? Give the fix.

Positive bias from using $\max$ of noisy estimates as an estimate of the max true value. Fix: double learning — select the argmax with one estimate and evaluate it with an independent one.

Under what condition is Expected Sarsa identical to Q-learning?

When its target policy π is greedy w.r.t. Q (while behaviour may be exploratory): $\sum_a\pi(a|S')Q(S',a)=\max_aQ(S',a)$.

Does Double Q-learning double the computation per step?

No — it doubles memory (two tables) but updates only one of them per step.

State the conditions under which Sarsa converges to the optimal policy.

Step sizes satisfy (2.7), all state–action pairs visited infinitely often, and the policy converges in the limit to greedy (e.g. ε-greedy with ε = 1/t).

What is an afterstate, and when are afterstate value functions useful?

The state immediately after the agent's action, before the environment's stochastic response. Useful when the immediate effect of actions is known (games, queuing): different (state, action) pairs with the same afterstate share one value.

Chapter quiz — check your understanding

Scored quiz: pick an answer (or type a number) to get instant feedback and an explanation. Questions marked Exam-style give you values to interpret (sweeps, logs, returns, learning curves), the way exam problems do. Your best score is saved in this browser and shown on the home page. "Shuffle & restart" re-orders the questions.