Chapter 05 · Part 2: Learning values
TD learning as bootstrapping
Temporal-difference learning swaps an unbiased, noisy Monte Carlo return for a biased, steadier target built from the current estimate, and n-step returns tune that trade.
Chapter 4 estimated with a sample mean of observed returns. That estimator is unbiased (first-visit) and its error shrinks like , but each return carries the randomness of every step until the episode ends. A return from a 100-step episode adds up 100 noisy rewards and 100 random transitions, and all of that noise is the price of one observation. The question for this chapter: can we spend less variance per observation, and what do we pay for it?
The answer is to stop waiting for the end of the episode. After one step we already hold a guess, , for the value of everything that happens next. Using that guess in place of the tail is called bootstrapping, a word borrowed from the statistician's bootstrap only in spirit: the estimate is pulled up by its own estimates. The resulting method is temporal-difference (TD) learning (Sutton, 1988). Throughout we use as in chapter 1 and evaluate a fixed policy , so is suppressed from the notation of the data-generating process.
What does the TD(0) update do?
Recall the incremental form of a sample mean from chapter 4. After observing a return from state , a step size gives
With this is exactly the running average; with constant it is an exponentially weighted average. The Monte Carlo update has to wait for . The TD(0) update uses the one-step TD target instead:
where is the TD error from the notation page. It can be applied after every transition, in the middle of an episode, and works for continuing tasks.
A tiny numerical case. Suppose , we observe and land in with , , . Then and . Nothing about the end of the episode was needed.
Why should this converge? Stochastic approximation
Define the Bellman operator for the policy, . Chapter 1 showed that is its fixed point, (that is the Bellman equation, the law of total expectation applied to ). Finding is therefore a root-finding problem, , in which we can only observe with noise: the TD error has conditional mean given the current and .
This is the setting of Robbins and Monro (1951): find the root of a function that can only be measured through noisy responses with , by iterating . Their step-size conditions, in the form used ever since, are
The first lets the iterates travel any distance needed; the second makes the accumulated noise, whose variance is proportional to , finite. The sample mean is the simplest case. With the recursion reproduces , and diverges while converges. A constant violates the second condition: the estimate never settles, it keeps fluctuating around the target with variance of order for iid noise of variance . That is the bias–variance trade of a constant step size that chapter 4 met as exponential smoothing.
For tabular TD(0), each state has its own count and step size, every state must be visited infinitely often, and the conditions hold per state. Sutton (1988) proved convergence of the expected values for TD(0) on absorbing Markov chains; almost-sure convergence follows from stochastic-approximation theory, and Sutton and Barto's textbook (2018, chapter 6) gives the details and references. The statistical content is: TD(0) is a Robbins–Monro procedure for a fixed point, with the next-state estimate standing in for the unknown tail.
Why is the TD target biased, and why does it have lower variance?
Fix a state and a current estimate . Compare the two measurements of :
- the return , with ;
- the TD target .
Bias. Because ,
The bias of the target at is times the average error of the estimate at the successor states. It vanishes when and is carried backward one step at a time. Note this is bias in the measurement conditional on the current ; the final estimator is a different object and its bias decays as the successors improve.
Variance. Take the favourable case , so the target is unbiased, and decompose with the law of total variance, conditioning on the first transition :
Here I used , which is the Markov property at work. The first term is nonnegative, so , with the gap equal to the discounted expected variance of the whole future. The target is the return with its random tail replaced by the tail's conditional mean: this is the Rao–Blackwell idea, and conditioning never increases variance. The difference is that the conditional mean is not known and has to be estimated, which is where the bias enters.
When the target's variance is for the current ; its mean squared error about is bias plus that variance, so
TD wins whenever the squared error of at the successors is smaller than the variance it saves. Early on, with initialised arbitrarily, the bias term can dominate; later, the variance term does.
A worked example by hand
Take a symmetric random walk on states with exits at and ; from each state, move left or right with probability ; reward on reaching , otherwise; . The return from any state is if the walk exits on the right and otherwise, so with (gambler's ruin). Take :
- and .
- With the exact values, the TD target is , and equally likely, so . Mean , variance .
The target is unbiased and its variance is one hundredth of the return's. The experiment below confirms both by simulation. If instead , the target is with certainty: variance , bias . Bootstrapping from a bad estimate trades all the variance for all the bias.
What is the -step return, and what does do?
Between one step and the whole episode there is a family of targets. The -step return uses real rewards and then bootstraps:
For this is the TD target, and once reaches the end of the episode it is the Monte Carlo return. The same argument as above gives
The bias is multiplied by and the estimation error is evaluated steps ahead. With the factor does not shrink, but the estimate at states further from where we are learning has often had more time to improve, and in episodic tasks the target eventually reaches terminal states, where is exact. The variance has rewards and transitions in it: when the increments behave roughly like independent draws, it grows about linearly in until it saturates at .
The -return averages all -step returns with geometric weights, :
(in an episodic task, the weight on values beyond the end of the episode goes to the full return). It is a convex combination of the dial settings, so its bias is the weighted average of their biases and is TD(0), is Monte Carlo. Its practical appeal, via eligibility traces, is that it can be computed online without storing steps; Sutton and Barto's chapters 7 and 12 cover both. Chapter 8 meets the same dial again as generalised advantage estimation.
What is known theoretically about the dial?
Kearns and Singh (2000) give upper bounds on the error of TD updates with -step backups or parameter , as a function of the number of trajectories, for any MDP, in an analysed "phased" variant where each phase averages fresh trajectories per state (so the step-size randomness is removed). Their bounds are sums of terms that grow with or (more reward noise) and terms that shrink with or (less reliance on the current estimate). They predict that larger or gives faster convergence to a higher asymptotic error floor, that for a fixed number of trajectories an intermediate value is best, and that a schedule which decreases or over time can beat any fixed value. These are upper bounds, not exact errors, and their analysis is for the phased scheme; but the experiment below shows the U-shape they predict.
What do the numbers say about the dial? An experiment
The script ch05_td.py runs three things. First, the variance check at one state from the worked example. Second, the main experiment: 19-state random walk as above, initialised to , online -step TD, a fixed budget of 10 episodes, and then the estimate at the end of those 10 episodes is compared with the true . This is repeated over 1000 independent runs (all configurations reuse the same simulated episodes, so comparisons between and are paired). At each state we compute and across runs, and average over the 19 states, so that holds exactly. "MC" is constant- every-visit Monte Carlo. Third, certainty equivalence, discussed in the next section.
1. Variance of the target at state s=10 (V exact, true v=0.500)
exact simulated
Var(G) = v(1-v) 0.2500 0.2500
Var(R+V(S')) = 1/400 0.0025 0.0025
mean of G 0.5000 0.5004
mean of R+V(S') 0.5000 0.5000
2. 19-state random walk, 10 episodes, 1000 independent runs
Quantities are averaged over the 19 states; V0 = 0; truth v(s) = s/20.
bias^2, variance, MSE at alpha = 0.2
n bias^2 variance MSE bias/var
1 0.24821 0.00170 0.24990 146.36
2 0.18609 0.00354 0.18963 52.59
4 0.10661 0.00781 0.11442 13.65
8 0.03933 0.01508 0.05441 2.61
16 0.00977 0.02707 0.03684 0.36
32 0.00344 0.04782 0.05126 0.07
64 0.00178 0.07580 0.07757 0.02
MC 0.00129 0.10956 0.11085 0.01
MSE by n (rows) and alpha (columns)
n 0.05 0.10 0.20 0.30 0.40 0.60 best alpha
1 0.30229 0.28302 0.24990 0.22162 0.19708 0.15785 0.60
2 0.28158 0.24633 0.18963 0.14582 0.11233 0.07147 0.60
4 0.24580 0.18896 0.11442 0.07323 0.05251 0.04386 0.60
8 0.19131 0.11790 0.05441 0.03791 0.03778 0.05200 0.40
16 0.12752 0.06227 0.03684 0.04297 0.05377 0.07576 0.20
32 0.07959 0.04482 0.05126 0.06760 0.08195 0.10400 0.10
64 0.06389 0.05612 0.07757 0.09674 0.11090 0.13049 0.10
MC 0.07984 0.08714 0.11085 0.12743 0.13891 0.15429 0.05
best MSE over alpha, with its bias^2 and variance
n alpha bias^2 variance MSE
1 0.60 0.14892 0.00893 0.15785
2 0.60 0.05504 0.01642 0.07147
4 0.60 0.01913 0.02473 0.04386
8 0.40 0.01059 0.02719 0.03778
16 0.20 0.00977 0.02707 0.03684
32 0.10 0.01742 0.02740 0.04482
64 0.10 0.00962 0.04651 0.05612
MC 0.05 0.02766 0.05218 0.07984
3a. Sutton & Barto A/B example: 8 episodes (A,0,B,0), 6 x (B,1), (B,0)
V(A) V(B)
batch MC (mean return) 0.0000 0.7500
batch TD(0), iterated 0.7500 0.7500
ML model, solved exactly 0.7500 0.7500
3b. 5-state random walk, RMS error over states, mean of 500 runs
episodes batch MC batch TD
1 0.4005 0.4005
2 0.3547 0.2966
5 0.2479 0.1767
10 0.1857 0.1266
25 0.1099 0.0758
50 0.0791 0.0541Part 1: the variance gap. The return at state 10 has variance and the one-step target has (simulated values agree to four decimals), and both are centred on .
Part 2: bias, variance and MSE of the estimator. A caution about what "bias" means in this table. The estimator is after 10 episodes, started from while the truth runs from to . Bias here is dominated by the initial error not yet having propagated. A one-step method moves information one state per visit, so after 10 episodes the far-from-exit states are still near zero. That is the bias of TD(0) as a learning procedure, a different (and more practically relevant) thing than the one-step bias of a target computed from a fixed , though they have the same cause.
At the pattern is clean. Squared bias falls monotonically with ( at to for MC); variance rises monotonically ( to ); MSE is U-shaped with a minimum at (). Monte Carlo has three times the MSE of the best , almost all of it variance, and 1-step TD has seven times, almost all of it bias.
The MSE table across step sizes adds a second dial. Large speeds up learning (less initialisation bias) but amplifies noise (variance), so the best falls as grows: for , at , at , at , and for MC. Two of those winners sit at the edge of the grid ( for and for MC), so the true optimum for might be at a larger and for MC at a smaller one; those rows are upper bounds on what tuning could achieve. Tuned over , intermediate ( or ) still gives the lowest MSE ( and ), about half that of tuned MC () and under a quarter of tuned 1-step TD ().
Three honest limits. The optimum depends on the budget: with 100 episodes instead of 10, the initialisation bias would shrink and the best would move down (try it in the exercises). It depends on the problem: here rewards are sparse and the variance in is large. And "bias" in this experiment includes the initial value; started from the small- methods would look better.
What does a fixed batch of data say? Certainty equivalence
Suppose we stop collecting data and have a fixed batch of episodes. Repeatedly sweep through the batch and apply the TD(0) increments summed over the whole batch (small ) until stops changing; do the same with Monte Carlo increments. What do the two procedures converge to?
Batch Monte Carlo converges, in the tabular case, to the sample average of the observed returns from each state. Equivalently, it minimises the squared error on the training returns,
which is a one-way ANOVA: a separate mean per state, with no structure shared between states.
Batch TD(0) converges (for small enough) to the value of the model fitted by maximum likelihood. Count the transitions in the batch: and , the mean reward observed leaving (with terminals as absorbing states of value zero). The batch TD fixed point solves
which is exactly the value of the policy in the estimated Markov chain: . This property is called certainty equivalence: act as if the estimated model were the truth. It is shown in Sutton and Barto (2018), section 6.3; the TD(0) increments sum to zero precisely at this equation, which is the reason.
The A/B example by hand
The classic case from Sutton and Barto: a two-state process with no discounting, observed in eight episodes. States are and ; each line is the sequence "state, reward received on leaving it":
- one episode: ;
- six episodes: ;
- one episode: .
Batch Monte Carlo. was visited in all eight episodes, with returns , so . was visited once, with return , so . This fits the training returns perfectly (zero squared error at ).
Batch TD(0). The data say always goes to with reward (, ), and from the episode terminates with mean reward . So and .
Which is right? If the process is Markov, then everything we know about the future from passes through , we have eight observations about and only one about , and is the better estimate: one observation of ending in is not strong evidence against being as good as . If, however, there is something about that is not captured by the state (non-Markov), then the single observation is the only evidence of it. This is the statistician's choice between a model-based and a model-free estimator, and the data cannot settle it by themselves. The script computes all three versions of the answer: batch MC, TD(0) swept to convergence, and the ML model solved as a linear system; the last two agree.
The results in the output above (section 3a) match the by-hand calculation. Part 3b measures what the difference is worth on a Markov problem: the 5-state random walk starting from the middle state, with RMS error over the five states after episodes, mean of 500 independent runs. After a single episode both methods agree (every visited state's observed return equals the outcome, and the ML model also routes everything to that exit). From two episodes on, batch TD has lower error, by about 16% at two episodes and about 30% from five episodes on: against after 10 episodes, against after 50. Both go to zero as data accumulate; the model-based one gets there faster because the walk really is Markov.
Exercises
- Step sizes. Show that satisfies the Robbins–Monro conditions and gives the sample mean. For , for which do both conditions hold? For constant and iid observations of variance , derive for .
- A/B with different data. Change the batch to: one episode ; two episodes ; one episode . Compute and at and by hand, then edit
ab_examplein the script to check. - Variance of a target. A chain moves (terminal), each step a reward with variance , independent across steps, and mean ; . Give and when is exact at . Where is the gap in the law of total variance?
- Change the code and predict. Set
episodes = 100innstep_experiment(and reducerunsto keep the runtime down). Predict how the best and the best move before running. Then setv0=0.5and predict which benefits most. - Model misspecification. Modify the walk so the transition probabilities depend on a hidden coin that is fixed within an episode (a non-Markov chain in the observed state). Predict whether batch TD still beats batch MC, run it, and say what the ML-model value converges to.
Chapter 6 takes the next step: what if the data were generated by a different policy than the one we want to evaluate? The unbiased fix, importance sampling, has its own variance problem. Chapter 7 combines bootstrapping with function approximation, where the interplay of bias and sharing information becomes more delicate.
Sources
- Sutton, R. S. (1988). Learning to predict by the methods of temporal differences. Machine Learning 3, 9–44.
- Robbins, H. and Monro, S. (1951). A stochastic approximation method. Annals of Mathematical Statistics 22(3), 400–407.
- Kearns, M. and Singh, S. (2000). "Bias-variance" error bounds for temporal difference updates. Proceedings of the 13th Annual Conference on Computational Learning Theory (COLT), 142–147.
- Sutton, R. S. and Barto, A. G. (2018). Reinforcement Learning: An Introduction, 2nd edition, MIT Press. Chapters 6 (TD learning, section 6.3 for the A/B example), 7 (-step methods), 12 (eligibility traces).