Learning values from experience: Monte Carlo and temporal-difference prediction
Before this lesson: lesson 01 (returns, and the Bellman expectation equation), lesson 02 (iterative policy evaluation and the operator ) and lesson 03 (the incremental mean). Monte Carlo estimation, bias and variance, and importance sampling are in probability 14; we restate what we need. Time: about 70 minutes, plus the notebook.
Why this matters #
Dynamic programming needs the model and . A robot, a game engine or a user population gives us only samples. Estimating the value of a policy from samples, called prediction or policy evaluation, is half of almost every RL algorithm:
- Critics and value heads. Actor-critic methods, PPO and the value model in RLHF train a value network on TD targets or λ-returns; GAE (lesson 08) is the λ-return idea applied to advantages.
- Q-learning and DQN (lesson 05, lesson 06) are TD learning for action values; Rainbow uses n-step returns.
- Off-policy evaluation with importance sampling estimates how a new policy (a recommender, a treatment rule) would perform, using logs of the old one. The ratio returns in PPO (lesson 09).
- Neuroscience. The TD error matches the firing of dopamine neurons, which signal reward prediction errors (Schultz, Dayan and Montague, 1997). TD-Gammon (Tesauro, 1995) learned world-class backgammon with TD(λ).
1. Predict first #
2. The picture #
Prediction from samples #
A policy is fixed. We do not know the MDP, but we can run and observe episodes , where is the reward after and is terminal. (Sutton and Barto write this reward ; see lesson 01.) We want
The recursion suggests two targets for :
- Monte Carlo: wait for the end of the episode and use the actual return .
- TD(0): after one step, replace the unknown rest by the current estimate , and use . Using your own estimate inside the target is bootstrapping.
Both then take a step toward the target, exactly like the incremental mean of lesson 03:
The random walk #
Our running example is the random walk of Sutton and Barto (Example 6.2). Five states A, B, C, D, E lie in a row, with a terminal state at each end. Every episode starts in C. At each step the agent moves left or right with probability 1/2. The reward is +1 for leaving on the right, and 0 for every other step; .
The true value of a state is the probability of leaving on the right. Number the positions 0 to 6 (0 and 6 are the terminals), so and . The Bellman equation of each inner state is : the values lie on a straight line from 0 to 1, so . Hence .
Choose a method and press Step. The blue bars are the current values (all start at 0.5), the dashed lines the true values, and the orange dot the agent. The default episode is C → B → C → D → E → right end. With TD(0), every TD error before the last step is 0, so only E moves. With MC, nothing moves until the end; then every visited state moves toward the return 1. With TD(λ), the orange trace bars show which states share the final TD error. Then switch to learning curves (mean of 100 runs) and look for the best α of each method: the best TD(0) curve ends lower than the best MC curve.
All values start at 0.5, , . One episode of the random walk is C → D → E → right end (+1). Which values change under TD(0)?
The TD errors are for C → D and D → E, so C and D do not move. The last error is (the value after the end is 0), so . Monte Carlo would move C, D and E to 0.55, because all three have return 1.
3. Definitions and main results #
Monte Carlo prediction #
After an episode ends, compute the returns backward: and for (one pass, from the end). Then
- first-visit MC uses, for each state, only the return after its first visit in the episode;
- every-visit MC uses the returns after all its visits.
The estimate is the average of the used returns (sample average), or a constant-α update .
Properties.
- Each first-visit return is an unbiased sample of , and returns from different episodes are independent. So the first-visit average converges to by the law of large numbers, with standard error after episodes that visit .
- Returns after different visits in the same episode are dependent, so every-visit MC is biased for a finite number of episodes, but it also converges to (Singh and Sutton, 1996).
- MC needs complete episodes: no update before the end. It does not use the Markov property; it only averages what followed each state.
TD(0) #
TD(0) updates after every step:
with when is terminal. The quantity is the TD error: the difference between the one-step target and the current estimate.
TD(0) is sampled dynamic programming. Given , the expected target is
the Bellman expectation operator of lesson 02. Iterative policy evaluation applies to all states with the model; TD(0) applies one noisy sample of it to the visited state. The expected update is zero exactly when , that is, at . In the tabular case, TD(0) converges to with probability 1 if every state is visited infinitely often and the step sizes satisfy , (Dayan 1992; Jaakkola, Jordan and Singh 1994; Tsitsiklis 1994). With a small constant , the values converge in the mean and keep fluctuating around .
The MC error is a sum of TD errors. If does not change during the episode, then
Proof.
- Write out the sum, using the definition of :
- The first sum is .
- In the second sum, shift the index (): it is . It cancels the third sum except for two end terms: .
- because is terminal. So the sum is .
So MC sends each state the whole chain of future TD errors, and TD(0) only the first one. TD(λ) below sends a decaying part of the chain.
Bias and variance #
| Monte Carlo | TD(0) | |
|---|---|---|
| target for | ||
| bias | none: | yes, while : the target's mean is |
| variance of the target | high: a sum of many random rewards and transitions | low: one reward and one transition |
| needs | complete episodes | one transition ; works online and in continuing tasks |
| Markov property | not used | used: must summarize the future |
| sensitive to the initial | no | yes (the bias comes from it) |
On the random walk, TD(0) usually learns faster than MC (Sutton and Barto, Figure 6.2). In our simulation (100 runs, 100 episodes, values start at 0.5) the best TD(0) step size, , reaches an RMS error of about 0.036, while the best first-visit constant-α MC ( or ) is at about 0.059. A larger learns faster at first but stays noisier, so compare the methods at their best step sizes.
"TD(0) targets are unbiased estimates of ." True or false?
The target uses the current estimate . Its mean is . If is wrong, the target is wrong on average; the bias disappears only as approaches . The MC target is unbiased, but it has a much higher variance.
Batch MC and batch TD #
With a fixed, finite set of episodes, we can replay the data again and again. In batch updating, each sweep sums the increments over all the data and applies them at the end of the sweep. For a small both methods converge, but to different values.
Theorem (batch limits).
- Batch MC converges to the average of the observed returns from each state. This minimizes the squared error on the training returns.
- Batch TD(0) converges to the value function of the maximum-likelihood Markov model of the data: with the fraction of transitions from that go to , and the average reward after ,
This is the certainty-equivalence estimate: the value we would compute if the estimated model were exactly right.
Proof (of the fixed points). At the limit the summed increments are 0 for every state .
- MC: , so is the mean of the returns .
- TD: . Divide by the number of transitions from : , the Bellman equation of the estimated model (with at terminal states).
Example. Six episodes: "A, 0, B, 1" once; "B, 1" three times; "B, 0" twice ().
- : six returns from B (one in the first episode, five in the others), four of them equal to 1. Both methods give .
- Batch MC: the only return observed from A is 1, so .
- Batch TD: in the data, A always goes to B with reward 0, so .
Which is better? MC fits the training returns exactly. TD uses what the data says about B, from all the episodes, to judge A. When the process really is Markov, TD's answer usually generalizes better. (Sutton and Barto's Example 6.4 uses eight episodes and gets MC against TD .)
Predict for each method, then press Run batch updates. The diagram is the maximum-likelihood model estimated from the data. The chart shows over sweeps for batch MC and batch TD, and , which both methods share. Change the counts or the reward of the A episode and predict again; the preset Sutton & Barto Ex. 6.4 gives 0 against 3/4.
Data: "A, 0, B, 0" once, "B, 1" six times, "B, 0" once (). What does batch TD(0) give for ?
B is visited 8 times and followed by reward 1 six times, so . In the data A always goes to B with reward 0, so batch TD gives . Batch MC gives , the one return observed from A. forgets the visit of B in the first episode.
n-step returns and the λ-return #
The n-step return uses real rewards, then bootstraps:
If the episode ends before (), then , the full return. gives the TD(0) target; gives the MC target. n-step TD updates toward , steps later. A middle is often better than both ends.
The λ-return averages all n-step returns, with weights that decay geometrically, for :
The first part gives weight to . Every n-step return with equals , so all their weight, , goes to the full return. The weights add up to 1: . With , (TD(0)); with , (MC).
Move λ and the number of steps until the episode ends. Violet bars are the weights of the n-step returns (they bootstrap); the aqua bar is the weight of the full return . With λ = 0.5 and the end 3 steps after , the weights are 0.5, 0.25 and 0.25. Set λ = 0 and λ = 1 to see the two ends: TD(0) and Monte Carlo.
and the episode ends 3 steps after time . What weights does the λ-return give to , and the full return ?
gets and gets . Every with equals , so the full return gets all the rest, . The weights must sum to 1; the first option forgets the lumped tail.
TD(λ): eligibility traces #
The λ-return needs the future, so it can only be computed at the end of the episode (the forward view). TD(λ) gets the same effect online with one number per state, the eligibility trace , which records how recently and how often was visited (the backward view).
At the start of each episode set for all . At every step :
- for every state (all traces decay);
- (an accumulating trace);
- ;
- for every state.
So the current TD error is sent back to a state visited steps ago with weight , and a state visited twice gets the sum of both weights.
Step through the episode C → B → C → D → E → +1. The orange bars are the traces; C was visited twice, so its bar has two pieces (the older visit is lighter). All TD errors are 0 until the reward arrives; then each state moves by (blue numbers). Predict first: at the last step, is larger or smaller than ? Then move λ: at λ = 0 only E moves; at λ = 1 every visit counts fully.
Theorem (forward view = backward view, offline). If the values are updated only at the end of the episode (offline), then for every state the sum of the TD(λ) updates equals the sum of the λ-return updates over the visits of .
Proof
- Extend the identity for MC: with fixed during the episode, . (For this is the MC identity above; the general case follows from the same telescoping, using .)
- Sum the forward-view updates of state : .
- Swap the two sums: .
- The inner sum is exactly the accumulating trace after step : each visit adds 1, and each step multiplies by . So the total is , the sum of the TD(λ) updates.
Two special cases: gives TD(0), and with offline updates gives every-visit MC (the identity ). With online updates the two views differ slightly, because changes during the episode; true online TD(λ) (van Seijen and Sutton, 2014) removes this difference with a modified trace.
Off-policy prediction with importance sampling #
Often the data comes from a behaviour policy (an old system, an exploring agent), but we want for a different target policy . We need coverage: must imply . The importance-sampling ratio of the rest of an episode is
Theorem. .
Proof.
- The probability of the trajectory under a policy is .
- In the ratio of this probability under and under , the unknown transition probabilities cancel. What is left is : we can compute it without the model.
- So .
With returns from and their ratios :
- ordinary importance sampling : unbiased, but its variance can be huge (a product of many ratios), even infinite;
- weighted importance sampling : biased for finite (with one return it simply gives that return), but the bias goes to 0 as grows. It is a weighted average of returns, so it always stays within their range, and in practice its variance is much lower.
Example. One step: "right" has return 1, "left" return 0. Target , so ; behaviour . The ratios are for right and for left. Data: right, left, right, right.
- Ordinary: : above 1, outside the range of possible returns.
- Weighted: .
Which importance-sampling estimator can give a value outside the range of the observed returns?
Ordinary IS multiplies returns by ratios that can be larger than 1 and divides by , not by the sum of the ratios, so it can leave the range (1.35 in the example, with returns in ). Weighted IS divides by , so it is a weighted average of the returns and stays inside their range. The price is a bias for finite .
Answers to section 1. (1) Monte Carlo. MC moves the state toward the return 1 at once. TD(0) moves only the last state before the reward in this episode; the information reaches earlier states over later episodes, one step per episode. (2) Yes. Batch MC converges to the average observed return of each state; batch TD converges to the values of the maximum-likelihood Markov model. In the A/B example, against .
4. Worked example #
The random walk with all values 0.5, , , and one episode C → B → C → D → E → right end (+1). The transitions are (C, 0, B), (B, 0, C), (C, 0, D), (D, 0, E), (E, 1, end).
(a) TD(0). Every TD error before the last step is . The last one is . Only E moves: .
(b) TD(λ) with λ = 0.5. Here . The traces after each step (decay first, then add 1):
| step | state | |||||
|---|---|---|---|---|---|---|
| 0 | C | 0 | 1 | 0 | 0 | 0 |
| 1 | B | 1 | 0.5 | 0 | 0 | 0 |
| 2 | C | 0.5 | 0.25 + 1 = 1.25 | 0 | 0 | 0 |
| 3 | D | 0.25 | 0.625 | 1 | 0 | 0 |
| 4 | E | 0.125 | 0.3125 | 0.5 | 1 | 0.5 |
Only the last TD error is nonzero, and . So , , , and . Note : one term per visit.
(c) Check with the forward view. C is visited at and . Since everywhere during the episode, every n-step return that bootstraps is 0.5, and the full return is 1.
- At (end 5 steps later): .
- At (end 3 steps later): .
- Total update of C: . ✓
(d) First-visit MC. Every visited state has return 1, so B, C, D and E all move to .
(e) TD(1). With λ = 1 the traces do not decay: , . So : two MC increments of 0.05, one per visit. This is offline every-visit MC.
5. In code #
NumPy checks the hand computations. The notebook implements MC, TD(0) and TD(λ) for whole data sets.
import numpy as np
# random walk: states A..E = 0..4; the episode C, B, C, D, E, right end (+1) as (s, r, s_next, done)
episode = [(2, 0, 1, False), (1, 0, 2, False), (2, 0, 3, False), (3, 0, 4, False), (4, 1, -1, True)]
def td_lambda(episode, lam, alpha=0.1, gamma=1.0):
V, z = np.full(5, 0.5), np.zeros(5)
for s, r, s2, done in episode:
delta = r + (0.0 if done else gamma * V[s2]) - V[s] # TD error; V = 0 after the end
z *= gamma * lam # all traces decay
z[s] += 1.0 # accumulating trace
V += alpha * delta * z
return V, z
print(td_lambda(episode, 0.0)[0]) # [0.5 0.5 0.5 0.5 0.55] TD(0): only E moves
V, z = td_lambda(episode, 0.5)
print(V) # [0.5 0.50625 0.515625 0.525 0.55]
print(z) # [0. 0.125 0.3125 0.5 1.] final traces
print(td_lambda(episode, 1.0)[0]) # [0.5 0.55 0.6 0.55 0.55] TD(1)
# first-visit constant-alpha MC: every visited state has the return G = 1
V = np.full(5, 0.5)
for s in dict.fromkeys(s for s, *_ in episode): # each state once, in order of first visit
V[s] += 0.1 * (1.0 - V[s])
print(V) # [0.5 0.55 0.55 0.55 0.55]
# importance sampling: target pi(right) = 0.9, behaviour pi_b(right) = 0.5
G = np.array([1.0, 0.0, 1.0, 1.0]) # right, left, right, right
rho = np.where(G == 1.0, 0.9 / 0.5, 0.1 / 0.5) # 1.8 or 0.2
print(np.mean(rho * G), np.sum(rho * G) / np.sum(rho)) # 1.35 0.964...
6. Where it shows up #
- Value networks in deep RL. DQN regresses on one-step TD targets; Rainbow uses 3-step returns. A2C and PPO train their critic on n-step returns or λ-returns; GAE (lesson 08) is the λ-weighting of this lesson applied to advantages, with typical values , .
- RL for language models. When a response gets one reward at the end and , every token's return equals that final reward: a Monte Carlo setting. A learned value model adds TD-style bootstrapping (lesson 09).
- Off-policy evaluation. Recommenders, ad systems and medical decision rules estimate the value of a new policy from logged data of the old one with (weighted, clipped or doubly robust) importance sampling, before any user sees it.
- Neuroscience. Dopamine neurons respond to unexpected reward and, after learning, to the cue that predicts it, as the TD error does (Schultz, Dayan and Montague, 1997).
- ML for science. Long simulations (molecular dynamics, climate, games) are expensive to run to the end; bootstrapped value estimates let an agent learn from partial runs.
7. Common mistakes #
- Bootstrapping past the end. The value after a terminal step is 0, not of some state. Use the "done" flag: .
- Forward loops for returns. Returns need one backward pass, ; a forward loop that recomputes each sum is slow and error-prone.
- "TD is unbiased." Its target uses the current estimate, so it is biased until . MC is unbiased (first-visit) but has high variance.
- Traces not reset. Eligibility traces start at 0 in every episode; old traces would send new TD errors to states of the previous episode.
- Decay and increment in the wrong order, or forgetting . The trace decays by , not by alone.
- λ-return weights that do not sum to 1. At the end of an episode the remaining weight goes to the full return .
- Reward timing. Here follows ; in Sutton and Barto it is . The TD error is in our notation and in theirs.
- Importance sampling without coverage. If for an action that uses, the data says nothing about it, and no reweighting can fix that.
8. Check yourself #
- Write the MC target and the TD(0) target for . Which one bootstraps, and what does that mean?
Answer
MC: . TD(0): . TD bootstraps: it uses its own current estimate in place of the rest of the return. - Rewards then the end, , and at the non-terminal states . Compute , and .
Answer
. . . - Why does TD(0) usually have lower variance than MC?
Answer
Its target depends on one random reward and one random transition. The MC target sums all the random rewards until the end, and their variances add up. - What does batch TD(0) converge to, and why can it differ from batch MC?
Answer
The values of the maximum-likelihood Markov model of the data (certainty equivalence). MC fits each state's own observed returns and ignores that its successor states were also observed from other episodes. - With accumulating traces and , a state is visited at steps 0 and 3. What is its trace after step 5?
Answer
: one term per visit, each decayed by the number of steps since that visit. - Why is ordinary importance sampling unbiased, and why is weighted importance sampling used anyway?
Answer
Because : the ratio turns behaviour probabilities into target probabilities. But its variance can be huge or infinite. Weighted IS is biased for finite (consistent), stays within the range of the returns, and usually has far lower variance.
Write the TD error .
, with if is terminal.
What does bootstrapping mean in TD learning?
Using your own current estimate, , inside the target in place of the rest of the actual return.
Compare the bias and variance of the MC and TD(0) targets.
MC (): unbiased, high variance. TD(0) (): biased while , low variance.
What does batch TD(0) converge to?
The value function of the maximum-likelihood Markov model of the data (the certainty-equivalence estimate).
Batch data: "A, 0, B, 1" once, "B, 1" three times, "B, 0" twice. Give for batch MC and batch TD.
MC: 1 (the one return from A). TD: .
Write the n-step return .
; it equals if the episode ends first.
What weight does the λ-return give to , and where does the rest go at the end of an episode?
; all the remaining weight goes to the full return .
State the accumulating-trace update of TD(λ).
Each step: , then , then . Traces start at 0 in every episode.
What are TD(λ) with λ = 0 and with λ = 1?
λ = 0 is TD(0). λ = 1 (offline, accumulating traces) is every-visit Monte Carlo.
Ordinary vs weighted importance sampling: which is unbiased, and which stays in the range of the returns?
Ordinary IS, , is unbiased; weighted IS, , is biased but stays within the range and has lower variance.
9. Interview angle #
- "MC vs TD: bias and variance?" — MC is unbiased with high variance and needs episode ends; TD is biased, has low variance, learns online and uses the Markov property. TD usually learns faster.
- "What is bootstrapping, and why can it be dangerous?" — Using your own estimate in the target. It speeds learning, but errors in feed back into the targets; with function approximation and off-policy data this can diverge (the deadly triad, lesson 06).
- "What does λ do in TD(λ) or GAE?" — It interpolates between one-step TD (λ = 0, low variance, high bias) and Monte Carlo (λ = 1, no bias, high variance), with geometric weights on n-step returns.
- "Explain eligibility traces." — A decaying memory of visited states; each TD error is sent back to them in proportion to their trace. Offline it equals the λ-return.
- "How do you evaluate a new policy from logged data?" — Importance sampling with ; prefer weighted or per-decision IS, clip large ratios, and check coverage.
10. Practice #
The notebook for this lesson runs in Colab. It has five exercises, each with a check cell and a folded solution:
td0_prediction: online TD(0) over a list of episodes; check the worked example.mc_prediction: first-visit and every-visit, sample average (batch) and constant α; check the A/B batch example and Sutton and Barto's Example 6.4.td_lambda_prediction: accumulating traces; check that λ = 0 equals TD(0) and the worked example.- Reproduce the RMS-error-vs-episodes plot on the random walk for several α, and check that TD(0) beats constant-α MC.
importance_sampling_estimates: ordinary and weighted IS; measure their bias and variance by simulation.
11. Watch and read #
- Sutton and Barto, Reinforcement Learning: An Introduction, 2nd edition, free PDF: §5.1 (MC prediction), §5.5 (importance sampling), §6.1–6.3 (TD(0), Examples 6.2 and 6.4, batch updating), §7.1 (n-step TD), §12.1–12.2 (λ-return, TD(λ)).
- Singh and Sutton, Reinforcement learning with replacing eligibility traces (1996): first-visit and every-visit MC, and the bias of every-visit MC.
- van Seijen and Sutton, True online TD(λ) (ICML 2014).
- Schultz, Dayan and Montague, A neural substrate of prediction and reward (Science, 1997): the TD error in dopamine neurons.
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.
No Google account needed: Python runs inside your browser. The first start downloads about 40 MB; your changes are saved in this browser only.