Learning from Experience

Reinforcement learning, part 3.1: prediction without a model, Monte Carlo and temporal differences

Author

Published

Oct. 2026

PDF

Introduction

So far you discovered RL basics and how to solve problems as big as a tic-tac-toe but you might wonder how to solve larger problems for which we don’t know the model. Welcome to this third part “Learning from Experience”

Where Parts 1 and 2 left us in a few words

Part 1, Modeling the World gave us the framework of RL: An agent in state StS_t takes an action AtA_t, receives a reward Rt+1R_{t+1} and lands in St+1S_{t+1}; and it wants to maximize the return, the discounted sum of the rewards to come:

Gt=Rt+1+γRt+2+γ2Rt+3+⋯=Rt+1+γ Gt+1G_t = R_{t+1} + \gamma R_{t+2} + \gamma^2 R_{t+3} + \cdots = R_{t+1} + \gamma\, G_{t+1}

The value functions score states and actions under a policy π\pi: vπ(s)≐Eπ[Gt∣St=s]v_\pi(s) \doteq \mathbb{E}_\pi[G_t \mid S_t = s] and qπ(s,a)≐Eπ[Gt∣St=s,At=a]q_\pi(s, a) \doteq \mathbb{E}_\pi[G_t \mid S_t = s, A_t = a]. Because the return is recursive, they satisfy the Bellman equations, one step plus the discounted value of where it leads:

