Simple Algorithm
Reinforcement Learning · Bootstrapping · 22 min

Monte Carlo Methods

Averaging complete returns: prediction, control and exploring starts.

How likely is a blackjack strategy to win? You could enumerate every way the cards might fall, given everything on the table. Or you could play half a million hands and count. Monte Carlo methods take the second route: they learn values and policies from complete episodes, need no model of the environment, and never lean on their own estimates. This lesson builds them up from prediction to control, and then to learning about one policy from data that another policy generated.

What you’ll learn

  • Implement first-visit and every-visit Monte Carlo prediction with incremental averages, and state what is known about their convergence.
  • Explain why model-free control needs action values and exploration, and implement Monte Carlo control with exploring starts and with ε-soft policies.
  • Prove that ε-greedy improvement improves any ε-soft policy, and identify the policy that on-policy Monte Carlo control can reach with a fixed ε.
  • Derive ordinary and weighted importance sampling and the incremental weighted update, and implement off-policy Monte Carlo control.
  • Decide when Monte Carlo is preferable to temporal-difference learning.

Monte Carlo prediction

Fix a policy π\pi. Its value Vπ(s)=Eπ[Gt∣St=s]V^\pi(s) = \E_\pi[G_t \mid S_t = s] is the expected return after a visit to ss, so the natural estimate is a sample mean of observed returns. One episode can visit ss several times, which gives two estimators. First-visit Monte Carlo uses only the return that follows the first visit to ss in each episode. Every-visit Monte Carlo uses the returns after all visits.

Returns are cheapest to compute backward, from the end of the episode, with Gt=Rt+1+γGt+1G_t = R_{t+1} + \gamma G_{t+1} and GT=0G_T = 0. The running mean is kept incrementally, V←V+1N(G−V)V \leftarrow V + \frac{1}{N}(G - V), so no list of returns is stored.

python
from collections import defaultdict
import gymnasium as gym

env = gym.make("Blackjack-v1")       # obs = (player sum, dealer's card, usable ace)
policy = lambda obs: 0 if obs[0] >= 20 else 1   # stick (0) on 20 or 21, else hit (1)

V, N = defaultdict(float), defaultdict(int)
for episode in range(500_000):
    obs, _ = env.reset(seed=0 if episode == 0 else None)
    states, rewards, done = [], [], False
    while not done:
        obs2, r, terminated, truncated, _ = env.step(policy(obs))
        states.append(obs); rewards.append(r)
        obs, done = obs2, terminated or truncated
    G = 0.0
    for t in reversed(range(len(states))):   # gamma = 1
        G += rewards[t]
        if states[t] not in states[:t]:      # first visit to states[t]
            N[states[t]] += 1
            V[states[t]] += (G - V[states[t]]) / N[states[t]]

First-visit evaluation of the policy that sticks only on 20 or 21 (Sutton & Barto, Example 5.1). The reward is +1+1, 00 or −1-1 at the end of the hand. No card probability appears anywhere: the deck, the dealer's hidden card and the dealer's rules live only inside the environment, which a dynamic-programming solution would need written out explicitly. In blackjack a state can never repeat within a hand, so first-visit and every-visit coincide here.

What is guaranteed. In first-visit MC, the returns from different episodes are independent and identically distributed with mean Vπ(s)V^\pi(s): by the Markov property, what happens after the first visit to ss does not depend on how the episode got there. So each average is an unbiased estimate, it converges by the law of large numbers, and its standard error falls like σ/n\sigma/\sqrt{n} after nn episodes that visit ss, where σ2\sigma^2 is the variance of the return. Every-visit MC averages correlated returns from the same episode; it is biased for finitely many episodes but still converges to Vπ(s)V^\pi(s) (Singh & Sutton, 1996).

Two structural facts set Monte Carlo apart. Each state's estimate is computed independently of every other state's estimate, so one bad estimate cannot contaminate the rest. And the cost of estimating one state does not depend on how many states there are: to evaluate only the start state, simulate episodes from it and average.

Predict before you look

After four first visits to ss the running average is V(s)=0.4V(s) = 0.4. The fifth visit is followed by a return of G=1G = 1. What is the new average?

