Chapter 5 · Book pp. 91–117

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.

First-visit vs every-visit Exploring starts On-policy ε-soft Off-policy Ordinary vs weighted importance sampling Incremental MC
Exam focus for this chapter

Why Monte Carlo?

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 MCEvery-visit MC
Averages returns after…only the first visit to $s$ in each episodeevery visit to $s$
Samplesi.i.d. unbiased estimates of $v_\pi(s)$; error std. falls as $1/\sqrt n$Not independent (biased for finite data)
ConvergenceTo $v_\pi(s)$ by the law of large numbersAlso to $v_\pi(s)$ (quadratically)
History / useMost studied (since 1940s); used in this chapterExtends more naturally to function approximation and eligibility traces
First-visit MC prediction, for estimating V ≈ vπon-policyno modelno bootstrap
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))
Returns are computed backwards with $G\leftarrow\gamma G+R_{t+1}$ (eq. 3.9). Exercise 5.9: replace the list by a count: $N(S_t)\mathrel{+}=1$; $V(S_t)\leftarrow V(S_t)+\frac{1}{N(S_t)}[G-V(S_t)]$.

Example 5.1 — Blackjack

Try it: Figure 5.1 — MC evaluation of "stick on 20 or 21"
−1+1· rows = player sum, columns = dealer showing
Exercises 5.1 and 5.2

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

Why 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

$$\pi_0\xrightarrow{E}q_{\pi_0}\xrightarrow{I}\pi_1\xrightarrow{E}q_{\pi_1}\xrightarrow{I}\pi_2\xrightarrow{E}\cdots\xrightarrow{I}\pi_*\xrightarrow{E}q_*$$
MC policy iteration§5.3

Policy improvement is greedy w.r.t. the current action-value function — no model needed:

$$\pi(s)\doteq\argmax_a q(s,a), \qquad q_{\pi_k}(s,\pi_{k+1}(s)) = \max_a q_{\pi_k}(s,a) \ge q_{\pi_k}(s,\pi_k(s)) \ge v_{\pi_k}(s)$$
Greedy improvement satisfies the policy improvement theorem(5.1)

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:

Monte Carlo ES (Exploring Starts), for estimating π ≈ π*on-policyno modelno bootstrap
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)
Cannot converge to a sub-optimal policy (the value function would then converge to that policy's values, changing the policy). Convergence to the optimal fixed point "seems inevitable" but is not formally proved — one of the most fundamental open theoretical questions in RL. Exercise 5.4: use incremental means $Q\leftarrow Q+\frac1N(G-Q)$ instead of lists.
Try it: Figure 5.2 — Monte Carlo ES solves blackjack

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 vs off-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:

On-policy first-visit MC control (for ε-soft policies), estimates π ≈ π*on-policyno modelε-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 π:

$$q_\pi(s,\pi'(s)) = \frac{\varepsilon}{|\mathcal A(s)|}\sum_a q_\pi(s,a) + (1-\varepsilon)\max_a q_\pi(s,a) \;\ge\; \frac{\varepsilon}{|\mathcal A(s)|}\sum_aq_\pi(s,a) + (1-\varepsilon)\sum_a\frac{\pi(a\mid s)-\frac{\varepsilon}{|\mathcal A(s)|}}{1-\varepsilon}q_\pi(s,a) = v_\pi(s)$$
ε-greedy improvement over an ε-soft policy(5.2)

(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

The dilemma of all learning control methods

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-policyOff-policy
PoliciesOne: π both acts and is learnedTwo: target π, behaviour $b$
ComplexitySimpler; considered firstNeeds importance sampling and extra notation
Variance / speedLower varianceOften greater variance, slower to converge
GeneralitySpecial case ($\pi=b$)More powerful: learn from a human expert, a non-learning controller, or about many policies
What is learnedBest ε-soft policyDeterministic 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).

$$\rho_{t:T-1}\doteq\frac{\prod_{k=t}^{T-1}\pi(A_k\mid S_k)\,p(S_{k+1}\mid S_k,A_k)}{\prod_{k=t}^{T-1}b(A_k\mid S_k)\,p(S_{k+1}\mid S_k,A_k)} = \prod_{k=t}^{T-1}\frac{\pi(A_k\mid S_k)}{b(A_k\mid S_k)}$$
Importance-sampling ratio(5.3)

The unknown dynamics cancel — the ratio depends only on the two policies and the observed sequence. It corrects the expectation:

$$\E[G_t\mid S_t=s]=v_b(s)\qquad\text{but}\qquad \E[\rho_{t:T-1}G_t\mid S_t=s]=v_\pi(s)$$
Importance sampling fixes the expectation(5.4)

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$.

$$V(s)\doteq\frac{\sum_{t\in\mathcal T(s)}\rho_{t:T(t)-1}G_t}{|\mathcal T(s)|}$$
Ordinary importance sampling(5.5)
$$V(s)\doteq\frac{\sum_{t\in\mathcal T(s)}\rho_{t:T(t)-1}G_t}{\sum_{t\in\mathcal T(s)}\rho_{t:T(t)-1}}$$
Weighted importance sampling(5.6)
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)UnbiasedBiased (bias → 0 asymptotically)
VarianceCan be unbounded (ratios unbounded)Bounded: max weight on any return is 1; variance → 0 even if ratio variance is infinite (bounded returns)
In practiceEasier to extend to function approximationStrongly preferred — dramatically lower variance
Every-visit versionsBoth biased (bias → 0); often preferred in practice (no need to track first visits, easier to approximate)
Try it: Figure 5.3 — ordinary vs weighted importance sampling on one blackjack state

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:

$$\E\Big[\Big(\prod_{t=0}^{T-1}\tfrac{\pi(A_t|S_t)}{b(A_t|S_t)}G_0\Big)^2\Big] = 0.1\sum_{k=0}^\infty 0.9^k\cdot 2^k\cdot 2 = 0.2\sum_{k=0}^\infty1.8^k = \infty$$
Infinite variance of ordinary ISEx 5.5 (§5.5)

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.

Try it: Figure 5.4 — ordinary importance sampling never settles

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$):