vπ(s)=∑aπ(a∣s)∑s′,rp(s′,r∣s,a) [r+γ vπ(s′)]v_\pi(s) = \sum_a \pi(a \mid s) \sum_{s', r} p(s', r \mid s, a)\,\big[r + \gamma\, v_\pi(s')\big]

When the model p(s′,r∣s,a)p(s', r \mid s, a) is known, we can use dynamic programming to solve these equations by sweeps (Part 2, Planning with a Model): the Bellman equation is used as an update rule, applied to every state again and again:

vk+1(s)=∑aπ(a∣s)∑s′,rp(s′,r∣s,a) [r+γ vk(s′)]v_{k+1}(s) = \sum_a \pi(a \mid s) \sum_{s', r} p(s', r \mid s, a)\,\big[r + \gamma\, v_k(s')\big]

The key idea was that optimal policies are always found by algorithms belonging to generalized policy iteration (GPI) composed of two actions:

Part 2 ended on the limit of this approach: even when the experience decides where to update, every update still needs the model to decide what the update is, which is rarely the case most cases.

What if we don’t have the model?

All the methods we have seen so far compute ∑s′,rp(s′,r∣s,a) [r+γ v(s′)]\sum_{s', r} p(s', r \mid s, a)\,[r + \gamma\, v(s')], which needs the model pp. This session removes that requirement.

The key idea fits in one line:

The key idea

Replace the expectation over pp by an average over experience we draw.

∑s′,rp(s′,r∣s,a) [r+γ v(s′)]⟶1N∑i=1N[ri+γ v(si′)]\sum_{s', r} p(s', r \mid s, a)\,\big[r + \gamma\, v(s')\big] \quad\longrightarrow\quad \frac{1}{N} \sum_{i=1}^{N} \big[r_i + \gamma\, v(s'_i)\big]

See how we can estimate the model by using experiences only on the following example :

An expectation, computed or estimated
One state, one action, three possible outcomes. Left, planning: the model gives the probability of each outcome, and the value is their weighted sum, computed exactly. Right, learning: the probabilities are unknown, but each episode draws one outcome; the average of the returns observed so far (orange) approaches the same value (dashed) as episodes accumulate.

When applying this idea to our problems, we could estimate pp from a lot of interactions. But this would require a giantic amount of time to cross each (s,a)(s,a) pair multiple times. So instead of finding the dynamics pp and then solving the problem, we keep the steps from GPI, and each one slightly differ:

One key idea for both: as we need many episodes, the environment must be fast to evaluate, we trade prior knowledge against fast interactions.

We will study:

  1. Monte Carlo evaluation: the value of a state as the average of the returns that followed.
  2. Temporal-difference evaluation: update after every step, from the next estimate.
  3. Monte Carlo or TD? How these two give different answers with the same data.

The control problem, i.e. finding a good policy without the model, is the subject of Part 3.2, Learning to Act: Monte Carlo control, SARSA, and Q-learning.

1. Monte Carlo: learning from complete episodes

Monte Carlo methods aim at estimating a dynamics based on a set of observations drawn from a probability distribution.

1.1 An average of returns

Monte Carlo methods are not specific to reinforcement learning. Whenever an expectation can’t be computed analytically, one can draw random samples and average them.

Formally, with X1,X2,…X_1, X_2, \dots independent copies of a random variable XX,

μ^N=1N∑i=1NXi →N→∞ E[X]\hat\mu_N = \frac{1}{N} \sum_{i=1}^N X_i \ \xrightarrow[N \to \infty]{} \ \mathbb{E}[X]

with probability one: this is the law of large numbers. The estimate is unbiased, E[μ^N]=E[X]\mathbb{E}[\hat\mu_N] = \mathbb{E}[X], and its error shrinks like σ/N\sigma / \sqrt{N}, where σ\sigma is the standard deviation of XX. It is used to price options, compute integrals in high dimension, or propagates uncertain inputs through finite-element models.

Two coins, one law
A fair coin (P(heads) = 0.5) and a weighted one (P(heads) = 0.7), flipped live, with X = 1 for heads. The running mean wanders at first, then settles on E[X] (dashed), inside a funnel E[X] ± σ/√N that narrows like 1/√N.

In reinforcement learning, the expectation we want is the value vπ(s)=Eπ[Gt∣St=s]v_\pi(s) = \mathbb{E}_\pi[G_t \mid S_t = s], and the samples are the returns.

The recipe is thus to play episodes with π\pi:

S0,A0,R1,S1,A1,R2,…,STS_0, A_0, R_1, S_1, A_1, R_2, \dots, S_T

and, every time the agent is in ss, write down the return that followed, Gt=Rt+1+γRt+2+⋯+γT−t−1RTG_t = R_{t+1} + \gamma R_{t+2} + \dots + \gamma^{T-t-1} R_T.

Monte Carlo policy evaluation estimates vπ(s)v_\pi(s) by the average of these returns: the empirical mean instead of the true expected return. No model is needed, only episodes.

But the episodes must end: GtG_t is known only once the episode has terminated, so Monte Carlo works for episodic tasks only.

The average does not need to store the returns. After each new return GtG_t from ss, it can be updated in place, as an average written step by step:

N(s)←N(s)+1,V(s)←V(s)+1N(s)[Gt−V(s)]N(s) \leftarrow N(s) + 1, \qquad V(s) \leftarrow V(s) + \frac{1}{N(s)}\big[G_t - V(s)\big]

This incremental form is what the algorithms below use.

1.2 Evaluating VV at the first visit or every visit

A state can come back several times in the same episode. To estimate its value fo a given policy, First-visit MC keeps only the return after the first visit to ss in each episode; every-visit MC keeps them all. See on the example below :

Algorithm Monte Carlo prediction (first visit / every visit)

Input: a policy π\pi to evaluate

  • V(s)←0V(s) \leftarrow 0 and N(s)←0N(s) \leftarrow 0 for every state ss
  • repeat for each episode
    • generate an episode with π\pi: S0,A0,R1,…,ST−1,AT−1,RTS_0, A_0, R_1, \dots, S_{T-1}, A_{T-1}, R_T
    • G←0G \leftarrow 0
    • for t=T−1,T−2,…,0t = T-1, T-2, \dots, 0, backward in time
      • G←γ G+Rt+1G \leftarrow \gamma\, G + R_{t+1}
      • if StS_t does not appear in S0,…,St−1S_0, \dots, S_{t-1}
        • N(St)←N(St)+1N(S_t) \leftarrow N(S_t) + 1
        • V(St)←V(St)+1N(St)[G−V(St)]V(S_t) \leftarrow V(S_t) + \frac{1}{N(S_t)}\big[G - V(S_t)\big]
Two episodes with γ = 1: A →(1)→ B →(0)→ A →(2)→ end, then B →(1)→ A →(2)→ end. The backward pass builds each return, G ← γG + Rt+1. In first-visit mode, the return after the second visit to A fails the test and is skipped: V(A) = 2.5, the average of 3 and 2. Switch to every visit: the test is struck out, and V(A) averages 2, 3 and 2, about 2.33. V(B) = 2.5 in both.

Every-visit MC is the same algorithm without the if: switch the figure to every visit to see it run.

Running backward builds every return of the episode in a single pass (forward pass would require O(n2)O(n^2) steps), since Gt=Rt+1+γ Gt+1G_t = R_{t+1} + \gamma\, G_{t+1}. The update with 1N\frac{1}{N} is the incremental form of section 1.1: the running average of the returns, computed without storing them.

For example, with γ=1\gamma = 1, on an episode that visits AA twice, the two version give:

A→ R1=1 B→ R2=0 A→ R3=2 end⇒G0=1+0+2=3,G2=2A \xrightarrow{\ R_1 = 1\ } B \xrightarrow{\ R_2 = 0\ } A \xrightarrow{\ R_3 = 2\ } \text{end} \qquad\Rightarrow\qquad G_0 = 1 + 0 + 2 = 3, \quad G_2 = 2

First-visit MC adds only the return 33 to the average of V(A)V(A). Every-visit MC adds 33 and 22. Both converge to vπ(A)v_\pi(A) as the number of visits grows, but they don’t behave the same on the way: the next exercise shows how.

Exercise 1.2 First visit or every visit? Math needed Compute: arithmetic, a small linear system, applying a formula of the pageend of high school Reason: expectations, inequalities, an argument in words: no new tools, but a chain of reasoningfirst year of university, with a first course in probability Prove: induction, limits, norms, fixed points: a proof, which can be skipped on a first readingabout two years of university math The level says which math is needed, not how long it takes.

An MDP has a single nonterminal state ss and a single action. From ss, the agent comes back to ss with probability pp, and reaches the terminal state with probability 1−p1 - p. Every transition gives a reward of +1+1, and γ=1\gamma = 1.

  1. You observe one episode that lasts 1010 steps, so its return is 1010. What is the first-visit MC estimate of vπ(s)v_\pi(s)? The every-visit estimate?
  2. What is the true value vπ(s)v_\pi(s), as a function of pp?
  3. A second episode lasts 22 steps. Give both estimates again, after the two episodes.
  4. Now use the constant step size update V(s)←V(s)+α [G−V(s)]V(s) \leftarrow V(s) + \alpha\,[G - V(s)], with first-visit returns, α=0.1\alpha = 0.1 and V(s)=0V(s) = 0 at the start. What is V(s)V(s) after each of the two episodes? Which step size would give back the first-visit average of question 3?
  5. Which of the two estimators is unbiased? Why is the other one biased?
Hint

The state ss is visited at t=0,1,…,9t = 0, 1, \dots, 9, and the return after the visit at time tt is the number of steps left, 10−t10 - t.

Hint

For question 2, write the Bellman equation of this one-state process: one reward of 11, then, with probability pp, the same value again.

Hint

For question 5, look at where the ten returns of the first episode come from: how many random draws produced them?

Checkpoint what you should get

After one episode: 1010 (first visit) and 5.55.5 (every visit). After two: 66 and 5812≈4.83\frac{58}{12} \approx 4.83. With α=0.1\alpha = 0.1: 11, then 1.11.1.

Solution
  1. The state is visited at t=0,…,9t = 0, \dots, 9, with returns 10,9,…,110, 9, \dots, 1. First visit: only t=0t = 0 counts, V(s)=10V(s) = 10. Every visit: V(s)=10+9+⋯+110=5510=5.5V(s) = \frac{10 + 9 + \dots + 1}{10} = \frac{55}{10} = 5.5.
  2. From ss, the number of remaining steps follows a geometric distribution with parameter 1−p1 - p, and each step gives +1+1, so vπ(s)=E[episode length]=11−pv_\pi(s) = \mathbb{E}[\text{episode length}] = \frac{1}{1 - p}. The Bellman equation gives the same, v=1+p vv = 1 + p\,v.
  3. The second episode gives the return 22 (first visit), or the returns 22 and 11 (every visit). First visit: 10+22=6\frac{10 + 2}{2} = 6. Every visit: 55+2+110+2=5812≈4.83\frac{55 + 2 + 1}{10 + 2} = \frac{58}{12} \approx 4.83.
  4. After episode 1: V=0+0.1 (10−0)=1V = 0 + 0.1\,(10 - 0) = 1. After episode 2: V=1+0.1 (2−1)=1.1V = 1 + 0.1\,(2 - 1) = 1.1. The step size α=1N(s)\alpha = \frac{1}{N(s)}, that is 11 then 12\frac{1}{2}, gives back the average: V=10V = 10, then 10+12(2−10)=610 + \frac{1}{2}(2 - 10) = 6. A constant α\alpha gives more weight to recent returns, which is useful only when the problem changes over time.
  5. First-visit is unbiased: each episode gives one return, an independent sample of GtG_t given St=sS_t = s. Every-visit is biased for a finite number of episodes: the returns of one episode are correlated (here 10,9,…,110, 9, \dots, 1 all come from the same draw), and long episodes contribute more terms. With p=12p = \frac{1}{2}, for instance, vπ(s)=2v_\pi(s) = 2, but the every-visit estimate after one episode of length nn is n+12\frac{n + 1}{2}, whose expectation is 2+12=1.5\frac{2 + 1}{2} = 1.5. It is still consistent: the bias vanishes as the number of episodes grows.
What to notice the take-away

The two estimators read the same data. First-visit throws away the correlated returns and stays unbiased; every-visit uses them all, and pays with a bias that only more episodes remove.

1.3 A constant step size

In the incremental form of section 1.1, 1N(s)\frac{1}{N(s)} comes from the definition of the mean, but replace it by a constant step size α\alpha, and you can control how older returns are gradually forgotten, which is useful when the policy or the environment drifts:

V(s)←V(s)+α [Gt−V(s)]V(s) \leftarrow V(s) + \alpha\,\big[G_t - V(s)\big]

Read it as: trust the new sample by a fraction α\alpha of the change.

On the equation GtG_t is called the target.

Average or constant step size
Noisy measurements Gk (σ = 2) of a hidden value v, and two incremental estimates starting from 0. The exact average V ← V + (1/N)[G − V] (green) is smooth, but after v jumps from 5 to 8 it barely moves, because it remembers every measurement. The constant step size V ← V + α[G − V] (orange) follows the jump, more noisily the larger α is.

This form general form of the equation will come back in every algorithm of this page and of Part 3.2; only the target changes.

Monte Carlo prediction has three properties to keep in mind for what follows:

An example: blackjack. Writing p(s′,r∣s,a)p(s', r \mid s, a) for every sequence of cards is tedious; simulating games is easy, which makes blackjack the classic Monte Carlo example. Evaluating the policy “stick on 20 or 21” over its 200 states, the value surface is still noisy after 10,000 games and smooth after 500,000: the high variance, in numbers.

What to look at Blackjack, evaluated by Monte Carlo: the value surfaces after 10,000 and 500,000 games

The policy sticks on 20 or 21 and hits otherwise; each game ends with a reward of +1+1, 00 or −1-1, and V(s)V(s) is the average over the games where the state was visited, with the state being the player’s sum, the card the dealer shows, and whether the player holds a usable ace. Look at the left column (usable ace), where states are rare: after 10,000 games the surface is still jagged, after 500,000 it is smooth. The wall at 20 and 21 is where sticking wins most of the time.

Four value surfaces for the blackjack policy that sticks on 20 or 21: with and without a usable ace, after 10,000 and 500,000 games. The surfaces are jagged after 10,000 games, especially with a usable ace, and smooth after 500,000, with high values for player sums of 20 and 21.
Value of the policy “stick on 20 or 21”, estimated by first-visit Monte Carlo, simulated for this page (Sutton and Barto, Figure 5.1).
Optional Monte Carlo as an observer: a control-engineering reading of the update Math needed Compute: arithmetic, a small linear system, applying a formula of the pageend of high school Reason: expectations, inequalities, an argument in words: no new tools, but a chain of reasoningfirst year of university, with a first course in probability Prove: induction, limits, norms, fixed points: a proof, which can be skipped on a first readingabout two years of university math The level says which math is needed, not how long it takes.

For an engineer, vπ(s)v_\pi(s) is a hidden constant, and each new return GtG_t is a noisy measurement of it. The incremental update is then an observer, which corrects its estimate with each new measurement:

V(s)←V(s)+α⏟gain [Gt−V(s)⏟innovation]V(s) \leftarrow V(s) + \underbrace{\alpha}_{\text{gain}}\,\big[\underbrace{G_t - V(s)}_{\text{innovation}}\big]

The dictionary: hidden state xx is vπ(s)v_\pi(s), the estimate x^\hat x is V(s)V(s), the measurement yy is the return GtG_t, the innovation y−x^y - \hat x is Gt−V(s)G_t - V(s), and the observer gain is the step size α\alpha.

The update as an observer
Vk = Vk−1 + α (Gk − Vk−1) as a block diagram: the measurement minus the previous estimate gives the innovation, the gain α scales it, and the result is added back to Vk−1. The unit delay z−1 closes the loop. Gray: the RL name of each signal.

Since the hidden state is constant, the observer reduces to a first-order filter, Vk=(1−α) Vk−1+α GkV_k = (1 - \alpha)\,V_{k-1} + \alpha\,G_k, with a single pole at 1−α1 - \alpha. With the gain 1N(s)\frac{1}{N(s)} it is the exact sample average, the Kalman filter of a constant. With a constant α\alpha it is an exponential moving average: smooth but slow for a small α\alpha, fast but noisy for a large one.

2. Temporal differences: learning from every step

The main drawback with Monte Carlo estimation is that one needs the fulln episode to compute the estimation. This section introduces Temporal Difference or TD that precisely aims at solving this issue with a technique called bootstrapping.

2.1 Bootstrapping

After each episode, Monte Carlo update pulls V(S)V(S) towards the return,

V(S)←V(S)+α [G−V(S)](MC)V(S) \leftarrow V(S) + \alpha\,\big[G - V(S)\big] \tag{MC}

Its problem is that GG is known only at the end of the episode. But recall that the return is recursive between two consecutive timesteps, and its second part has a name:

Gt=Rt+1+γ Gt+1,Eπ[Gt+1∣St+1]=vπ(St+1)G_t = R_{t+1} + \gamma\, G_{t+1}, \qquad \mathbb{E}_\pi\big[G_{t+1} \mid S_{t+1}\big] = v_\pi(S_{t+1})

Taking the expectation of the first equation, the value of a state is written with the value of the next one:

vπ(St)=Eπ[Rt+1+γ vπ(St+1)∣St]v_\pi(S_t) = \mathbb{E}_\pi\big[R_{t+1} + \gamma\, v_\pi(S_{t+1}) \mid S_t\big]

So after a single step, we can replace the unknown Gt+1G_{t+1} by our current estimate of its expectation, V(St+1)V(S_{t+1}). Updating an estimate from another estimate is called bootstrapping, and it gives the so-called TD(0) update:

V(St)←V(St)+α [Rt+1+γ V(St+1)⏟target−V(St)⏟error]V(S_t) \leftarrow V(S_t) + \alpha\,\big[\underbrace{\underbrace{R_{t+1} + \gamma\, V(S_{t+1})}_{\text{target}} - V(S_t)}_{\text{error}}\big]

For a given state StS_t being the state we met at time tt, the TD target Rt+1+γ V(St+1)R_{t+1} + \gamma\, V(S_{t+1}) is where V(St)V(S_t) is pulled to: one measured reward, then the estimate of what follows.

The difference between the target and the current estimate is the TD error,

δt=Rt+1+γ V(St+1)−V(St)\delta_t = R_{t+1} + \gamma\, V(S_{t+1}) - V(S_t)

a measure of novelty: how much better (δt>0\delta_t > 0) or worse (δt<0\delta_t \lt 0) the step went than the estimate predicted. The “(0)” of TD(0) means one real reward before bootstrapping; nn-step TD and TD(λ\lambda) look further ahead (section 3).

TD(0) takes the best of the two previous worlds. It samples, like Monte Carlo: no model is used but it uses samples from what the agent really experienced. And it bootstraps, like dynamic programming: its uses the current estimate in the target. Like DP, it updates after every transition, so it learns during the episode, and it does not even need the episode to end.

See how TD(0) can compute the value function on all states of a 3*3 grid example below :

Algorithm TD(0) prediction

Input: a policy π\pi to evaluate, a step size α∈(0,1]\alpha \in (0, 1]

  • V(s)V(s) arbitrary for every state ss, with V(terminal)=0V(\text{terminal}) = 0
  • repeat for each episode
    • initialize SS
    • repeat until SS is terminal
      • take the action AA given by π\pi in SS; observe RR and S′S'
      • V(S)←V(S)+α [R+γ V(S′)−V(S)]V(S) \leftarrow V(S) + \alpha\,\big[R + \gamma\, V(S') - V(S)\big]
      • S←S′S \leftarrow S'
TD(0) on a 3×3 grid, with the line being run highlighted. The agent starts top-left and moves at random until the exit, bottom-right; every move costs R = −1, γ = 1, α = 0.5. After each move, V(S) moves halfway to the TD target R + γV(S′): one real reward, then the estimate of the cell reached. The first episode runs line by line, the next ones faster.

There is no strict criterion of stopping as this process could run forever. We draw a subsequent number of runs that we consider meaningful.

2.2 TD(0) on a random walk

The random walk is a chain of five states, AA to EE, between two exits. Every episode starts in CC; the policy is a random move at each step, left or right; the reward is +1+1 on the right exit and 00 everywhere else, with γ=1\gamma = 1. The value of a state is then the probability of leaving on the right: vπ=16,26,…,56v_\pi = \frac{1}{6}, \frac{2}{6}, \dots, \frac{5}{6} from AA to EE.

Start with V=0.5V = 0.5 for AA to EE, V(end)=0V(\text{end}) = 0, and α=0.1\alpha = 0.1. Suppose the random policy takes right three times: C→D→E→endC \to D \to E \to \text{end}.

TD(0) on the random walk, one step at a time
The random walk: five states between two exits, start in C, left or right with probability ½, reward +1 only on the right exit, γ = 1. Under each state, its estimate V (bold) and its true value vπ (faint). The agent plays the episode of the text, C → D → E → end, with V = 0.5 everywhere and α = 0.1; each card shows the TD target, the TD error δ and the update of one step.

#does it make sense to have the 3 3 grid and this? very similar examples?

Only V(E)V(E) moves. The first two steps held no surprise: the estimates said 0.50.5, and the next state also said 0.50.5. The reward is felt only at the last step, and it travels back one state per episode. Monte Carlo, on the same episode, would have pulled CC, DD and EE all at once towards the return, 11.

Exercise 2.2 TD(0) by hand Math needed Compute: arithmetic, a small linear system, applying a formula of the pageend of high school Reason: expectations, inequalities, an argument in words: no new tools, but a chain of reasoningfirst year of university, with a first course in probability Prove: induction, limits, norms, fixed points: a proof, which can be skipped on a first readingabout two years of university math The level says which math is needed, not how long it takes.
  1. An agent observes Rt+1=3R_{t+1} = 3, with V(St)=5V(S_t) = 5, V(St+1)=6V(S_{t+1}) = 6, γ=0.9\gamma = 0.9 and α=0.1\alpha = 0.1. Compute the TD target, the TD error δt\delta_t, and the new value of V(St)V(S_t).
  2. Back to the random walk, after the episode C→D→E→endC \to D \to E \to \text{end} of the figure above. The coin says right three times again: compute the three TD(0) updates of this second episode.
Hint

Target first, Rt+1+γ V(St+1)R_{t+1} + \gamma\, V(S_{t+1}); then the error, target minus V(St)V(S_t); then move V(St)V(S_t) by α\alpha times the error.

Hint

In question 2, the estimates are those left by the first episode: V(E)=0.55V(E) = 0.55, the others 0.50.5. Update in the order of the steps, each with the latest values.

Checkpoint what you should get

Question 1: target 8.48.4, error 3.43.4, new value 5.345.34. Question 2: V(C)=0.5V(C) = 0.5, V(D)=0.505V(D) = 0.505, V(E)=0.595V(E) = 0.595.

Solution
  1. TD target: Rt+1+γV(St+1)=3+0.9×6=8.4R_{t+1} + \gamma V(S_{t+1}) = 3 + 0.9 \times 6 = 8.4. TD error: δt=8.4−5=3.4\delta_t = 8.4 - 5 = 3.4. New value: V(St)=5+0.1×3.4=5.34V(S_t) = 5 + 0.1 \times 3.4 = 5.34.
  2. Step 1, C→DC \to D: target 0+V(D)=0.50 + V(D) = 0.5, error 00, V(C)=0.5V(C) = 0.5. Step 2, D→ED \to E: target 0+V(E)=0.550 + V(E) = 0.55, error 0.050.05, V(D)=0.5+0.1×0.05=0.505V(D) = 0.5 + 0.1 \times 0.05 = 0.505. Step 3, E→endE \to \text{end}: target 1+0=11 + 0 = 1, error 1−0.55=0.451 - 0.55 = 0.45, V(E)=0.55+0.1×0.45=0.595V(E) = 0.55 + 0.1 \times 0.45 = 0.595.
What to notice the take-away

In the second episode, DD moves because it now sees the new V(E)V(E): the reward has traveled back one more state. CC will move only in the third episode. Monte Carlo would have moved all three states from the very first episode, but towards a target, 11, that is far from their true values, 0.50.5, 0.670.67 and 0.830.83.

3. Monte Carlo and TD comparison

Let’s quickly review the practical differences these algorithms have in practice as they influence different family of RL solutions.

3.1 Estimating one the way : Driving home example

An everyday example makes the computing difference concrete. Each evening, leaving the office, you predict how long it will take to get home, and you revise the prediction on the way. The reward of each leg is the minutes it took; the value of a state is the predicted number of minutes still to go, with γ=1\gamma = 1. The figure shows the elapsed time, the prediction of what remains, and their sum, the predicted total for both algorithms:

Driving home
Each bar is a state of the trip: time elapsed (gray) plus predicted time still to go, which sum to the predicted total. Both methods run on the same trip, side by side. Monte Carlo (left) waits until home and moves every prediction toward the actual 43 minutes; TD (right) moves each prediction toward the next one, on the way. Change the step size α (the book uses α = 1).

Monte Carlo waits until you are home. Then every prediction of the trip moves towards the actual total, 4343 minutes: you needed the whole episode to learn anything.

TD learns on the way: each prediction moves towards the next one. At the car, the “30 minutes” of the office already becomes “40”, because it rains, before you know how the trip ends.

3.2 Bias and variance

The two methods both correspond to different tradeoffs on various aspects :

Monte CarloTD(0)
update✗ at the end of the episode✓ after every step
bias✓ none✗ yes: it bootstraps on estimates
variance✗ high✓ low
continuing tasks✗ no✓ yes
sample efficiency✗ lower✓ usually higher
converges to vπv_\pi✓ yes✓ yes

Monte Carlo’s target, GtG_t, is a true sample of vπ(St)v_\pi(S_t), so it is unbiased; but it sums every random event until the end of the episode, so it is noisy. TD’s target, Rt+1+γV(St+1)R_{t+1} + \gamma V(S_{t+1}), contains a single random reward and a single random transition, so it varies much less; but V(St+1)V(S_{t+1}) is only an estimate, wrong at the beginning, so the target is biased.

In one sentence : Monte Carlo pays high variance to be unbiased; TD pays some bias for low variance, and learns online.

Watch it on random-walk example :

Bias and variance: Monte Carlo and TD(0) on the random walk
100 learners per method, each on its own random episodes of the random walk (Monte Carlo and TD(0) see the same ones), all starting from V = 0.5. Thin lines: 20 learners, whose spread is the variance; bold line: their average, whose gap to the true values (dashes) is the bias. Monte Carlo's targets are 0 or 1, so its learners scatter; TD's targets are a neighbor's estimate, so they stay together, and early on they share the same error. Below, the error, episode after episode.

Early on, Monte Carlo’s average is closer to the truth, but each of its learners is far from it; TD’s learners agree with each other, on a value that is wrong at first. After a few dozen episodes, the low variance wins: TD’s error is lower, at every step size.

3.3 RL in one plot: width and depth

Dynamic Programming (DP), Monte Carlo and TD all update V(s)V(s) towards a target. They differ in how they build it, among two aspects:

Dynamic programming is full width, one step deep: V(s)←∑aπ(a∣s)∑s′,rp(s′,r∣s,a) [r+γV(s′)]V(s) \leftarrow \sum_a \pi(a \mid s) \sum_{s', r} p(s', r \mid s, a)\,[r + \gamma V(s')], no sampling noise but the model is required.

TD(0) is one sample, one step deep: online, low variance, biased.

Monte Carlo is one sample, full depth: it never bootstraps, it is unbiased, and it needs complete episodes.

The fourth corner, full width and full depth, is exhaustive search (which is of course not an appealing solution 😁).

Two axes: width and depth
The backup diagram of each method: from the state being updated, the transitions its target reads, lit from the leaves back to the root. Left column, one sampled transition: no model needed. Right column, every action and next state, weighted by π and p: the model is needed. Top row, one step, then the current estimate: these methods bootstrap. Bottom row, to the end of the episode: no bootstrapping. Click a corner for its target.

The next exercise shows that the difference is not only about speed: on the same data, Monte Carlo and TD can give different answers, and it is worth knowing which one to trust.

Exercise 3.3 You are the predictor Math needed Compute: arithmetic, a small linear system, applying a formula of the pageend of high school Reason: expectations, inequalities, an argument in words: no new tools, but a chain of reasoningfirst year of university, with a first course in probability Prove: induction, limits, norms, fixed points: a proof, which can be skipped on a first readingabout two years of university math The level says which math is needed, not how long it takes.

You observe the following 88 episodes of an unknown Markov reward process with two states, AA and BB (γ=1\gamma = 1; each episode is written as state, reward, state, reward, …):

A,0,B,0B,1B,1B,1B,1B,1B,1B,0\begin{array}{ll} A, 0, B, 0 & \qquad B, 1 \\ B, 1 & \qquad B, 1 \\ B, 1 & \qquad B, 1 \\ B, 1 & \qquad B, 0 \end{array}

The first episode starts in AA, gets 00, moves to BB, gets 00 and ends. The seven others start in BB and end right away.

  1. What is the best estimate of V(B)V(B)? Justify.
  2. Batch Monte Carlo (the average of the observed returns): what is V(A)V(A)?
  3. Batch TD(0) (TD(0) updates repeated over these 88 episodes until VV stops changing): what is V(A)V(A)?
  4. Draw the Markov process that best explains the data (the maximum-likelihood model). Which of the two answers for V(A)V(A) is the exact value of this model? Which one minimizes the squared error on the observed returns?
  5. Which answer would you trust more to predict the next episode that starts in AA? Relate your answer to the bias and variance of Monte Carlo and TD.
Hint

Count: in how many of the 88 episodes was BB visited, and how many times did it end with a reward of 11?

Hint

At the fixed point of batch TD(0), the average TD error on every transition is zero. There is only one transition from AA.

Checkpoint what you should get

V(B)=0.75V(B) = 0.75 for both methods; V(A)=0V(A) = 0 for batch Monte Carlo, V(A)=0.75V(A) = 0.75 for batch TD(0).

Solution
  1. BB was seen 88 times; the process ended with reward 11 in 66 of them and 00 in 22. Both methods agree: V(B)=68=0.75V(B) = \frac{6}{8} = 0.75.
  2. Batch Monte Carlo: the only return observed from AA is 0+0=00 + 0 = 0, so V(A)=0V(A) = 0.
  3. Batch TD(0): the only transition from AA is A→BA \to B with reward 00. At the fixed point its TD error is zero, 0+V(B)−V(A)=00 + V(B) - V(A) = 0, so V(A)=V(B)=0.75V(A) = V(B) = 0.75.
  4. Maximum-likelihood model: from AA, go to BB with probability 11 and reward 00; from BB, terminate with reward 11 (probability 0.750.75) or 00 (probability 0.250.25). In this model, the value of AA is exactly 0.750.75: that is the batch TD answer, called the certainty-equivalence estimate. The batch Monte Carlo answer, V(A)=0V(A) = 0, is the one that minimizes the squared error on the observed returns.
  5. The TD answer, 0.750.75. The Markov property says that what happens after BB does not depend on how BB was reached, so the 88 observations of BB tell us about AA too. Monte Carlo uses only the single episode that started in AA: unbiased, but one sample is a very noisy estimate (high variance). TD reuses the estimate of BB by bootstrapping: biased if V(B)V(B) were wrong, but with much less variance.
What to notice the take-away

Monte Carlo fits the returns it saw; TD fits the Markov process that produced them. When the problem really is Markov, TD’s answer uses more of the data, which is one reason it often learns faster.

Optional Between TD(0) and Monte Carlo: n-step returns and TD(λ) Math needed Compute: arithmetic, a small linear system, applying a formula of the pageend of high school Reason: expectations, inequalities, an argument in words: no new tools, but a chain of reasoningfirst year of university, with a first course in probability Prove: induction, limits, norms, fixed points: a proof, which can be skipped on a first readingabout two years of university math The level says which math is needed, not how long it takes.

TD(0) and Monte Carlo are the two ends of a range. The nn-step return uses nn real rewards, then bootstraps:

Gt(n)=Rt+1+γRt+2+⋯+γn−1Rt+n+γn V(St+n)G_t^{(n)} = R_{t+1} + \gamma R_{t+2} + \dots + \gamma^{n-1} R_{t+n} + \gamma^n\, V(S_{t+n})

With n=1n = 1 it is the TD(0) target; when nn reaches the end of the episode, it is the Monte Carlo return.

The λ\lambda-return averages all of them, with geometric weights that sum to 11:

Gtλ=(1−λ)∑n=1∞λn−1 Gt(n)G_t^\lambda = (1 - \lambda) \sum_{n=1}^{\infty} \lambda^{n-1}\, G_t^{(n)}

and the update V(St)←V(St)+α [Gtλ−V(St)]V(S_t) \leftarrow V(S_t) + \alpha\,[G_t^\lambda - V(S_t)] is TD(0) for λ=0\lambda = 0 and Monte Carlo for λ=1\lambda = 1. Written this way (the forward view), it needs the episode to end, like Monte Carlo.

More in Sutton and Barto, chapters 7 and 12.

4. Quick wrap-up before 3.2

In a few lines:

Part 3.2: Learning to Act uses these estimates to find a good policy, still without a model: exploration, Monte Carlo control, SARSA and Q-learning.