Show the answer

0.52

V←V+1N(G−V)=0.4+15(1−0.4)=0.52V \leftarrow V + \frac{1}{N}(G - V) = 0.4 + \frac15(1 - 0.4) = 0.52. Check: the four earlier returns summed to 1.61.6, and (1.6+1)/5=0.52(1.6 + 1)/5 = 0.52.

Action values, exploration and exploring starts

To improve a policy you must compare actions. With state values that takes a one-step lookahead, max⁡a[r(s,a)+γ∑s′P(s′∣s,a)V(s′)]\max_a \big[r(s,a) + \gamma\sum_{s'}P(s' \mid s,a)V(s')\big], and a model-free agent has neither rr nor PP. So Monte Carlo control estimates action values Qπ(s,a)Q^\pi(s,a) directly, by averaging the returns that followed each visit to the pair (s,a)(s,a). Improvement is then a table lookup: π(s)←arg max⁡aQ(s,a)\pi(s) \leftarrow \argmax_a Q(s,a).

This creates an exploration problem. A deterministic policy takes one action per state, so the returns of all the other actions are never observed and their estimates never improve. One fix is exploring starts: begin each episode from a randomly chosen state–action pair, with every pair having positive probability, and follow π\pi afterwards.

text
Monte Carlo ES (first-visit, sample averages)
Initialize Q(s, a) arbitrarily and N(s, a) ← 0;  π(s) ← argmax_a Q(s, a)
loop for each episode:
    pick (S0, A0) at random, every pair with probability > 0
    generate S0, A0, R1, S1, A1, ..., R(T) taking A0 first and following π afterwards
    G ← 0
    for t = T−1, T−2, ..., 0:
        G ← γ·G + R(t+1)
        if the pair (S(t), A(t)) does not occur earlier in the episode:
            N(S(t), A(t)) ← N(S(t), A(t)) + 1
            Q(S(t), A(t)) ← Q(S(t), A(t)) + (G − Q(S(t), A(t))) / N(S(t), A(t))
            π(S(t)) ← argmax_a Q(S(t), a)          # improve right away

Evaluation and improvement alternate after every episode instead of waiting for evaluation to finish: generalized policy iteration in its most "optimistic" form. Each Q(s,a)Q(s,a) averages returns collected under a whole sequence of different policies.

Why should this work? Suppose the greedy policy eventually stopped changing at some πˉ\bar\pi. From then on, every new return is a return of πˉ\bar\pi, so each Q(s,a)Q(s,a) converges to Qπˉ(s,a)Q^{\bar\pi}(s,a). But πˉ\bar\pi is greedy with respect to QQ, hence with respect to its own action values, and by the policy improvement theorem a policy that is greedy for its own action values is optimal. So MC-ES cannot settle on a suboptimal policy.

The argument assumes that the policy settles. Whether MC-ES always converges was long listed by Sutton and Barto (2018) as "one of the most fundamental open theoretical questions in reinforcement learning". Partial answers, and counterexamples for some variants, are the subject of the Fixed Point lesson Monte Carlo Control & Its Convergence. In blackjack, where a simulator can start a hand in any situation (Sutton and Barto pick the dealer's showing card, the player's sum and whether the player holds a usable ace at random) and take a random first action, exploring starts are easy to arrange, and MC-ES finds the optimal strategy of their Example 5.3.

Check your understanding

Why does model-free Monte Carlo control estimate Q(s,a)Q(s,a) rather than V(s)V(s)?

  1. QQ has fewer entries than VV, so it needs fewer episodes
  2. Returns cannot be averaged for states, only for state–action pairs
  3. Choosing a greedy action from VV needs rr and PP for a lookahead, while choosing one from QQ needs only a comparison of table entries
  4. QQ estimates are unbiased and VV estimates are not
Show the answer

C. Choosing a greedy action from VV needs rr and PP for a lookahead, while choosing one from QQ needs only a comparison of table entries

arg max⁡aQ(s,a)\argmax_a Q(s,a) is computable from the table alone. With VV, comparing actions means predicting where each action leads and what it pays, which is exactly the model the agent lacks.

Control without exploring starts: ε-soft policies

Exploring starts are often impossible: you cannot place a real robot in an arbitrary state, or start a customer's session halfway through. The alternative is to keep exploring forever with an ε-soft policy, one with π(a∣s)≥ε/∣A∣\pi(a \mid s) \ge \varepsilon/\abs{\mathcal A} for every action. The ε-greedy policy is the ε-soft policy closest to greedy: it gives each non-greedy action probability ε/∣A∣\varepsilon/\abs{\mathcal A} and the greedy action the rest, 1−ε+ε/∣A∣1 - \varepsilon + \varepsilon/\abs{\mathcal A}.

On-policy Monte Carlo control evaluates the current ε-soft policy by Monte Carlo and replaces it with the ε-greedy policy for the new QQ. Is that an improvement? Not by the usual argument, because the new policy is not greedy. But it is greedy enough.

Derivationε-greedy improvement on an ε-soft policy
  1. ∑aπ′(a∣s) Qπ(s,a)=ε∣A∣∑aQπ(s,a)+(1−ε)max⁡aQπ(s,a)\sum_a \pi'(a \mid s)\,Q^\pi(s,a) = \frac{\varepsilon}{\abs{\mathcal A}}\sum_a Q^\pi(s,a) + (1-\varepsilon)\max_a Q^\pi(s,a)

    Let π\pi be ε-soft and π′\pi' ε-greedy with respect to QπQ^\pi. In each state, the expected action value of π′\pi' is

  2. max⁡aQπ(s,a)  ≥  ∑aπ(a∣s)−ε/∣A∣1−ε Qπ(s,a)\max_a Q^\pi(s,a) \;\ge\; \sum_a \frac{\pi(a \mid s) - \varepsilon/\abs{\mathcal A}}{1-\varepsilon}\,Q^\pi(s,a)

    Because π\pi is ε-soft, the weights wa=(π(a∣s)−ε/∣A∣)/(1−ε)w_a = \big(\pi(a \mid s) - \varepsilon/\abs{\mathcal A}\big)/(1-\varepsilon) are nonnegative and sum to 1. A maximum is at least any weighted average:

  3. ∑aπ′(a∣s) Qπ(s,a)  ≥  ε∣A∣∑aQπ(s,a)+∑a(π(a∣s)−ε∣A∣)Qπ(s,a)=Vπ(s)\sum_a \pi'(a \mid s)\,Q^\pi(s,a) \;\ge\; \frac{\varepsilon}{\abs{\mathcal A}}\sum_a Q^\pi(s,a) + \sum_a\Big(\pi(a \mid s) - \frac{\varepsilon}{\abs{\mathcal A}}\Big)Q^\pi(s,a) = V^\pi(s)

    Substitute, and the ε/∣A∣\varepsilon/\abs{\mathcal A} terms cancel:

  4. Vπ′(s)≥Vπ(s)for all sV^{\pi'}(s) \ge V^{\pi}(s)\quad\text{for all } s

    The policy improvement theorem now gives Vπ′≥VπV^{\pi'} \ge V^\pi in every state. Equality everywhere holds only when π\pi is already the best ε-soft policy: Sutton and Barto show this by moving the forced randomness into the environment, which turns "best ε-soft policy" into "optimal policy of a modified MDP".

So a fixed ε\varepsilon can at best reach the optimal ε-soft policy, which still takes random actions and can lose a lot near a cliff. To reach an optimal policy, exploration must fade, but slowly enough that every action is still tried infinitely often. Schedules with both properties are called GLIE (greedy in the limit with infinite exploration), for example ε-greedy with ε=c/N(s)\varepsilon = c/N(s) in a state visited N(s)N(s) times so far. The tempting global schedule εk=1/k\varepsilon_k = 1/k in episode kk is not GLIE in every MDP: a state that can only be reached by two exploratory moves in a row may never be visited. Why, and what GLIE does and does not guarantee, is taken up in the Fixed Point lesson.

Check your understanding

An ε-greedy policy has ε=0.2\varepsilon = 0.2 and 4 actions. With what probability does it take the greedy action?

  1. 0.800.80
  2. 0.950.95
  3. 0.850.85
  4. 0.750.75
Show the answer

C. 0.850.85

The random choice, made with probability 0.20.2, picks the greedy action a quarter of the time too: 1−0.2+0.2/4=0.851 - 0.2 + 0.2/4 = 0.85. Each other action gets 0.2/4=0.050.2/4 = 0.05.

Off-policy Monte Carlo: importance sampling

On-policy methods compromise: they learn about the policy that explores. Off-policy methods separate the two roles. A behavior policy bb generates the data and keeps exploring; a target policy π\pi, often the greedy one, is the policy being evaluated or improved. This requires coverage: every action π\pi might take must have positive probability under bb, π(a∣s)>0⇒b(a∣s)>0\pi(a \mid s) > 0 \Rightarrow b(a \mid s) > 0.

The returns in the data are samples from the wrong distribution. Importance sampling reweights each one by how much more or less likely its trajectory is under π\pi than under bb.

DerivationOnly the policies appear in the weight
  1. Pr⁡(At,St+1,At+1,…,ST∣St,π)=∏k=tT−1π(Ak∣Sk) P(Sk+1∣Sk,Ak)\Pr\big(A_t, S_{t+1}, A_{t+1}, \dots, S_T \mid S_t, \pi\big) = \prod_{k=t}^{T-1}\pi(A_k \mid S_k)\,P(S_{k+1} \mid S_k, A_k)

    Given StS_t, the probability of the rest of the trajectory under a policy is a product of action choices and transitions:

  2. ρt:T−1=∏k=tT−1π(Ak∣Sk) P(Sk+1∣Sk,Ak)b(Ak∣Sk) P(Sk+1∣Sk,Ak)=∏k=tT−1π(Ak∣Sk)b(Ak∣Sk)\rho_{t:T-1} = \prod_{k=t}^{T-1}\frac{\pi(A_k \mid S_k)\,P(S_{k+1} \mid S_k, A_k)}{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)}

    In the ratio of the two probabilities, the unknown transition probabilities cancel. What remains is the importance sampling ratio, computable without a model:

  3. Eb[ρt:T−1 Gt∣St=s]=∑τPr⁡b(τ) Pr⁡π(τ)Pr⁡b(τ) G(τ)=∑τPr⁡π(τ) G(τ)=Vπ(s)\E_b\big[\rho_{t:T-1}\,G_t \mid S_t = s\big] = \sum_\tau \Pr_b(\tau)\,\frac{\Pr_\pi(\tau)}{\Pr_b(\tau)}\,G(\tau) = \sum_\tau \Pr_\pi(\tau)\,G(\tau) = V^\pi(s)

    Summing over trajectories τ\tau turns an expectation under bb into one under π\pi (this is where coverage is needed: no trajectory of π\pi may have probability 0 under bb):

VOIS(s)=∑t∈T(s)ρt:T(t)−1 Gt∣T(s)∣VWIS(s)=∑t∈T(s)ρt:T(t)−1 Gt∑t∈T(s)ρt:T(t)−1V_{\mathrm{OIS}}(s) = \frac{\sum_{t \in \mathcal T(s)}\rho_{t:T(t)-1}\,G_t}{\abs{\mathcal T(s)}}\qquad\qquad V_{\mathrm{WIS}}(s) = \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}}
T(s)\mathcal T(s) collects the visits to ss (first visits, or all visits) across episodes, and T(t)T(t) is the end of the episode containing visit tt. Ordinary importance sampling divides by the number of returns; weighted importance sampling divides by the total weight, and is 0 when every weight is 0.

The two behave very differently. First-visit ordinary IS is unbiased, but a rare trajectory that π\pi likes and bb rarely takes gets an enormous weight, and the variance can be infinite. Weighted IS is a weighted average of observed returns, so it always lies between the smallest and the largest return. It is biased: with a single return it simply reports that return, and if every trajectory has positive weight its expectation is then Vb(s)V^b(s), not Vπ(s)V^\pi(s). The bias vanishes as data accumulate, and in practice the far lower variance usually makes weighted IS the better choice.

Weighted IS also has a constant-memory update. Keep a cumulative weight CC per state, and for a return GG with weight WW:

C←C+W,V←V+WC (G−V).C \leftarrow C + W, \qquad V \leftarrow V + \frac{W}{C}\,\big(G - V\big).
text
Off-policy Monte Carlo control (weighted IS, every-visit); the target π is greedy
Initialize Q(s, a) arbitrarily, C(s, a) ← 0;  π(s) ← argmax_a Q(s, a)
loop for each episode:
    b ← any policy with coverage, e.g. ε-greedy with respect to Q
    generate S0, A0, R1, ..., S(T−1), A(T−1), R(T) following b
    G ← 0;  W ← 1
    for 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)
        if A(t) ≠ π(S(t)): exit the loop     # π never takes A(t): earlier steps get weight 0
        W ← W / b(A(t) | S(t))              # π(A(t) | S(t)) = 1

