Part I · Foundations of Sequential Decision-Making
6.Learning from Experience: Monte Carlo & Temporal-Difference
“If one had to identify one idea as central and novel to reinforcement learning, it would undoubtedly be temporal-difference learning.”
Take away the blueprint. Rusty gets no transition probabilities, no reward function he can inspect — only the ability to act and observe what happens. Remarkably, almost everything survives. Monte Carlo methods learn from complete episodes by averaging returns. Temporal-difference methods do something stranger and more powerful: they update a guess toward another guess, learning from single transitions without waiting for the outcome. This chapter derives both, proves what can be proved, and confronts the systematic optimism that makes Q-learning overestimate everything it values.
Foundation
First-visit MC and its unbiasedness, importance sampling with variance analysis, the TD(0) update, SARSA/Expected SARSA/Q-learning, Watkins' convergence theorem, and the double-estimator argument.
Conceptual
Rusty learning the warehouse from scratch — value bleeding backwards from the dock as the TD error propagates, with δ and the return streaming live.
Practical
rl-tabular's model-free learners over the Chapter 4 Env trait, with the update returning δ so dashboards can display the learning signal itself.
After this chapter you can
- Explain why first-visit Monte Carlo is an unbiased estimator of v_π, and what it costs in variance
- Derive the importance-sampling correction for off-policy evaluation and explain why its variance can be infinite
- Write the TD(0) update and identify the bias–variance trade it makes against Monte Carlo
- State the difference between SARSA and Q-learning precisely, in terms of which policy the target evaluates
- Explain maximization bias, prove it occurs even with unbiased estimates, and show how Double Q-learning removes it
- Recognize GLIE conditions and their role in convergence guarantees
6.1 No model, no problem — the Monte Carlo idea
Chapter 5 needed to compute expectations. Without it, one option remains: sample.
The value is by definition an average of returns. So run episodes, record the returns that actually followed each state, and average them. That is Monte Carlo prediction, and its correctness follows from the law of large numbers rather than from any property of the MDP.
First-visit MC averages the returns following the first visit to in each episode. Its estimator is unbiased: each first-visit return is an independent sample from the distribution whose mean is , so the average converges to as the number of visits grows, with standard error falling as .
6.2 Off-policy evaluation and importance sampling
A robot often needs to evaluate one policy while behaving according to another — estimate the value of an aggressive policy while running a safe one, or reuse data collected last week. This is off-policy learning, and it is the setting that dominates robotics because data is expensive enough that you want to reuse all of it.
Let be the behaviour policy generating the data and the target policy we want to evaluate. The returns we observe come from the wrong distribution. Importance sampling reweights them by the ratio of trajectory probabilities:
Notice that the environment dynamics cancel: appears identically in numerator and denominator. Only the policy probabilities survive, which is what makes this usable without a model. Then
so ordinary importance sampling — averaging — is unbiased.
6.3 Temporal difference: learning a guess from a guess
Monte Carlo waits for the episode to end. TD does not, and the trick is disarmingly simple.
The return recursion from Chapter 4 says . Monte Carlo uses the observed as its target. TD substitutes the current estimate for the tail:
That is TD(0). It updates immediately after one transition, needs no episode boundary, and works on continuing tasks.
The quantity is the TD error, and it deserves a name because it recurs everywhere in this book. It measures the surprise: how much better or worse the transition turned out than the current estimate predicted. When everywhere, the value function is self-consistent and satisfies the Bellman equation.
6.4 Control: SARSA, Expected SARSA, Q-learning
To control rather than merely predict, learn action values and follow the GPI pattern from Chapter 5: estimate , act greedily-ish with respect to it, repeat.
Three algorithms differ only in what they put in the target.
SARSA uses the action actually taken next:
It is on-policy: the target evaluates the same -greedy policy the agent is executing, exploration included.
Q-learning uses the best action available, whether or not it is taken:
It is off-policy: the target evaluates the greedy policy while the agent behaves -greedily.
Expected SARSA replaces the sample with its expectation under the policy:
eliminating the variance due to sampling at the cost of a sum over actions. It usually dominates SARSA, and reduces to Q-learning when is greedy.
Learning without a model
ch06-train-liveRusty has no map. Every value on the heatmap was bootstrapped from experience alone.
Episodes
0
Last return
0
not started
Mean |δ| (last ep.)
0
magnitude of the learning signal
Current ε
0.200
exploration remaining
Press play and watch the mechanism directly. Value appears at the dock and bleeds backwards, one cell per episode-ish, because that is how far a one-step TD error can carry information. Early arrows are nonsense — every is zero and ties break randomly. The policy sharpens only where the TD error has actually reached.
Then set and watch the run stall. With no exploration, Rusty commits to the first corridor that ever paid off and never discovers the better one. This is the Chapter 3 dilemma, now with states.
6.5 Does it converge?
Yes, under conditions worth knowing precisely.
Theorem 6.1— Convergence of tabular Q-learning (Watkins & Dayan, 1992)
In a finite MDP, tabular Q-learning converges to with probability 1, provided:
- every state–action pair is visited infinitely often;
- the learning rates satisfy the Robbins–Monro conditions, and for every pair;
- rewards are bounded.
The proof combines the two things Chapter 2 built. The Bellman optimality operator is a -contraction, so the expected update moves toward ; stochastic approximation theory then shows the noisy sampled updates track the expected ones almost surely, given Robbins–Monro step sizes. The full argument is in Watkins and Dayan and in Bertsekas & Tsitsiklis.
Condition 1 is the one that bites. "Visited infinitely often" requires persistent exploration, which is why must decay slowly — the GLIE conditions (Greedy in the Limit with Infinite Exploration): explore forever, but let exploration vanish so the policy becomes greedy in the limit. A schedule like satisfies both.
6.6 Maximization bias and the double estimator
One more phenomenon, because it explains a family of algorithms in Chapter 9.
Q-learning's target contains . Suppose all the estimates are unbiased but noisy. Is the max unbiased?
No. By Jensen's inequality applied to the convex max function,
Taking the maximum of noisy estimates systematically overestimates the true maximum. The max operator preferentially selects whichever action got lucky, and luck does not persist — but the inflated estimate does, and it propagates through every subsequent backup.
This is maximization bias, and it is not a small effect. With many actions and noisy returns, the overestimation compounds through bootstrapping until the value function is meaningfully optimistic everywhere.
Proposition 6.2— Double estimation removes the bias
Maintain two independent estimates and . Use one to select the maximizing action and the other to evaluate it:
Since is independent of the selection, — the estimate is no longer biased upward.
Double Q-learning implements this by keeping two tables and flipping a coin each step to decide which is updated and which evaluates. It costs twice the memory and nothing in computation, and the fix carries directly into deep RL: Double DQN in Chapter 9 is this exact idea with the target network playing the role of the second estimator, and TD3's clipped double-Q in Chapter 11 is the continuous-control version.
use rl_core::{Env, Transition};
pub struct QLearning {
q: Vec<f64>, // flat: state * n_actions + action
n_actions: usize,
alpha: f64,
gamma: f64,
}
impl QLearning {
#[inline]
fn idx(&self, s: usize, a: usize) -> usize { s * self.n_actions + a }
fn max_q(&self, s: usize) -> f64 {
(0..self.n_actions)
.map(|a| self.q[self.idx(s, a)])
.fold(f64::NEG_INFINITY, f64::max)
}
/// One off-policy update. Returns the TD error δ — the learning signal.
pub fn update(&mut self, s: usize, a: usize, t: &Transition<usize>) -> f64 {
// The target bootstraps from the GREEDY action, whatever we actually do next.
let target = if t.done {
t.reward
} else {
t.reward + self.gamma * self.max_q(t.next_state)
};
let i = self.idx(s, a);
let delta = target - self.q[i];
self.q[i] += self.alpha * delta;
delta
}
}6.7 Chapter bridge
Rusty can now learn without a map. He samples, bootstraps, and improves — the GPI pattern of Chapter 5 with expectations replaced by samples.
But we have accepted a stark choice. Monte Carlo waits for the whole return: unbiased, high variance, no bootstrapping. TD(0) uses one step: low variance, biased, fast. Nothing in the mathematics says those are the only options, and they are not.
Chapter 7 puts a dial between them. The -return blends every -step return at once; eligibility traces make the blend cheap enough to compute online. And then a second idea: if we can learn a model from experience, we can plan with it as in Chapter 5 while continuing to learn as in this chapter — Dyna, the architecture that unifies both halves of Part I.
- 01Foundation●●●First-visit MC is unbiased
Prove that the first-visit MC estimator of v_π(s) is unbiased. Then explain precisely why the every-visit estimator is biased, and why the bias nonetheless vanishes asymptotically.
- 02Foundation●●●Infinite variance
Construct a two-state MDP with a behaviour policy b and target π for which ordinary importance sampling has infinite variance. Show the variance integral diverges, then verify empirically that weighted importance sampling behaves acceptably on the same problem.
- 03Foundation●●●MC error as a sum of TD errors
Prove the identity G_t − V(S_t) = Σ_{k≥t} γ^{k−t} δ_k, assuming V does not change during the episode. This identity is the bridge to Chapter 7 — make sure you can produce it from memory.
- 04Foundation●●●Maximization bias by construction
Build a single-state MDP with several actions whose true values are all zero but whose sampled returns are noisy. Show analytically that Q-learning’s estimate is positive in expectation, and compute how it grows with the number of actions.
- 05Conceptual●●●The backward wave
In the live training dashboard, note the episode at which the cell farthest from the dock first acquires a non-zero value under Q-learning. Increase α and repeat. Explain the relationship you observe and its limit.
- 06Conceptual●●●SARSA versus Q-learning under risk
Set the slip probability high and compare the greedy policies SARSA and Q-learning converge to near the shelves. Which hugs the obstacles? Explain in terms of what each algorithm’s target evaluates.
- 07Practical●●●Expected SARSA
Implement Expected SARSA and compare it against SARSA across learning rates from 0.05 to 0.6. Expected SARSA should tolerate larger α — explain why in terms of the variance of the target.
- 08Practical●●●Measure the overestimation
Instrument Q-learning and Double Q-learning to log max_a Q(s,a) against the true q*(s) computed by Chapter 5’s value iteration. Plot the gap over training. The single-estimator version should sit visibly above the truth for a long time.
References
Baseline references
- Sutton, R. S. & Barto, A. G. (2018). Reinforcement Learning: An Introduction. MIT Press, 2nd editionChapter 5 (Monte Carlo methods, importance sampling) and Chapter 6 (TD learning, SARSA, Q-learning, Expected SARSA, maximization bias).
- Kober, J., Bagnell, J. A. & Peters, J. (2013). Reinforcement Learning in Robotics: A Survey. International Journal of Robotics Research 32(11)§2.2.1 value-function approaches, and §3.2 on why sample cost dominates algorithm choice in robotics.
Further reading & modern sources
- Sutton, R. S. (1988). Learning to predict by the methods of temporal differences. Machine Learning 3(1)The paper that introduced TD learning.
- Watkins, C. J. C. H. & Dayan, P. (1992). Q-learning. Machine Learning 8The convergence proof of Theorem 6.1.
- van Hasselt, H. (2010). Double Q-learning. NeurIPS 23Maximization bias identified and fixed — the ancestor of Double DQN (Chapter 9) and TD3 (Chapter 11).
- Rummery, G. A. & Niranjan, M. (1994). On-line Q-learning using connectionist systems. Cambridge University Engineering Department, Technical ReportThe origin of SARSA, under its original name.
- Bertsekas, D. P. & Tsitsiklis, J. N. (1996). Neuro-Dynamic Programming. Athena ScientificThe rigorous stochastic-approximation treatment underlying every convergence claim in this chapter.
