Monte Carlo Methods
Our first learning methods: no model of the environment is needed — only experience (sample episodes). Values are estimated by averaging complete returns, so MC works for episodic tasks and updates episode-by-episode. MC methods do not bootstrap.
- Why MC needs no model, why it only works for episodic tasks, and why it does not bootstrap.
- First-visit vs every-visit MC; their convergence properties.
- Why we estimate action values without a model, and the problem of maintaining exploration.
- Three ways to explore: exploring starts, on-policy ε-soft, off-policy with a behaviour policy.
- Importance-sampling ratio (5.3) — why the dynamics cancel; ordinary (5.5) vs weighted (5.6) IS: bias, variance.
- The incremental weighted update (5.8) and the off-policy MC control algorithm (and why $W \leftarrow W/b$).
- Advantages of MC over DP.
Why Monte Carlo?
- Requires only experience — sample sequences of states, actions, rewards from actual interaction (no model at all) or simulated interaction (a sample model that only generates transitions, not the full distributions DP needs).
- Defined here only for episodic tasks, so well-defined returns exist. Values and policies change only at the end of an episode — incremental episode-by-episode, not step-by-step.
- Like bandits, MC averages samples per state–action pair — but now there are many interrelated "bandits": the return after an action depends on later actions, which are also being learned ⇒ nonstationary from the earlier state's viewpoint. Handled with GPI.
5.1 Monte Carlo prediction
Estimate $v_\pi(s)$ by averaging the returns observed after visits to $s$. The first occurrence of $s$ in an episode is its first visit.
| First-visit MC | Every-visit MC | |
|---|---|---|
| Averages returns after… | only the first visit to $s$ in each episode | every visit to $s$ |
| Samples | i.i.d. unbiased estimates of $v_\pi(s)$; error std. falls as $1/\sqrt n$ | Not independent (biased for finite data) |
| Convergence | To $v_\pi(s)$ by the law of large numbers | Also to $v_\pi(s)$ (quadratically) |
| History / use | Most studied (since 1940s); used in this chapter | Extends more naturally to function approximation and eligibility traces |
Input: a policy π to be evaluated Initialize: V(s) ∈ ℝ, arbitrarily, for all s ∈ S Returns(s) ← an empty list, for all s ∈ S Loop forever (for each episode): Generate an episode following π: S₀, A₀, R₁, S₁, A₁, R₂, …, S_{T−1}, A_{T−1}, R_T G ← 0 Loop for each step of episode, t = T−1, T−2, …, 0: G ← γG + R_{t+1} Unless S_t appears in S₀, S₁, …, S_{t−1}: // drop this check → every-visit MC Append G to Returns(S_t) V(S_t) ← average(Returns(S_t))
Example 5.1 — Blackjack
- Episodic, undiscounted (γ = 1); reward +1 win, −1 lose, 0 draw (also the return). Actions: hit or stick. Infinite deck. Dealer sticks on ≥ 17.
- State = (player sum 12–21, dealer's showing card A–10, usable ace?) → 200 states. A usable ace counts as 11 without busting.
- Evaluate the policy "stick only on 20 or 21". Even though we know the rules completely, computing $p(s',r\mid s,a)$ for DP would be complex and error-prone; generating sample games is easy.
5.1 Values jump up for player sums 20 and 21 because the policy sticks there and usually wins. They drop for the column where the dealer shows an ace — the dealer's strongest card. Values are higher with a usable ace (low sums) because the player can hit without risk of busting (the ace can revert to 1).
5.2 Every-visit gives the same results here: in blackjack a state can never recur within an episode (the sum or the usable-ace flag always changes), so every visit is a first visit.
Backup diagram and key properties
- DP's diagram shows all possible one-step transitions; MC's shows only the sampled transitions of one episode, but all the way to the end.
- Estimates for each state are independent — MC does not bootstrap.
- Cost of estimating one state is independent of the number of states: you can generate episodes from the states of interest only (soap-bubble example 5.2: random walks to the boundary estimate the surface height at one point).
- Exercise 5.3: the MC backup for $q_\pi$ has a state–action pair as root, followed by the trajectory to termination.
5.2 Monte Carlo estimation of action values
With a model, $v$ suffices: look one step ahead and choose the best action. Without a model, state values alone are not sufficient — you need $q(s,a)$ to pick actions. So the primary goal of MC control is to estimate $q_*$.
Same methods, but visits are to state–action pairs. Problem: under a deterministic π, only one action per state is ever observed, so other actions' estimates never improve. This is the problem of maintaining exploration.
Exploring starts (ES): every episode starts in a state–action pair, and every pair has non-zero probability of being the start ⇒ all pairs visited infinitely often. Useful in simulation, but cannot be relied on when learning from real interaction.
5.3 Monte Carlo control
Policy improvement is greedy w.r.t. the current action-value function — no model needed:
Two unrealistic assumptions give the easy convergence guarantee: (1) exploring starts, (2) infinitely many episodes per evaluation. Remove (2) like value iteration does — don't complete evaluation; alternate evaluation and improvement episode by episode:
Initialize: π(s) ∈ A(s) (arbitrarily), for all s ∈ S Q(s,a) ∈ ℝ (arbitrarily), for all s ∈ S, a ∈ A(s) Returns(s,a) ← empty list, for all s ∈ S, a ∈ A(s) Loop forever (for each episode): Choose S₀ ∈ S, A₀ ∈ A(S₀) randomly such that all pairs have probability > 0 Generate an episode from S₀, A₀, following π: S₀, A₀, R₁, …, S_{T−1}, A_{T−1}, R_T G ← 0 Loop for each step of episode, t = T−1, T−2, …, 0: G ← γG + R_{t+1} Unless the pair S_t, A_t appears in S₀, A₀, S₁, A₁, …, S_{t−1}, A_{t−1}: Append G to Returns(S_t, A_t) Q(S_t, A_t) ← average(Returns(S_t, A_t)) π(S_t) ← argmax_a Q(S_t, a)
Exploring starts pick dealer card, player sum, usable ace and the first action uniformly at random. Initial policy: stick only on 20 or 21; Q = 0.
5.4 Monte Carlo control without exploring starts (on-policy)
On-policy methods evaluate or improve the same policy that is used to make decisions (MC ES is on-policy). Off-policy methods evaluate or improve a policy different from the one that generates the data.
On-policy control uses soft policies: $\pi(a\mid s)>0$ for all $s,a$, gradually shifted toward a deterministic optimal policy. ε-soft: $\pi(a\mid s)\ge\varepsilon/|\mathcal A(s)|$. ε-greedy policies (non-greedy actions get $\varepsilon/|\mathcal A(s)|$, greedy gets $1-\varepsilon+\varepsilon/|\mathcal A(s)|$) are the ε-soft policies closest to greedy.
GPI only requires moving the policy toward greedy, so we move it to ε-greedy:
Algorithm parameter: small ε > 0 Initialize: π ← an arbitrary ε-soft policy Q(s,a) ∈ ℝ (arbitrarily), for all s ∈ S, a ∈ A(s) Returns(s,a) ← empty list, for all s ∈ S, a ∈ A(s) Repeat forever (for each episode): Generate an episode following π: S₀, A₀, R₁, …, S_{T−1}, A_{T−1}, R_T G ← 0 Loop for each step of episode, t = T−1, T−2, …, 0: G ← γG + R_{t+1} Unless the pair S_t, A_t appears in S₀, A₀, …, S_{t−1}, A_{t−1}: Append G to Returns(S_t, A_t) Q(S_t, A_t) ← average(Returns(S_t, A_t)) A* ← argmax_a Q(S_t, a) (with ties broken arbitrarily) For all a ∈ A(S_t): π(a|S_t) ← 1 − ε + ε/|A(S_t)| if a = A* ε/|A(S_t)| if a ≠ A*
Any ε-greedy policy π′ w.r.t. $q_\pi$ is an improvement over any ε-soft π:
(The max is ≥ any weighted average with non-negative weights summing to 1.) Equality holds only when π is optimal among ε-soft policies — shown by "moving the ε-softness inside the environment" (with prob. ε the environment re-picks the action at random); the best general policy there equals the best ε-soft policy here. Trade-off: we only reach the best ε-soft policy, but we no longer need exploring starts.
5.5 Off-policy prediction via importance sampling
They want action values for optimal behaviour, but must behave non-optimally to explore. On-policy is a compromise (learns about a near-optimal policy that still explores). Off-policy uses two policies: the target policy π (learned about; becomes optimal; may be deterministic) and the behaviour policy $b$ (generates data; exploratory).
| On-policy | Off-policy | |
|---|---|---|
| Policies | One: π both acts and is learned | Two: target π, behaviour $b$ |
| Complexity | Simpler; considered first | Needs importance sampling and extra notation |
| Variance / speed | Lower variance | Often greater variance, slower to converge |
| Generality | Special case ($\pi=b$) | More powerful: learn from a human expert, a non-learning controller, or about many policies |
| What is learned | Best ε-soft policy | Deterministic optimal policy |
Coverage assumption: $\pi(a\mid s)>0 \Rightarrow b(a\mid s)>0$. So $b$ must be stochastic wherever it differs from π; π may be deterministic (typically greedy).
The unknown dynamics cancel — the ratio depends only on the two policies and the observed sequence. It corrects the expectation:
Number time steps continuously across episodes; $\mathcal T(s)$ = time steps at which $s$ is visited (first visits only for first-visit), $T(t)$ = first termination after $t$.
| Ordinary IS (5.5) | Weighted IS (5.6) | |
|---|---|---|
| After one return | $\rho G$ — can be extreme (ratio 10 ⇒ 10× the return) | Exactly $G$ (ratio cancels) — reasonable, but its expectation is $v_b$ |
| Bias (first-visit) | Unbiased | Biased (bias → 0 asymptotically) |
| Variance | Can be unbounded (ratios unbounded) | Bounded: max weight on any return is 1; variance → 0 even if ratio variance is infinite (bounded returns) |
| In practice | Easier to extend to function approximation | Strongly preferred — dramatically lower variance |
| Every-visit versions | Both biased (bias → 0); often preferred in practice (no need to track first visits, easier to approximate) | |
State: dealer shows 2, player sum 13 with a usable ace. Behaviour: hit/stick with prob. ½ each. Target: stick only on 20 or 21. True value ≈ −0.27726. Mean-square error averaged over independent runs (log x-axis).
Example 5.5 — infinite variance
One state $s$; right → terminate with reward 0; left → back to $s$ w.p. 0.9, or terminate with +1 w.p. 0.1. Target: always left ⇒ $v_\pi(s)=1$. Behaviour: left/right ½ each. Episodes ending with right have ρ = 0; an episode of $k+1$ lefts has ρ = $2^{k+1}$. The second moment of the scaled return:
Ordinary IS estimates fail to converge even after millions of episodes; weighted IS gives exactly 1 after the first episode ending with left. Trajectories with loops easily cause this.
5.6 Incremental implementation
On-policy MC and ordinary IS: use the Chapter 2 incremental mean on (scaled) returns. Weighted IS needs a weighted average. With returns $G_1,\dots,G_{n-1}$ and weights $W_k$ (e.g. $\rho$):
Exercise 5.10 derivation: $V_{n+1}=\frac{C_{n-1}V_n+W_nG_n}{C_n}=\frac{(C_n-W_n)V_n+W_nG_n}{C_n}=V_n+\frac{W_n}{C_n}(G_n-V_n)$. Note the step size here is $W_n/C_n$ — a data-dependent, decreasing step size.
Input: an arbitrary target policy π Initialize, for all s ∈ S, a ∈ A(s): Q(s,a) ∈ ℝ (arbitrarily) C(s,a) ← 0 Loop forever (for each episode): b ← any policy with coverage of π Generate an episode following b: S₀, A₀, R₁, …, S_{T−1}, A_{T−1}, R_T G ← 0 W ← 1 Loop for each step of episode, t = T−1, T−2, …, 0, while W ≠ 0: G ← γG + R_{t+1} C(S_t,A_t) ← C(S_t,A_t) + W Q(S_t,A_t) ← Q(S_t,A_t) + (W / C(S_t,A_t)) [G − Q(S_t,A_t)] W ← W · π(A_t|S_t) / b(A_t|S_t)
5.7 Off-policy Monte Carlo control
Initialize, for all s ∈ S, a ∈ A(s): Q(s,a) ∈ ℝ (arbitrarily) C(s,a) ← 0 π(s) ← argmax_a Q(s,a) (with ties broken consistently) Loop forever (for each episode): b ← any soft policy Generate an episode using b: S₀, A₀, R₁, …, S_{T−1}, A_{T−1}, R_T G ← 0 W ← 1 Loop for each step of episode, t = T−1, T−2, …, 0: G ← γG + R_{t+1} C(S_t,A_t) ← C(S_t,A_t) + W Q(S_t,A_t) ← Q(S_t,A_t) + (W / C(S_t,A_t)) [G − Q(S_t,A_t)] π(S_t) ← argmax_a Q(S_t,a) (with ties broken consistently) If A_t ≠ π(S_t) then exit inner Loop (proceed to next episode) W ← W · 1 / b(A_t|S_t)
- Exercise 5.11 — why 1/b, not π/b? π is deterministic greedy. If $A_t\ne\pi(S_t)$ the ratio would be 0 and we exit the loop; otherwise $\pi(A_t|S_t)=1$, so the factor is $1/b(A_t|S_t)$.
- Weakness: learns only from the tails of episodes after the last non-greedy action. If non-greedy actions are common, learning is slow, especially for early states of long episodes. Remedy: TD learning (Ch 6), or discounting-aware IS (§5.8).
- To converge to π*, every (s,a) needs infinitely many returns: choose $b$ ε-soft. $b$ may even change between or within episodes.
5.8–5.9 *Discounting-aware and per-decision importance sampling
Discounting-aware IS: if γ < 1 and episodes are long, scaling $G_0$ by all 100 ratio factors is wasteful — with γ = 0, $G_0=R_1$ only needs $\pi(A_0|S_0)/b(A_0|S_0)$. Treat discounting as a probability of termination and decompose the return into flat partial returns $\bar G_{t:h}\doteq R_{t+1}+\dots+R_h$:
Each $\bar G_{t:h}$ is then scaled only by the truncated ratio $\rho_{t:h-1}$ (estimators 5.9 ordinary, 5.10 weighted). Identical to §5.5 when γ = 1.
Per-decision IS (works even with γ = 1): each reward $R_{t+k}$ only needs the ratios up to the action that produced it, because later factors have expected value 1: $\E\big[\tfrac{\pi(A_k|S_k)}{b(A_k|S_k)}\big]=\sum_a b(a|S_k)\tfrac{\pi(a|S_k)}{b(a|S_k)}=1$ (5.13).
$V(s)=\sum_{t\in\mathcal T(s)}\tilde G_t/|\mathcal T(s)|$ is unbiased (first-visit) with possibly lower variance. No consistent per-decision weighted version is known.
5.10 Summary — MC vs DP
| Dynamic programming (Ch 4) | Monte Carlo (Ch 5) | |
|---|---|---|
| Model | Needs full distributions $p(s',r|s,a)$ | None (actual experience) or only a sample model (simulation) |
| Update | Expected update, one step, all successors | Sample update, whole episode, one trajectory |
| Bootstraps? | Yes | No |
| Focus on a subset of states | Must sweep (or async) | Easy and efficient — start episodes there |
| Markov violations | Hurt (relies on successor estimates) | Less harmed (no bootstrapping) |
| Task types | Episodic and continuing | Episodic only |
| When updates happen | Per sweep / per state | End of episode |
Four advantages of MC over DP: (1) learn from actual interaction with no model; (2) work with simulation/sample models; (3) easy to focus on a small subset of states; (4) less harmed by violations of the Markov property.
Hyperparameters and design choices
| Choice | Options | Effect |
|---|---|---|
| Step size | Sample average $1/N(s,a)$; or constant α ("constant-α MC", eq. 6.1); weighted: $W/C$ | $1/N$ converges for a fixed policy; constant α weights recent returns more — better while the policy (hence returns) keeps changing in control. |
| ε (on-policy) | Fixed or decaying | Larger ε explores more but the learned policy is only best among ε-soft policies (performance capped). Decay ε → 0 for convergence to π*. |
| Behaviour policy $b$ | Any soft policy with coverage | The more $b$ differs from π, the larger the IS ratios ⇒ higher variance; off-policy MC control only learns from episode tails where $b$ agreed with π. |
| IS variant | Ordinary vs weighted; per-decision; discounting-aware | Weighted: biased but low variance (preferred). Ordinary: unbiased but possibly infinite variance. |
| First- vs every-visit | Every-visit is simpler and generalises to function approximation. | |
| γ | Usually 1 (episodic) | γ < 1 enables discounting-aware IS variance reduction. |
Self-test
Ex 5.5 — One non-terminal state, one action: back to itself w.p. p, terminate w.p. 1−p; reward +1 every transition, γ = 1. One episode of 10 steps (return 10). First-visit and every-visit estimates?
First-visit: only the first visit counts, return 10 → 10. Every-visit: returns from the 10 visits are 10, 9, …, 1 → average 5.5.
Ex 5.7 — Why did the weighted IS error first increase in Figure 5.3?
Estimates start at 0 (error ≈ 0.077). Early on, weighted IS sets the estimate to the few returns with non-zero weight — essentially single ±1 outcomes (it is biased toward these samples), so the squared error jumps up before averaging over more episodes brings it down.
Ex 5.8 — With every-visit MC in Example 5.5, is the variance still infinite?
Yes. Every-visit adds the scaled returns of later visits within the same episode; the term for the first visit (and all long-episode terms with ratio $2^k$) still has an infinite second moment, and adding more non-negative terms cannot make it finite.
Why can't we use state values alone for model-free control?
Choosing an action from $v$ needs a one-step lookahead $\sum p(s',r|s,a)[r+\gamma v(s')]$, i.e. a model. $q(s,a)$ ranks actions directly.
What are exploring starts, and why are they unrealistic?
Every episode begins from a randomly chosen state–action pair with all pairs having non-zero probability. In real interaction you usually can't choose the start state/action freely.
What does on-policy first-visit MC control converge to?
The best policy among ε-soft policies (not the true optimal deterministic policy), unless ε is decayed.
Why do the transition probabilities cancel in the importance-sampling ratio?
The trajectory probability under both policies contains the same factors $p(S_{k+1}|S_k,A_k)$; only the action-selection probabilities differ.
Give the main trade-off between ordinary and weighted importance sampling.
Ordinary: unbiased, but variance can be unbounded. Weighted: biased (→0 asymptotically) but bounded and usually much lower variance — preferred in practice.
State the coverage assumption and its consequence for $b$.
$\pi(a|s)>0\Rightarrow b(a|s)>0$. Hence $b$ must be stochastic in every state where it differs from π.
Why is off-policy MC control potentially slow?
It learns only from the portion of each episode after the last action where $b$ deviated from the greedy π (the "tail"). Early states of long episodes rarely get updates.
What does "MC does not bootstrap" buy you?
Estimates are independent across states (no reliance on other estimates); less harmed by non-Markov states; cost of estimating one state independent of the number of states. The price: must wait until the end of the episode, and high variance.
Ex 5.13 — Sketch why $\E[\rho_{t:T-1}R_{t+1}]=\E[\rho_{t:t}R_{t+1}]$.
$\rho_{t:T-1}R_{t+1}=\rho_{t:t}R_{t+1}\cdot\prod_{k=t+1}^{T-1}\frac{\pi(A_k|S_k)}{b(A_k|S_k)}$. Condition on everything up to $S_{t+1}$: each later factor, given its state, has expectation $\sum_ab(a|s)\frac{\pi(a|s)}{b(a|s)}=1$; applying the tower rule from the last factor backward, the product's conditional expectation is 1, leaving $\E[\rho_{t:t}R_{t+1}]$.
Chapter quiz — check your understanding
Scored quiz: pick an answer (or type a number) to get instant feedback and an explanation. Questions marked Exam-style give you values to interpret (sweeps, logs, returns, learning curves), the way exam problems do. Your best score is saved in this browser and shown on the home page. "Shuffle & restart" re-orders the questions.