The weight for a pair (St,At)(S_t, A_t) includes only the ratios of later actions, because QQ already conditions on the first action. Since the greedy target gives probability 1 to its own action and 0 to every other, the loop stops at the latest non-greedy action: this method learns only from the tails of episodes. When non-greedy actions are common, states early in long episodes learn very slowly (Sutton & Barto, §5.7).

When Monte Carlo beats TD

TD learning usually learns faster, and the next lesson shows why. But Monte Carlo has real advantages, and they come from the one thing it refuses to do: lean on its own estimates.

SituationMonte CarloTD (bootstrapping)
States are not Markov (aliased observations, missing memory)Still averages the returns that actually follow each observation, so no error comes from the Markov assumptionBootstraps through aliased states and passes their mixed-up values backward
Some estimates are badly wrongEach estimate is independent; errors stay putErrors propagate to every state that bootstraps from them
Only a few states matter (e.g. the start state)Simulate from them and average; cost independent of the number of statesMust learn the values of the states in between too
Long episodes, noisy rewardsHigh variance: the return sums every later random stepLow variance: one random step per target
Never-ending tasks, or learning before the outcomeImpossible: needs complete returnsNatural: one step is enough
With function approximation the contrast sharpens: gradient Monte Carlo converges to the best fit of the true values, while TD converges to a different fixed point that can be worse (Function Approximation & Deep Q-Learning).
Think first A robot's camera cannot tell two hallways apart. Entered through door A, the hallway always leads to +1+1; entered through door C, a look-alike hallway always leads to 00. Both doors are used equally often. What do Monte Carlo and TD(0) learn for the value of door A?

