Core idea. Temporal-difference learning estimates value functions from experience by combining sampling with bootstrapping. Monte Carlo methods wait until the end of an episode and average complete returns. Dynamic programming uses a known model and backs up exact expectations. Temporal-difference methods use sampled transitions and replace the unknown future return by the current value estimate.
TD learning is not simply Monte Carlo with a shorter episode. It estimates a Bellman fixed point by noisy one-step updates. The target depends on the current value function, so the target changes during learning.
13.2.1 Interactive: TD target and TD error
The TD error is the gap between the current estimate \(V(S_t)\) and the one-step bootstrapped target \(R_{t+1}+\gamma V(S_{t+1})\). The following Plotly figure shows how the target and update change as the discount factor and current estimates vary.
13.3 10.2 The prediction problem for a fixed policy
Let \(\pi\) be fixed. The environment and policy induce a Markov reward process with transition matrix
TD learning assumes that \(P_\pi\) and \(r_\pi\) are not known, or that solving this system is not the desired computational strategy. Instead, we observe transitions
\[
S_t,R_{t+1},S_{t+1}
\]
sampled under policy \(\pi\) and update only the value of the visited state.
For a tabular value function, write \(V_t(s)\) for the estimate after \(t\) updates. TD(0) is
The Monte Carlo target is an unbiased sample of the return, conditional on \(S_t\), but can have large variance. The TD target usually has lower variance because it uses only one random reward and one random next state. However, it is biased during learning because \(V(S_{t+1})\) is only an estimate.
This creates a central tradeoff:
Method
Target
Bias during learning
Variance
Needs episode end?
Monte Carlo
\(G_t\)
low for value target
high
yes
TD(0)
\(R_{t+1}+\gamma V(S_{t+1})\)
yes
lower
no
Dynamic programming
\(r+\gamma PV\)
none if model exact
none
no
13.6.1 Interactive: Monte Carlo and TD learning curves
The following demonstration compares the typical behavior of Monte Carlo and TD estimates on a small prediction problem. Monte Carlo uses complete returns; TD uses bootstrapped one-step targets.
13.7 10.6 Learning rates and stochastic approximation
TD learning is a stochastic approximation algorithm. A generic stochastic approximation update has the form
In practice, constant learning rates are also common. A constant \(\alpha\) may not converge exactly, but it can track nonstationary environments and is often useful in continuing learning.
13.7.1 Interactive: learning-rate schedules
The next figure compares decreasing and constant learning rates. Decreasing schedules stabilize asymptotically; constant schedules keep adapting but fluctuate near the solution.
13.8 10.7 TD convergence in the tabular case
A full proof of TD convergence requires stochastic approximation theory, but the main ideas are accessible.
Assume:
the state space is finite;
the policy \(\pi\) is fixed;
the Markov chain induced by \(\pi\) visits each relevant state infinitely often;
rewards have bounded second moments;
step sizes satisfy the stochastic approximation conditions.
Then tabular TD(0) converges to \(V^\pi\) under standard ergodicity assumptions.
The fixed point is unique because \(T^\pi\) is a contraction in the sup norm:
This is why TD can learn without knowing \(P_\pi\).
13.9 10.8 TD prediction on the random walk example
A classical example uses a one-dimensional random walk with two terminal states. The nonterminal states are \(1,2,3,4,5\). From each nonterminal state, the process moves left or right with equal probability. The left terminal gives reward \(0\); the right terminal gives reward \(1\).
For \(\gamma=1\), the exact values are
\[
V^*(i)=\frac{i}{6},
\qquad i=1,2,3,4,5.
\]
Here the star denotes the true prediction target for the fixed random policy, not an optimal control value.
True values: [0.167 0.333 0.5 0.667 0.833]
After 1 episodes: [0.45 0.5 0.5 0.5 0.5 ]
After 10 episodes: [0.389 0.472 0.52 0.57 0.747]
After 50 episodes: [0.167 0.366 0.501 0.755 0.895]
After 100 episodes: [0.178 0.452 0.6 0.743 0.889]
13.9.1 Interactive: TD learning on a random walk
The figure below shows how TD estimates on the random-walk problem move toward the exact linear value function.
13.10 10.9 The TD error as a diagnostic
The TD error
\[
\delta_t=R_{t+1}+\gamma V(S_{t+1})-V(S_t)
\]
is not merely an update signal. It is also a diagnostic.
If \(V=V^\pi\), then
\[
\mathbb E[\delta_t\mid S_t=s]=0
\]
for each state \(s\). Individual TD errors need not be zero because transitions and rewards are random. However, persistent positive or negative average TD error in a state indicates that the value estimate is systematically too low or too high relative to its Bellman target.
This diagnostic is important in deep RL. Neural value functions are often trained by minimizing squared TD error. Large TD-error outliers may indicate rare transitions, reward scaling problems, poor exploration, or function-approximation instability.
13.11 10.10 Batch TD and the empirical Bellman equation
Suppose we collect a dataset of transitions
\[
\mathcal D=\{(s_i,r_i,s_i')\}_{i=1}^n.
\]
A simple batch TD objective is the empirical squared TD error
In the tabular case, minimizing this objective is not exactly the same as solving the empirical Bellman equation, because the target also depends on \(V\). This distinction becomes more important with function approximation.
For now, the key point is that TD methods transform sequential prediction into learning from one-step transitions. This is the bridge to later algorithms such as SARSA, Q-learning, actor-critic methods, and deep Q-networks.
13.12 10.11 \(n\)-step returns
TD(0) uses a one-step target. Monte Carlo uses the full return. Between them are \(n\)-step returns:
Eligibility traces give credit not only to the current state but also to recently visited states.
13.13.1 Interactive: TD(\(\lambda\)) weighting of backups
The parameter \(\lambda\) controls how much weight is placed on longer returns. The following figure shows the geometric weights on \(n\)-step returns for different values of \(\lambda\).
13.14 10.13 Python implementation of TD(\(\lambda\))
The following code implements a simple tabular TD(\(\lambda\)) update for the random-walk example.
import numpy as nprng = np.random.default_rng(6241)n_states =5terminal_left =0terminal_right = n_states +1gamma =1.0alpha =0.05lam =0.8V = np.full(n_states +2, 0.5)V[terminal_left] =0.0V[terminal_right] =0.0def td_lambda_episode(V, alpha, lam): e = np.zeros_like(V) s =3while s notin [terminal_left, terminal_right]: s_next = s + rng.choice([-1, 1]) reward =1.0if s_next == terminal_right else0.0 delta = reward + gamma * V[s_next] - V[s] e *= gamma * lam e[s] +=1.0 V += alpha * delta * e V[terminal_left] =0.0 V[terminal_right] =0.0 s = s_nextfor _ inrange(200): td_lambda_episode(V, alpha, lam)print("TD(lambda) values:", np.round(V[1:-1], 3))print("True values: ", np.round(np.arange(1, n_states +1) /6, 3))
The word semi-gradient is important. The TD target depends on \(\theta_t\), but the update treats the target as fixed when differentiating with respect to \(V_\theta(S_t)\). This idea becomes central in Chapter 13.
13.16 10.15 AI component: using an AI assistant to audit TD code
TD algorithms are short, but they are easy to implement incorrectly. A useful AI workflow is to ask an assistant to check the following issues:
Is the TD target computed before or after updating \(V(S_t)\)?
Are terminal values handled correctly?
Is the reward associated with the transition \(S_t\to S_{t+1}\)?
Is the learning rate constant, state-dependent, or time-dependent?
Is the experiment episodic or continuing?
Is the code accidentally using the exact model when it claims to be model-free?
Are random seeds and evaluation metrics reported clearly?
A good prompt is:
I am implementing tabular TD(0) for a fixed-policy Markov reward process. Please check whether my TD target, terminal-state handling, learning-rate schedule, and evaluation metric are mathematically consistent. Do not rewrite the whole code. First list possible conceptual errors.
Warning
AI tools often describe TD as minimizing a supervised regression loss. That explanation is incomplete. TD targets depend on the current value estimate, so TD is better understood first as stochastic approximation to a Bellman fixed point.
13.17 10.16 Summary
Temporal-difference learning is one of the central ideas of reinforcement learning. It combines the sampling viewpoint of Monte Carlo methods with the Bellman fixed-point viewpoint of dynamic programming.
is a sampled Bellman residual. In expectation, it points toward the Bellman fixed point. This idea will be reused immediately in SARSA and Q-learning, and later in actor-critic and deep reinforcement learning.
13.18 Conceptual exercises
Explain why TD(0) can update before an episode terminates, while ordinary Monte Carlo prediction cannot.
Describe the bias-variance tradeoff between Monte Carlo and TD learning.
In what sense is TD a model-free method? In what sense does it still rely on the Markov property?
Why is the TD target not a fixed label in the same way as a supervised-learning target?
Explain how the TD error can be used as a diagnostic for value-function quality.
13.19 Mathematical exercises
Let \(T^\pi\) be the Bellman expectation operator. Prove that \(T^\pi\) is a contraction in \(\|\cdot\|_\infty\) when \(0\leq\gamma<1\).
Show that if \(V=V^\pi\), then \(\mathbb E[\delta_t\mid S_t=s]=0\) for every state \(s\).
For a two-state Markov reward process, write the TD(0) expected update explicitly and identify its fixed point.
Derive the \(n\)-step return formula recursively.
Show that the weights \((1-\lambda)\lambda^{n-1}\) sum to \(1\) for \(0\leq\lambda<1\).
Derive the semi-gradient TD update for \(V_\theta(s)=\phi(s)^T\theta\).
13.20 Computational exercises
Implement TD(0) on the random-walk problem and compare several learning rates.
Compare Monte Carlo prediction and TD(0) using root mean squared error against the exact value function.
Modify the random-walk example so the right terminal reward is \(2\) instead of \(1\). Predict and verify the new exact value function.
Implement \(n\)-step TD for \(n=1,2,4,8\) and compare learning curves.
Implement TD(\(\lambda\)) for \(\lambda=0,0.4,0.8,1.0\) and compare empirical performance.
Record TD errors during training and plot their moving average by state.
13.21 AI-assisted exercises
Ask an AI assistant to explain TD(0), then identify whether the explanation correctly distinguishes the TD target from the Monte Carlo return.
Give an AI assistant a TD implementation with one intentional bug in terminal-state handling. Ask it to find the bug and explain the mathematical consequence.
Ask an AI assistant to design a Monte Carlo versus TD experiment. Critique whether the proposed comparison uses fair learning rates and evaluation metrics.
Use an AI assistant to generate a small MRP. Then compute the exact value function yourself and verify whether the proposed TD code converges to it.
Ask for an explanation of TD(\(\lambda\)) in both forward-view and backward-view language. Check whether the weights and eligibility trace equations are consistent.
13.22 Instructor notes
This chapter should be taught as the transition from averaging complete returns to learning Bellman fixed points from sampled transitions. Students with statistics backgrounds often understand the sample-average view quickly, but TD requires a new idea: the target is itself changing because it uses the current estimate. Emphasize the conditional expectation of the TD error and the relationship between TD and stochastic approximation.
A good classroom sequence is:
compare MC and TD targets on one trajectory;
derive the expected TD update;
run the random-walk example;
discuss learning rates;
introduce \(n\)-step returns and TD(\(\lambda\)) as the bridge between MC and TD.