Temporal-Difference Learning
Learning a guess from a guess: TD(0) and the TD error.
Every temporal-difference update corrects one guess with a slightly better guess. That one idea learns from incomplete episodes, works in tasks that never end, usually learns faster than Monte Carlo on Markov problems, and, when data are reused, converges to a different answer from Monte Carlo's: the value of the most likely model of the world. This lesson derives TD(0), compares it with Monte Carlo and dynamic programming, and looks at what batch TD computes and where bootstrapping goes wrong.
What you’ll learn
- Derive TD(0) as a sampled, bootstrapped Bellman backup, and compute TD errors and updates by hand.
- Show that the Monte Carlo error is a discounted sum of TD errors, and compare Monte Carlo, TD and dynamic programming by sampling, bootstrapping, bias and variance.
- Reproduce the random-walk comparison of TD(0) and Monte Carlo, and explain what the first episode changes.
- Explain batch updating and certainty equivalence, and why TD's answer can be wrong when states are not Markov.
TD(0): a sampled, bootstrapped backup
The value of a policy has two equivalent definitions, and each suggests an algorithm:
Monte Carlo samples the first expectation: its target is the return . Dynamic programming computes the second expectation exactly from the model, using its current estimate in place of . Temporal-difference learning does both halves at once: it samples the second expectation, like Monte Carlo, and bootstraps from the current estimate, like dynamic programming.
import numpy as np
import gymnasium as gym
env = gym.make("FrozenLake-v1", is_slippery=True)
V = np.zeros(env.observation_space.n)
alpha, gamma = 0.05, 0.99
rng = np.random.default_rng(0)
for episode in range(20_000):
s, _ = env.reset(seed=0 if episode == 0 else None)
done = False
while not done:
a = int(rng.integers(env.action_space.n)) # evaluate the uniform random policy
s2, r, terminated, truncated, _ = env.step(a)
target = r + (0.0 if terminated else gamma * V[s2])
V[s] += alpha * (target - V[s]) # TD(0)
s, done = s2, terminated or truncatedTabular TD(0) evaluating the random policy on a slippery 4×4 lake. Note the target: it bootstraps from V[s2] unless the episode terminated. When an episode is cut off by a time limit (truncated), the state still has a future, so the correct target keeps ; treating truncation as termination silently biases the values toward zero (here, downward).
With and : , the agent receives and lands in with . What is the new ?
Show the answer
B.
, so . The reward was negative, yet the estimate rises: what matters is the reward plus the discounted value of where you landed, compared with what you expected.
TD, Monte Carlo and dynamic programming
How are the TD and Monte Carlo errors related? If is held fixed during an episode, the Monte Carlo error decomposes exactly into the TD errors along the way.
Add and subtract , using :
Unroll to the end of the episode, where and :
So a Monte Carlo update is the sum of the TD updates the episode would trigger, applied at the end instead of step by step. With TD(0) updating during the episode the identity holds only approximately; the discrepancy is small when is small.
| Property | Dynamic programming | Monte Carlo | TD(0) |
|---|---|---|---|
| Needs a model? | yes | no | no |
| Samples? | no: full expectation | yes: whole episodes | yes: one transition |
| Bootstraps? | yes | no | yes |
| Target for | |||
| Bias of the target | , deterministic | none | same as DP's, while |
| Variance of the target | none | high: every later random step | low: one random step |
| Learns online, in continuing tasks? | (sweeps, no data) | no | yes |
| Relies on the Markov property? | yes | no | yes |
The random walk
Sutton and Barto's random walk (Example 6.2): states A to E, every episode starts at C, each step goes left or right with probability ½, leaving on the right pays and on the left , and . The Bellman equations with boundary values 0 and 1 force the values onto a line: . All estimates start at 0.5.
The first episode wanders and finally leaves on the left, from A. With and every estimate at 0.5, which estimates does TD(0) change during this episode?
- Every state visited, each by
- Only , from 0.5 to 0.45
- None, because the reward was 0
- Only , because the episode started there
Show the answer
B. Only , from 0.5 to 0.45
Inside the walk the reward is 0 and both estimates are 0.5, so and nothing moves. The only nonzero TD error is on the final transition, from A to the terminal state: , so . Monte Carlo would instead have moved every visited state toward 0.
Think first Averaged over many runs, TD's RMS error at a large step size such as can fall quickly and then rise slightly before leveling off. Why would the error get worse with more data?
Split the mean squared error into squared bias plus variance. Every run starts from the same estimates (0.5), so at first there is no variance at all, only bias, and early updates remove bias fast. But a constant step keeps injecting noise, and the variance climbs from zero to its steady-state level, which is higher for larger . If that floor lies above the lowest point reached while the bias was falling, the curve dips and rises. Whether it happens depends on the initialization: starting far from the truth, the bias dominates for longer and the dip can vanish.
Batch updating and certainty equivalence
Suppose experience is scarce: a fixed set of episodes that you may replay as often as you like. In batch updating, you sweep through all the stored transitions, add up the increments each method prescribes, apply the sum, and repeat until nothing changes. For small enough both methods converge, and their limits no longer depend on . But they converge to different answers.
Batch Monte Carlo converges to the sample mean of the returns observed after each state: the values that minimize the squared error on the training returns. Batch TD(0) converges to something else.
At a fixed point of batch TD(0) the summed increments vanish in every state. With the number of stored transitions out of :
Divide by . Let be the average reward observed when leaving and the observed fraction of moves from to (terminal states have value 0):
This is the Bellman equation of the maximum-likelihood Markov model of the data. Batch TD(0) computes the exact values of that model: the certainty-equivalence estimate, so called because it treats the estimated model as if it were certainly correct. It never stores the model.
Computing the certainty-equivalence estimate directly takes memory of order for the model and up to order operations to solve it. Batch TD reaches the same answer with memory of order , and online TD heads toward it from the first transition. That is a large part of why TD often learns faster: on Markov problems it reasons as if it had estimated the full model, without paying for one. The Fixed Point lesson TD vs Monte Carlo: Certainty Equivalence works through Sutton and Barto's "You are the predictor" example and asks when this is the right answer.
Bootstrapping without the Markov property
Certainty equivalence is the right answer when the states really are Markov. When they are not, because the agent's observations merge situations whose futures differ, the maximum-likelihood "Markov model" of the data is a fiction, and batch TD computes the values of that fiction. Monte Carlo makes no such assumption: it averages what actually followed each observation.
Recall the robot from Monte Carlo Methods whose camera cannot tell two hallways apart: entered through door A, the hallway leads to ; entered through door C, a look-alike hallway leads to .
Now door A is used three times as often as door C. What do batch TD(0) and batch Monte Carlo estimate for the value of door A (, the step from a door into the hallway pays 0)?
- TD: 1, MC: 1
- TD: 0.5, MC: 1
- TD: 0.75, MC: 0.75
- TD: 0.75, MC: 1
Show the answer
D. TD: 0.75, MC: 1
The merged hallway is followed by three times out of four, so batch TD values it at 0.75 and bootstraps door A from it: . Monte Carlo averages the returns actually observed after door A, all of them . TD's error comes from the representation, not from noise, so more data will not fix it.
The same tension returns throughout the course. With function approximation, states are always partly merged by the features, and TD's fixed point can be worse than the best fit that Monte Carlo would find (Function Approximation & Deep Q-Learning). The usual compromise is not to choose but to blend: -step returns and TD() bootstrap a little later, which reduces the damage from imperfect states while keeping much of TD's variance advantage (n-Step Returns & Eligibility Traces).
Key takeaways
- TD(0) moves toward : a sample of the dynamic-programming backup, available one step later, with no model.
- With held fixed, : a Monte Carlo correction is the episode's TD corrections added up and applied at the end.
- The TD target has low variance but is biased while is wrong; tabular TD(0) still converges to under Robbins–Monro step sizes.
- Batch Monte Carlo fits the observed returns; batch TD(0) computes the values of the maximum-likelihood Markov model (certainty equivalence), which is why TD usually wins on Markov problems.
- When observations are not Markov, TD's model is a fiction and its answer is biased however much data arrives; Monte Carlo stays unbiased, and n-step methods blend the two.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
For a fixed estimate , what is the expected TD(0) target ?
- , so the target is unbiased
- , the one-step backup of the current estimate, which equals only when the errors of at the possible next states average out to zero
- , the current estimate
Show the answer
B. , the one-step backup of the current estimate, which equals only when the errors of at the possible next states average out to zero
Averaging over the action, reward and next state gives exactly the Bellman backup of . The target is therefore biased while is wrong, and the bias shrinks as approaches its fixed point .
If is held fixed during an episode, which identity holds?
- , for any
Show the answer
C.
Write and unroll; with the sum telescopes. The discount weights each later TD error by .
A fixed dataset of episodes is replayed until both methods converge. What does batch TD(0) converge to?
- The sample mean of the returns observed after each state
- The true values , exactly
- The values of the maximum-likelihood Markov model of the data: the certainty-equivalence estimate
- It does not converge without decaying step sizes
Show the answer
C. The values of the maximum-likelihood Markov model of the data: the certainty-equivalence estimate
At the batch fixed point the summed TD errors vanish in every state, which is the Bellman equation of the model with the observed average rewards and transition frequencies. The sample means of returns are what batch Monte Carlo converges to.
An episode of a continuing task is cut off by a 200-step time limit; the last state is not terminal. What should the TD target for the final transition be?
- alone, because the episode is over
- , because still has a future
- The Monte Carlo return of the whole episode
Show the answer
B. , because still has a future
Truncation is a fact about the experiment, not the environment: from the process would have continued. Bootstrapping from keeps the target unbiased for the true task. Treating the cut-off as termination teaches the agent that states near the time limit are worth less.
Go deeper
- Convergence of TD: Stochastic Approximation · Robbins–Monro conditions, the ODE method and finite-time bounds.
- TD vs Monte Carlo: Certainty Equivalence · What batch TD and batch Monte Carlo each converge to, and why TD often wins.
- TD Learning in the Brain · Dopamine neurons, reward prediction errors and the evidence for TD.
Further reading
- R. S. Sutton, "Learning to predict by the methods of temporal differences," Machine Learning 3, 9–44 (1988).
- R. S. Sutton & A. G. Barto, Reinforcement Learning: An Introduction, ch. 6 (MIT Press, 2nd ed., 2018).
- C. Szepesvári, Algorithms for Reinforcement Learning (Morgan & Claypool, 2010).