Monte Carlo averages the returns observed after door A: all of them are +1+1, so it learns V(A)=1V(A) = 1, which is right. TD(0) sees a single "hallway" state whose outcomes are +1+1 half the time and 00 half the time, learns V(hallway)=12V(\text{hallway}) = \tfrac12, and bootstraps door A's value from it: V(A)=12V(A) = \tfrac12. No amount of data fixes TD's answer, because the error comes from the state representation, not from noise. The Fixed Point lesson TD vs Monte Carlo: Certainty Equivalence makes this precise.

Key takeaways

  • Monte Carlo prediction averages observed returns: first-visit MC is unbiased with error falling like 1/n1/\sqrt n; every-visit MC is biased but consistent. Neither bootstraps, so each estimate is independent of the others.
  • Model-free control needs action values, and action values need exploration: exploring starts, or ε-soft policies.
  • ε-greedy improvement improves any ε-soft policy, so a fixed ε\varepsilon reaches at best the optimal ε-soft policy; GLIE schedules let exploration fade.
  • Importance sampling corrects for a behavior policy with ratios ∏π/b\prod \pi/b that need no model. Ordinary IS is unbiased with possibly infinite variance; weighted IS is biased, consistent and much steadier, with an incremental update V←V+(W/C)(G−V)V \leftarrow V + (W/C)(G - V).
  • Monte Carlo is the safer choice when states are not Markov or estimates are unreliable; TD is the better learner when the Markov property holds and data are scarce.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

