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) update (6.2) and TD error (6.5); MC error as a sum of TD errors (6.6).
- Why the TD target is an estimate "for two reasons" — sampling and bootstrapping.
- Advantages of TD over MC and DP; convergence conditions.
- Batch MC (minimises training MSE) vs batch TD (certainty-equivalence / max-likelihood model) — the "You are the predictor" example.
- Sarsa vs Q-learning vs Expected Sarsa: targets, on/off-policy, cliff walking behaviour, variance.
- Maximization bias and Double Q-learning.
- Backup diagrams for TD(0), Sarsa, Q-learning, Expected Sarsa.
6.1 TD prediction
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).
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
- MC estimates (6.3): uses a sample return because the expectation is unknown.
- DP estimates (6.4): the expectation is computed exactly from the model, but $v_\pi(S_{t+1})$ is unknown → uses the current estimate $V(S_{t+1})$ (bootstrap).
- TD is an estimate for both reasons: it samples the expectation in (6.4) and uses the current estimate $V$ instead of $v_\pi$.
TD and MC updates are sample updates (one sampled successor); DP uses expected updates (full distribution of successors).
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
| State | Elapsed (min) | Predicted time to go | Predicted total |
|---|---|---|---|
| leaving office, Friday 6:00 | 0 | 30 | 30 |
| reach car, raining | 5 | 35 | 40 |
| exiting highway | 20 | 15 | 35 |
| 2ndary road, behind truck | 30 | 10 | 40 |
| entering home street | 40 | 3 | 43 |
| arrive home | 43 | 0 | 43 |
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 |
|---|---|
| DP | Needs no model of rewards or next-state distributions. |
| MC | Online, 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. |
| Soundness | For 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). |
| Speed | No 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$.
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:
- Batch TD(0) converges deterministically to a single answer independent of α (if α small enough). Batch constant-α MC also converges — to a different answer.
- Batch MC → sample averages of observed returns: minimises mean-square error on the training set.
- Batch TD → the certainty-equivalence estimate: the value function that would be exactly correct for the maximum-likelihood model of the Markov process (transition probabilities = observed fractions, rewards = observed averages).
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.
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.
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(\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.
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.
6.5 Q-learning: off-policy TD control
- $Q$ directly approximates $q_*$, independent of the policy being followed — simplifies analysis; early convergence proofs.
- The behaviour policy still matters: it determines which pairs are visited. Requirement for convergence: all pairs continue to be updated (+ step-size conditions) ⇒ $Q\to q_*$ w.p. 1.
- Off-policy (Ex 6.11): target policy is greedy (the max), behaviour is ε-greedy — and no importance sampling is needed because the target bootstraps from $\max_a Q(S',a)$ rather than a sampled next action.
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
Example 6.6 — cliff walking
4×12 grid; −1 per step; stepping into the cliff gives −100 and teleports to start. ε-greedy, ε = 0.1.
- Q-learning learns the values of the optimal path along the cliff edge — but, because of ε-greedy exploration, occasionally falls off ⇒ worse online performance.
- Sarsa takes its own exploration into account and learns the longer safer path ⇒ better online reward.
- If ε were gradually reduced, both would converge to the optimal policy.
6.6 Expected Sarsa
- Moves deterministically in the direction Sarsa moves in expectation ⇒ eliminates the variance due to random selection of $A_{t+1}$. More computation per step; generally performs better than Sarsa.
- In cliff walking (deterministic transitions; all randomness from the policy) Expected Sarsa can use α = 1 without degrading asymptotic performance; Sarsa only does well long-run at small α (where short-term performance is poor).
- Can be on- or off-policy. If π is greedy while behaviour is exploratory, Expected Sarsa is exactly Q-learning — it subsumes and generalises Q-learning while reliably improving over Sarsa.
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).
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).
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.
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
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).
- More efficient: many (position, move) pairs lead to the same afterstate and must have the same value; an action-value function would learn them separately, an afterstate function shares learning instantly.
- Also arises in queuing (assigning/rejecting customers): actions are defined by their known immediate effects.
- Exercise 6.14 — Jack's car rental: the afterstate is the number of cars at each location after the overnight move. Many (state, action) pairs lead to the same morning configuration — e.g. (10 cars, 5 cars) moving 1 car to the second location and (9, 6) moving none both give (9, 6) — so they share one value ⇒ fewer values to learn and faster convergence.
6.9 Summary — comparison of the TD control methods
| Method | Target | On/off-policy | Learns | Notes |
|---|---|---|---|---|
| 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 behaviour | Optimal 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 |
| DP | MC | TD | |
|---|---|---|---|
| Model needed | Yes | No | No |
| Bootstraps | Yes | No | Yes |
| Samples | No (expected) | Yes | Yes |
| Online / step-by-step | — | No (end of episode) | Yes |
| Continuing tasks | Yes | No | Yes |
| Target variance | none | High (whole return) | Low (one reward + estimate) |
| Bias | — | Unbiased target | Biased target (depends on current V) |
| Batch solution | — | Min. training MSE | Certainty equivalence |
| Sensitive to non-Markov states | Yes | Less | More |
Hyperparameters in this chapter
| Parameter | Effect | Notes 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 policy | Causes Q-learning's cliff falls; Sarsa adapts its path to ε. Decay ε → 0 (GLIE) for convergence to optimal. |
| Initial Q / V | Starting estimates; bias that decays | Random walk init 0.5. Optimistic Q drives exploration (Ch 2). |
| γ | Horizon of the target | Most 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.