Chapter 4: Monte Carlo & Temporal-Difference Learning
Drop the model and learn from experience: Monte Carlo prediction and control, TD(0), the bias-variance tradeoff between sampling and bootstrapping, and the n-step and TD(lambda) methods that interpolate between them.
- Topics
- 5
- Demos
- 2
- Videos
- 3
- Min read
- 20
Chapter Overview
Dynamic programming needed the transition dynamics. Almost no interesting problem provides them. This chapter removes that assumption and replaces the expectation in the Bellman update with something the agent can actually obtain: sampled experience.
There are two distinct ways to do this, and the difference between them is the central idea of the chapter. Monte Carlo methods wait until an episode ends and use the actual return — unbiased, but high variance and unusable until termination. Temporal-difference methods use a one-step reward plus the current estimate of the next state's value — biased, because the estimate is wrong early on, but low variance and updatable after every single step. Neither dominates. n-step methods and TD(lambda) span the space between them, and understanding that spectrum explains design choices in every algorithm that follows.
Chapter Roadmap
Click any topic to jump in
Monte Carlo Prediction
Estimate a state's value by averaging the actual returns observed after visiting it — no model, no bootstrapping.
Monte Carlo Control
Plug sampled action-value estimates into generalized policy iteration, with exploration supplied by epsilon-greedy.
One-step TD and full-return Monte Carlo are the endpoints, not rival families.
TD(0) Prediction
Update after every step using the observed reward plus the discounted estimate of the next state.
Bootstrapping vs Sampling
The bias-variance axis that separates TD from Monte Carlo and explains when each one wins.
n-step & TD(lambda)
Interpolate between the two extremes by looking n steps ahead, or by averaging all n at once with eligibility traces.
Topics
5 topics in this chapter
Monte Carlo prediction estimates in the most direct way imaginable: run episodes under , record the return that actually followed each visit to , and average them. The law of large numbers does the rest. No model is required, and — unusually for this course — no assumption about the Markov property is needed either. The method only needs episodes that terminate. That second point deserves emphasis because it is the one genuine advantage Monte Carlo holds over everything that follows. Because the method never uses one state's value to estimate another's, it never propagates a representation error from state to state. It samples the whole return directly, so it converges to the correct expected return for whatever representation you gave it. Temporal-difference methods bootstrap from neighbouring estimates and therefore inherit any error in the state representation, which makes Monte Carlo markedly more robust when the states are not quite Markov — a common situation in practice.
Definition
Monte Carlo prediction estimates the value of a state by averaging the actual returns observed after visiting it, using complete episodes and never bootstrapping from other estimates. It requires episodes that terminate, but it needs neither a model of the environment nor the Markov property, which makes it unusually robust when the state representation is imperfect.
In this topic
- 1First-Visit and Every-Visit
- 2The Cost of Waiting
First-Visit and Every-Visit
First-visit Monte Carlo averages returns following only the first occurrence of a state in each episode; every-visit averages returns after every occurrence. First-visit yields independent samples and is therefore the easier one to analyse, giving an unbiased estimate whose error falls as one over the square root of the number of visits. Every-visit is biased for finite samples because returns within a single episode are correlated — a state visited twice contributes two overlapping futures — but it is also consistent, converging to the same answer, and it often performs slightly better in practice by extracting more data per episode.
The bracket is the prediction error against the actual observed return. With this is exactly a running sample mean; with constant it becomes an exponentially weighted average that tracks a changing target — which is what you want when the policy is still improving.
Why does Monte Carlo prediction not require the Markov property, when dynamic programming does?
The Cost of Waiting
Monte Carlo can only update once an episode terminates, because the return is not known until then. That rules out continuing tasks entirely and makes long episodes very slow to learn from. It also means credit is assigned to every state in the episode using the same noisy return, so variance grows with episode length as all the randomness along the trajectory accumulates into a single number. The practical consequence is a method that is statistically clean but operationally awkward: correct in the limit, and often unusably slow to get there on the problems people actually care about.
If the return is a sum of independent noisy rewards with unit variance, its variance is and its standard deviation . Getting a value estimate to a standard error of 0.1 then takes returns: 500 for a 5-step episode, 10,000 for 100 steps and 100,000 for 1,000 steps. The number of episodes needed grows linearly with episode length, before counting that each episode also takes longer to run.
An episode is 1000 steps long and the only reward arrives at the end. What does Monte Carlo do, and why is it high variance?
Prediction becomes control by dropping the estimated values into the generalized policy iteration loop from Chapter 3. Two adjustments are needed for the model-free setting, and both follow directly from things established earlier. First, estimate action values rather than state values, so that improvement needs no model — Chapter 2 showed that acting greedily from requires the dynamics, while acting greedily from is a lookup. Second, ensure every action keeps being tried, because a greedy policy stops sampling the actions it currently rates poorly, so their estimates never improve and an unlucky early sample becomes permanent. The convergence proofs require every state-action pair to be visited infinitely often. Exploring starts guarantee this by beginning episodes from a random state-action pair, but that is impossible in most real environments where you cannot teleport the agent. The practical alternative is an -greedy policy, which keeps every action at positive probability forever. The result is an algorithm that needs nothing but the ability to run episodes and observe rewards.
Definition
Monte Carlo control plugs sampled action-value estimates into the generalized policy iteration loop from the previous chapter. It learns action values rather than state values so that improvement needs no model at all, and it relies on -greedy exploration to keep every state-action pair being visited often enough for its estimate to remain meaningful.
In this topic
- 1Exploring Starts and Epsilon-Greedy
- 2Improvement Without Full Evaluation
Exploring Starts and Epsilon-Greedy
Convergence proofs need every state-action pair to be visited infinitely often. Exploring starts guarantee this by beginning episodes from a random state-action pair, but that is impossible in most real environments where you cannot place the agent arbitrarily. The practical alternative is an -greedy policy, which takes the greedy action with probability and a uniformly random one otherwise, so every action retains positive probability forever. The weakness is that exploratory moves are uniform: a clearly terrible action is sampled exactly as often as a promising untried one.
The probabilities in the formula sum to one: the greedy action gets and the other actions get each. The policy improvement theorem still holds within the class of -soft policies, which is why fixed- control converges to the best member of that class rather than to . GLIE needs two things at once: every state-action pair is tried infinitely often, and the policy becomes greedy in the limit.
Epsilon-greedy never becomes fully greedy, so it never converges to the optimal policy. Is that a real problem?
Improvement Without Full Evaluation
Classic policy iteration evaluates each policy to convergence before improving, which here would require infinitely many episodes per improvement. Monte Carlo control instead improves the policy after every episode, using whatever estimates are available. This is generalized policy iteration with a tiny evaluation budget, the same truncation idea that produced value iteration in Chapter 3. One caution: for the exploring-starts version, convergence to the optimum is still only partly proved. Sutton posed it as an open problem, and Tsitsiklis settled it only for the case where every state-action pair starts episodes equally often; arbitrary start choices can break it. It works reliably in practice nonetheless.
Any fixed point of Monte Carlo control with exploring starts is optimal. If the policy has stopped changing, it is greedy with respect to , and if has stopped changing, it equals . A policy that is greedy with respect to its own satisfies the Bellman optimality equation. What remains unproved in general is that the stochastic process actually reaches such a point, because each episode's update depends on the policy that the previous updates produced.
How does improving after every episode avoid the instability you might expect from acting on such noisy estimates?
Related Problems on PixelBank
Temporal-difference learning is the idea that gives reinforcement learning its distinctive character. Instead of waiting for the true return, TD(0) updates toward the observed reward plus the discounted value estimate of the state that follows. It is learning a guess from a guess, and the natural objection is that errors should compound — the target is wrong early on, so the update is wrong, so the next target is wronger still. That objection turns out to be misplaced, for a reason worth understanding. The target is not purely an estimate: it contains one real observed reward. Every update therefore injects a step of genuine information, and terminal states have known value zero, so correct information propagates backwards from the ends of episodes. Formally the TD operator is a contraction, so errors shrink geometrically rather than accumulating. That guarantee holds in the tabular case and breaks only when function approximation, bootstrapping and off-policy updates are combined — the deadly triad of Chapter 6.
Definition
TD(0) updates a state's value toward the observed reward plus the discounted estimate of the next state, rather than waiting for the full return. It learns online after every step, needs no model and no terminating episodes, and converges because the update injects one real reward each time.
In this topic
- 1The TD Error
- 2Why TD Often Wins
The TD Error
The quantity is the TD error: the difference between the estimate before and after seeing one more step of reality. It is the single most important scalar in reinforcement learning, and it reappears in three distinct roles across the remaining chapters. It drives the update in TD(0), it serves as the advantage estimate in the actor-critic methods of Chapter 8, and its magnitude is the sampling priority in prioritized experience replay. Recognizing it in each disguise makes those later algorithms considerably less mysterious.
TD errors add up to the Monte Carlo error. If is held fixed during an episode, : the full-return correction is the discounted sum of the one-step corrections along the way. TD applies each piece as soon as it is observed instead of waiting for the sum, which is why it can learn before the episode ends and why the two methods agree in expectation when is already correct.
TD bootstraps from its own estimates, which are wrong at initialization. Why doesn't the error compound catastrophically?
Why TD Often Wins
TD updates after every step, so it learns from incomplete episodes and works in continuing tasks that never terminate. Its targets have far lower variance than full returns because they depend on one random reward and transition rather than hundreds. Empirically it converges faster than Monte Carlo on most Markov problems, and it exploits structure Monte Carlo ignores by reusing value estimates across states — information learned about one state immediately improves the targets for all of its predecessors, which is a form of generalization that Monte Carlo simply does not have access to.
On the 5-state random walk, starting all values at 0.5 and averaging 100 runs, TD(0) with reaches an RMS error of 0.038 after 100 episodes. Monte Carlo's best step size among 0.01, 0.02 and 0.04, which was , reaches 0.083. Each TD update moves a state's value toward a neighbour's estimate plus one reward, and on this chain the neighbours' errors are already shrinking, so variance drops faster than bias is added.
In the classic random-walk experiment TD converges faster than Monte Carlo. What is it exploiting?
Related Problems on PixelBank
Every value-learning method makes two independent choices, and almost all the confusion about which algorithm to use dissolves once they are separated. The first is whether to sample the environment's transitions or take a full expectation over them. The second is whether to bootstrap from existing value estimates or use complete returns. Those two axes place dynamic programming, Monte Carlo and temporal-difference learning in a single two-by-two picture, and they predict the strengths of each. Dynamic programming takes full expectations and bootstraps, so it needs a model. Monte Carlo samples and does not bootstrap, so it needs terminating episodes. TD samples and bootstraps, which is why it needs neither. The remaining corner — full expectations without bootstrapping — is exhaustive search over whole trajectories, generally intractable. Bootstrapping trades bias for reduced variance; sampling trades variance for freedom from a model. Neither choice dominates, which is why the intermediate methods in the next topic usually win.
Definition
Two independent axes classify every value-learning method: whether it samples transitions or takes a full expectation over the model, and whether it bootstraps from existing value estimates or waits for a complete return. Bootstrapping trades bias for lower variance; sampling trades variance for model-freedom.
In this topic
- 1The Two Axes
- 2Bias and Variance in Practice
The Two Axes
Dynamic programming takes a full expectation over every next state, which requires a model, and bootstraps after a single step, so its backups are wide but shallow. Monte Carlo samples one trajectory and does not bootstrap, so its backups are narrow but run to the end of the episode. TD samples and bootstraps, narrow and shallow, which is why it needs neither a model nor complete episodes. The remaining corner, full expectation without bootstrapping, is exhaustive search over whole trajectories, wide and deep, and generally intractable. Laid out this way, the methods are not competing philosophies but corners of one design space.
Cost explains the layout. With possible outcomes per step and a horizon of steps, a full-width backup that never bootstraps must consider trajectories. Bootstrapping cuts the depth to one, giving terms per backup, which is dynamic programming. Sampling cuts the width to one, giving terms, which is Monte Carlo. Doing both gives a single term, which is TD(0). Each axis removes one factor from the exponent.
Place n-step TD and exhaustive search on these two axes.
Bias and Variance in Practice
The Monte Carlo target is unbiased with variance proportional to episode length. The TD target is biased by the current value error but has variance from only one transition. Early in training the bias dominates because the estimates are poor; later it vanishes as values become accurate, while Monte Carlo's variance never shrinks at all. That asymmetry is the practical argument for bootstrapping: its cost is temporary and self-correcting, whereas the variance cost of full returns is permanent and set by the problem rather than by the state of learning.
The bias of a bootstrapped target shrinks with depth: . The variance of the Monte Carlo target grows with episode length, roughly linearly when rewards are independent. With unit reward noise, a 1,000-step return has a standard deviation of about 31.6 against 2.2 for a 5-step return, so it needs about 200 times as many samples for the same precision.
You are training on episodes that last 5000 steps with sparse rewards. Which method, and why?
Related Problems on PixelBank
n-step methods make the bootstrapping depth an explicit parameter: use real rewards, then bootstrap from the value of the state reached. Setting gives TD(0) and letting reach the end of the episode gives Monte Carlo, so the two methods of this chapter turn out to be endpoints of a single family rather than rivals. Intermediate values usually outperform both, and the reason is concrete. In a sparse-reward gridworld, one-step TD moves useful information exactly one state back per episode, so on a 20-step path the start state learns nothing for 20 episodes. A ten-step return gets the signal there in two. TD() avoids committing to any single by averaging all of them with geometrically decaying weights. Computing that average directly means waiting for the episode to end, but eligibility traces approximate it online, and true online TD() computes it exactly. Both methods buy faster propagation without paying the full variance of Monte Carlo returns.
Definition
n-step methods use real rewards before bootstrapping, spanning the whole range from TD(0) at one step to Monte Carlo at infinitely many. TD() declines to pick a single depth and instead averages over every n-step return with geometrically decaying weights, computed online using eligibility traces so that no waiting for the episode to end is required.
In this topic
- 1The n-step Return
- 2Eligibility Traces and the Lambda Return
The n-step Return
The n-step return accumulates discounted rewards and then adds the discounted value estimate of the state reached. Intermediate values of typically outperform both extremes, with the best setting depending on how sparse the rewards are and how accurate the value function currently is. The costs are real but modest: updates must be delayed by steps, since the return is not complete until then, and becomes another hyperparameter to tune. In practice the method is fairly forgiving, with performance varying smoothly rather than sharply across nearby values.
The formula splits the target into observed rewards and one estimate, discounted by . That discount is what makes depth useful: the worst-case error of the expected n-step target is at most times the worst-case error of . On a 20-step corridor with reward only at the goal and values starting at zero, the start state first receives a nonzero value after episode 20 with , episode 10 with , episode 4 with and episode 2 with .
In a gridworld where reward arrives only at the goal, how does the choice of n change how fast learning propagates?
Eligibility Traces and the Lambda Return
Rather than committing to one , the lambda return averages all n-step returns with weights , which sum to one. Computing it directly means waiting for the episode to end. The backward view with eligibility traces approximates it online: each state keeps a trace that jumps when the state is visited and decays by every step, and every TD error updates all states in proportion to their traces. The two views match exactly when updates are applied offline at the end of the episode; true online TD() makes them match online too. In practice , like , still needs tuning.
The weights form a geometric distribution over depths: for , with mean depth . So behaves on average like a 2-step return, like a 10-step return and like a 20-step return. In an episode that ends at step , all the weight left over for depths beyond the end goes to the full Monte Carlo return.
What do lambda = 0 and lambda = 1 correspond to, and what does an intermediate value buy?