An undiscounted episode visits XX, then YY, then XX again, then terminates, with rewards R1=1R_1 = 1, R2=2R_2 = 2, R3=3R_3 = 3. What do first-visit and every-visit MC each estimate for V(X)V(X) from this episode alone?

  1. Both 66
  2. First-visit 66, every-visit 4.54.5
  3. First-visit 33, every-visit 4.54.5
  4. First-visit 66, every-visit 99
Show the answer

B. First-visit 66, every-visit 4.54.5

The returns are G0=1+2+3=6G_0 = 1 + 2 + 3 = 6 after the first visit to XX, G1=5G_1 = 5 after YY, and G2=3G_2 = 3 after the second visit to XX. First-visit uses only G0=6G_0 = 6; every-visit averages both visits, (6+3)/2=4.5(6 + 3)/2 = 4.5.

Question 2

Monte Carlo control with a deterministic greedy policy and episodes that always start in the same state can get stuck. Why?

  1. The returns are biased because they are averaged
  2. Actions the policy never takes are never tried, so their estimates never change and a better action can stay hidden
  3. Monte Carlo needs a discount factor below 1
  4. The policy improvement theorem fails for deterministic policies
Show the answer

B. Actions the policy never takes are never tried, so their estimates never change and a better action can stay hidden

Returns are only observed for pairs that occur. If the greedy policy never takes action aa in state ss, Q(s,a)Q(s,a) keeps its initial value forever, and if that value is pessimistic the better action is never discovered. Exploring starts or ε-soft policies guarantee that every pair keeps being tried.

