Simple Algorithm
Reinforcement Learning · Bootstrapping · 22 min

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:

Vπ(s)=Eπ[Gt∣St=s]=Eπ[Rt+1+γVπ(St+1)∣St=s].V^\pi(s) = \E_\pi\big[G_t \mid S_t = s\big] = \E_\pi\big[R_{t+1} + \gamma V^\pi(S_{t+1}) \mid S_t = s\big].

Monte Carlo samples the first expectation: its target is the return GtG_t. Dynamic programming computes the second expectation exactly from the model, using its current estimate in place of VπV^\pi. 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.

V(St)←V(St)+α δt,δt=Rt+1+γV(St+1)−V(St)V(S_t) \leftarrow V(S_t) + \alpha\,\delta_t,\qquad \delta_t = R_{t+1} + \gamma V(S_{t+1}) - V(S_t)
TD(0). The TD error δt\delta_t is available one step after StS_t is visited, so the update happens online, within the episode. By convention V=0V = 0 at terminal states.
python
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 truncated

Tabular 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 s2s_2 still has a future, so the correct target keeps γV(s2)\gamma V(s_2); treating truncation as termination silently biases the values toward zero (here, downward).

Check your understanding

With γ=0.9\gamma = 0.9 and α=0.5\alpha = 0.5: V(s)=2V(s) = 2, the agent receives R=−1R = -1 and lands in s′s' with V(s′)=4V(s') = 4. What is the new V(s)V(s)?

  1. 1.51.5
  2. 2.32.3
  3. 2.52.5
  4. 2.62.6
Show the answer

B. 2.32.3

δ=−1+0.9×4−2=0.6\delta = -1 + 0.9 \times 4 - 2 = 0.6, so V(s)←2+0.5×0.6=2.3V(s) \leftarrow 2 + 0.5 \times 0.6 = 2.3. 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 VV is held fixed during an episode, the Monte Carlo error decomposes exactly into the TD errors along the way.

DerivationThe Monte Carlo error is a sum of TD errors
  1. Gt−V(St)=Rt+1+γV(St+1)−V(St)⏟δt+γ(Gt+1−V(St+1))G_t - V(S_t) = \underbrace{R_{t+1} + \gamma V(S_{t+1}) - V(S_t)}_{\delta_t} + \gamma\big(G_{t+1} - V(S_{t+1})\big)

    Add and subtract γV(St+1)\gamma V(S_{t+1}), using Gt=Rt+1+γGt+1G_t = R_{t+1} + \gamma G_{t+1}:

  2. Gt−V(St)=∑k=tT−1γk−t δkG_t - V(S_t) = \sum_{k=t}^{T-1}\gamma^{k-t}\,\delta_k

    Unroll to the end of the episode, where GT=0G_T = 0 and V(ST)=0V(S_T) = 0:

  3. 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 VV during the episode the identity holds only approximately; the discrepancy is small when α\alpha is small.