$$V_n\doteq\frac{\sum_{k=1}^{n-1}W_kG_k}{\sum_{k=1}^{n-1}W_k},\quad n\ge2$$
Weighted average of returns(5.7)
$$V_{n+1}\doteq V_n+\frac{W_n}{C_n}\big[G_n-V_n\big],\qquad C_{n+1}\doteq C_n+W_{n+1},\quad C_0\doteq0$$
Incremental weighted update(5.8)

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.

Off-policy MC prediction (policy evaluation) for estimating Q ≈ qπoff-policyweighted ISevery-visit
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)
With π = b, W is always 1 and this is on-policy every-visit MC. W is updated after Q because $Q(S_t,A_t)$ is conditioned on $A_t$ — the ratio starts at $t+1$ (Exercise 5.6: $Q(s,a)=\frac{\sum\rho_{t+1:T(t)-1}G_t}{\sum\rho_{t+1:T(t)-1}}$).

5.7 Off-policy Monte Carlo control

Off-policy MC control, for estimating π ≈ π*off-policyweighted ISgreedy target
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$:

$$G_t = (1-\gamma)\sum_{h=t+1}^{T-1}\gamma^{h-t-1}\bar G_{t:h} + \gamma^{T-t-1}\bar G_{t:T}$$
Return as a sum of flat partial returns§5.8

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).

$$\E[\rho_{t:T-1}R_{t+k}] = \E[\rho_{t:t+k-1}R_{t+k}] \;\Rightarrow\; \tilde G_t = \rho_{t:t}R_{t+1}+\gamma\rho_{t:t+1}R_{t+2}+\gamma^2\rho_{t:t+2}R_{t+3}+\dots+\gamma^{T-t-1}\rho_{t:T-1}R_T$$
Per-decision importance sampling(5.14), (5.15)

$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)
ModelNeeds full distributions $p(s',r|s,a)$None (actual experience) or only a sample model (simulation)
UpdateExpected update, one step, all successorsSample update, whole episode, one trajectory
Bootstraps?YesNo
Focus on a subset of statesMust sweep (or async)Easy and efficient — start episodes there
Markov violationsHurt (relies on successor estimates)Less harmed (no bootstrapping)
Task typesEpisodic and continuingEpisodic only
When updates happenPer sweep / per stateEnd 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

ChoiceOptionsEffect
Step sizeSample 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 decayingLarger ε 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 coverageThe 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 variantOrdinary vs weighted; per-decision; discounting-awareWeighted: biased but low variance (preferred). Ordinary: unbiased but possibly infinite variance.
First- vs every-visitEvery-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.