Question 3

The target policy is greedy and deterministic; the behavior policy picks each of 2 actions with probability 12\tfrac12. In a 3-step episode the behavior happened to choose the greedy action every time. What is the importance sampling ratio ρ0:2\rho_{0:2}?

  1. 18\tfrac18
  2. 11
  3. 88
  4. 00
Show the answer

C. 88

Each step contributes π(Ak∣Sk)/b(Ak∣Sk)=1/12=2\pi(A_k \mid S_k)/b(A_k \mid S_k) = 1/\tfrac12 = 2, so ρ0:2=23=8\rho_{0:2} = 2^3 = 8. Had the behavior taken a single non-greedy action, the ratio would be 0. Most episodes get weight 0 and a few get large weights, which is the source of importance sampling's variance.

Question 4

Both π\pi and bb are soft, so every trajectory has a positive weight. After exactly one visit to ss, what does the weighted importance-sampling estimate equal?

  1. ρ G\rho\,G, the weighted return
  2. The observed return GG itself, so in expectation it estimates Vb(s)V^b(s)
  3. G/ρG/\rho
  4. Vπ(s)V^\pi(s) exactly
Show the answer

B. The observed return GG itself, so in expectation it estimates Vb(s)V^b(s)

With one return, ρG/ρ=G\rho G/\rho = G: the weight cancels, so the estimate is the behavior policy's return and its expectation is Vb(s)V^b(s), not Vπ(s)V^\pi(s). That is the bias of weighted IS. It vanishes as returns accumulate, because the weights then reshape the average toward π\pi's distribution.

Question 5

In which situation is Monte Carlo most clearly preferable to TD(0)?

  1. A continuing task with no episodes
  2. A task with long episodes and very noisy rewards at every step
  3. The agent's observations merge states whose futures differ, so they are not Markov
  4. The agent must update its predictions before each episode ends
Show the answer

C. The agent's observations merge states whose futures differ, so they are not Markov

Monte Carlo averages the returns that actually follow each observation, so it makes no Markov assumption. TD bootstraps through merged states, and the resulting error does not shrink with more data.

Go deeper

Further reading

  • R. S. Sutton & A. G. Barto, Reinforcement Learning: An Introduction, ch. 5 (MIT Press, 2nd ed., 2018).
  • S. P. Singh & R. S. Sutton, "Reinforcement learning with replacing eligibility traces," Machine Learning 22, 123–158 (1996).
  • D. Precup, R. S. Sutton & S. Singh, "Eligibility traces for off-policy policy evaluation," Proceedings of the 17th International Conference on Machine Learning (ICML), 759–766 (2000).