PropertyDynamic programmingMonte CarloTD(0)
Needs a model?yesnono
Samples?no: full expectationyes: whole episodesyes: one transition
Bootstraps?yesnoyes
Target for V(St)V(S_t)∑aπ(a∣s)[r(s,a)+γ∑s′P(s′∣s,a)V(s′)]\sum_a\pi(a \mid s)\big[r(s,a) + \gamma\sum_{s'}P(s' \mid s,a)V(s')\big]GtG_tRt+1+γV(St+1)R_{t+1} + \gamma V(S_{t+1})
Bias of the target(TπV)(s)−Vπ(s)(\mathcal T^\pi V)(s) - V^\pi(s), deterministicnonesame as DP's, while V≠VπV \ne V^\pi
Variance of the targetnonehigh: every later random steplow: one random step
Learns online, in continuing tasks?(sweeps, no data)noyes
Relies on the Markov property?yesnoyes
The TD target is a sample of the dynamic-programming backup: E[Rt+1+γV(St+1)∣St=s]=(TπV)(s)\E\big[R_{t+1} + \gamma V(S_{t+1}) \mid S_t = s\big] = (\mathcal T^\pi V)(s). It inherits DP's bias toward the current estimate and replaces the model by one sampled transition.

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 +1+1 and on the left 00, and γ=1\gamma = 1. The Bellman equations V(k)=12V(k−1)+12V(k+1)V(k) = \tfrac12V(k-1) + \tfrac12V(k+1) with boundary values 0 and 1 force the values onto a line: 16,26,…,56\tfrac16, \tfrac26, \dots, \tfrac56. All estimates start at 0.5.

Check your understanding

The first episode wanders and finally leaves on the left, from A. With α=0.1\alpha = 0.1 and every estimate at 0.5, which estimates does TD(0) change during this episode?

  1. Every state visited, each by −0.05-0.05
  2. Only V(A)V(A), from 0.5 to 0.45
  3. None, because the reward was 0
  4. Only V(C)V(C), because the episode started there
Show the answer

B. Only V(A)V(A), from 0.5 to 0.45

Inside the walk the reward is 0 and both estimates are 0.5, so δ=0+0.5−0.5=0\delta = 0 + 0.5 - 0.5 = 0 and nothing moves. The only nonzero TD error is on the final transition, from A to the terminal state: δ=0+0−0.5=−0.5\delta = 0 + 0 - 0.5 = -0.5, so V(A)←0.5−0.05=0.45V(A) \leftarrow 0.5 - 0.05 = 0.45. 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 α=0.15\alpha = 0.15 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 α\alpha. 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 α\alpha both methods converge, and their limits no longer depend on α\alpha. 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.

DerivationWhat batch TD(0) converges to
  1. ∑i: si=s(ri+γV(si′)−V(s))=0for every s\sum_{i:\,s_i = s}\big(r_i + \gamma V(s'_i) - V(s)\big) = 0\quad\text{for every } s

    At a fixed point of batch TD(0) the summed increments vanish in every state. With N(s)N(s) the number of stored transitions out of ss:

  2. V(s)=r^(s)+γ∑s′P^(s′∣s) V(s′)V(s) = \hat r(s) + \gamma\sum_{s'}\hat P(s' \mid s)\,V(s')

    Divide by N(s)N(s). Let r^(s)\hat r(s) be the average reward observed when leaving ss and P^(s′∣s)=N(s,s′)/N(s)\hat P(s' \mid s) = N(s, s')/N(s) the observed fraction of moves from ss to s′s' (terminal states have value 0):

  3. 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 ∣S∣2\abs{\mathcal S}^2 for the model and up to order ∣S∣3\abs{\mathcal S}^3 operations to solve it. Batch TD reaches the same answer with memory of order ∣S∣\abs{\mathcal S}, 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 +1+1; entered through door C, a look-alike hallway leads to 00.

Check your understanding

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 (γ=1\gamma = 1, the step from a door into the hallway pays 0)?

  1. TD: 1, MC: 1
  2. TD: 0.5, MC: 1
  3. TD: 0.75, MC: 0.75
  4. TD: 0.75, MC: 1
Show the answer

D. TD: 0.75, MC: 1

The merged hallway is followed by +1+1 three times out of four, so batch TD values it at 0.75 and bootstraps door A from it: V(A)=0+0.75V(A) = 0 + 0.75. Monte Carlo averages the returns actually observed after door A, all of them +1+1. 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: nn-step returns and TD(λ\lambda) 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 V(St)V(S_t) toward Rt+1+γV(St+1)R_{t+1} + \gamma V(S_{t+1}): a sample of the dynamic-programming backup, available one step later, with no model.
  • With VV held fixed, Gt−V(St)=∑kγk−tδkG_t - V(S_t) = \sum_k\gamma^{k-t}\delta_k: 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 VV is wrong; tabular TD(0) still converges to VπV^\pi 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.

Question 1

For a fixed estimate VV, what is the expected TD(0) target E[Rt+1+γV(St+1)∣St=s]\E\big[R_{t+1} + \gamma V(S_{t+1}) \mid S_t = s\big]?

  1. Vπ(s)V^\pi(s), so the target is unbiased
  2. (TπV)(s)(\mathcal T^\pi V)(s), the one-step backup of the current estimate, which equals Vπ(s)V^\pi(s) only when the errors of VV at the possible next states average out to zero
  3. V(s)V(s), the current estimate
  4. E[Gt∣St=s]\E[G_t \mid S_t = s]
Show the answer

B. (TπV)(s)(\mathcal T^\pi V)(s), the one-step backup of the current estimate, which equals Vπ(s)V^\pi(s) only when the errors of VV at the possible next states average out to zero

Averaging over the action, reward and next state gives exactly the Bellman backup of VV. The target is therefore biased while VV is wrong, and the bias shrinks as VV approaches its fixed point VπV^\pi.

Question 2

If VV is held fixed during an episode, which identity holds?

  1. Gt−V(St)=δtG_t - V(S_t) = \delta_t
  2. Gt−V(St)=∑k=tT−1δkG_t - V(S_t) = \sum_{k=t}^{T-1}\delta_k, for any γ\gamma
  3. Gt−V(St)=∑k=tT−1γk−t δkG_t - V(S_t) = \sum_{k=t}^{T-1}\gamma^{k-t}\,\delta_k
  4. Gt=∑k=tT−1γk−t δkG_t = \sum_{k=t}^{T-1}\gamma^{k-t}\,\delta_k
Show the answer

C. Gt−V(St)=∑k=tT−1γk−t δkG_t - V(S_t) = \sum_{k=t}^{T-1}\gamma^{k-t}\,\delta_k

Write Gt−V(St)=δt+γ(Gt+1−V(St+1))G_t - V(S_t) = \delta_t + \gamma(G_{t+1} - V(S_{t+1})) and unroll; with GT=V(ST)=0G_T = V(S_T) = 0 the sum telescopes. The discount weights each later TD error by γk−t\gamma^{k-t}.

Question 3

A fixed dataset of episodes is replayed until both methods converge. What does batch TD(0) converge to?

  1. The sample mean of the returns observed after each state
  2. The true values VπV^\pi, exactly
  3. The values of the maximum-likelihood Markov model of the data: the certainty-equivalence estimate
  4. 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.

Question 4

An episode of a continuing task is cut off by a 200-step time limit; the last state S200S_{200} is not terminal. What should the TD target for the final transition be?

  1. R200R_{200} alone, because the episode is over
  2. R200+γV(S200)R_{200} + \gamma V(S_{200}), because S200S_{200} still has a future
  3. 00
  4. The Monte Carlo return of the whole episode
Show the answer

B. R200+γV(S200)R_{200} + \gamma V(S_{200}), because S200S_{200} still has a future

Truncation is a fact about the experiment, not the environment: from S200S_{200} the process would have continued. Bootstrapping from V(S200)V(S_{200}) 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

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).