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 . Its value is the expected return after a visit to , so the natural estimate is a sample mean of observed returns. One episode can visit several times, which gives two estimators. First-visit Monte Carlo uses only the return that follows the first visit to 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 and . The running mean is kept incrementally, , so no list of returns is stored.
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 , or 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 : by the Markov property, what happens after the first visit to 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 after episodes that visit , where 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 (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.
After four first visits to the running average is . The fifth visit is followed by a return of . What is the new average?
Show the answer
0.52
. Check: the four earlier returns summed to , and .
Action values, exploration and exploring starts
To improve a policy you must compare actions. With state values that takes a one-step lookahead, , and a model-free agent has neither nor . So Monte Carlo control estimates action values directly, by averaging the returns that followed each visit to the pair . Improvement is then a table lookup: .
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 afterwards.
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 awayEvaluation and improvement alternate after every episode instead of waiting for evaluation to finish: generalized policy iteration in its most "optimistic" form. Each averages returns collected under a whole sequence of different policies.
Why should this work? Suppose the greedy policy eventually stopped changing at some . From then on, every new return is a return of , so each converges to . But is greedy with respect to , 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.
Why does model-free Monte Carlo control estimate rather than ?
- has fewer entries than , so it needs fewer episodes
- Returns cannot be averaged for states, only for state–action pairs
- Choosing a greedy action from needs and for a lookahead, while choosing one from needs only a comparison of table entries
- estimates are unbiased and estimates are not
Show the answer
C. Choosing a greedy action from needs and for a lookahead, while choosing one from needs only a comparison of table entries
is computable from the table alone. With , 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 for every action. The ε-greedy policy is the ε-soft policy closest to greedy: it gives each non-greedy action probability and the greedy action the rest, .
On-policy Monte Carlo control evaluates the current ε-soft policy by Monte Carlo and replaces it with the ε-greedy policy for the new . Is that an improvement? Not by the usual argument, because the new policy is not greedy. But it is greedy enough.
Let be ε-soft and ε-greedy with respect to . In each state, the expected action value of is
Because is ε-soft, the weights are nonnegative and sum to 1. A maximum is at least any weighted average:
Substitute, and the terms cancel:
The policy improvement theorem now gives in every state. Equality everywhere holds only when 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 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 in a state visited times so far. The tempting global schedule in episode 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.
An ε-greedy policy has and 4 actions. With what probability does it take the greedy action?
Show the answer
C.
The random choice, made with probability , picks the greedy action a quarter of the time too: . Each other action gets .
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 generates the data and keeps exploring; a target policy , often the greedy one, is the policy being evaluated or improved. This requires coverage: every action might take must have positive probability under , .
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 than under .
Given , the probability of the rest of the trajectory under a policy is a product of action choices and transitions:
In the ratio of the two probabilities, the unknown transition probabilities cancel. What remains is the importance sampling ratio, computable without a model:
Summing over trajectories turns an expectation under into one under (this is where coverage is needed: no trajectory of may have probability 0 under ):
The two behave very differently. First-visit ordinary IS is unbiased, but a rare trajectory that likes and 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 , not . 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 per state, and for a return with weight :
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)) = 1The weight for a pair includes only the ratios of later actions, because 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.
| Situation | Monte Carlo | TD (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 assumption | Bootstraps through aliased states and passes their mixed-up values backward |
| Some estimates are badly wrong | Each estimate is independent; errors stay put | Errors 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 states | Must learn the values of the states in between too |
| Long episodes, noisy rewards | High variance: the return sums every later random step | Low variance: one random step per target |
| Never-ending tasks, or learning before the outcome | Impossible: needs complete returns | Natural: one step is enough |
Think first A robot's camera cannot tell two hallways apart. Entered through door A, the hallway always leads to ; entered through door C, a look-alike hallway always leads to . 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 , so it learns , which is right. TD(0) sees a single "hallway" state whose outcomes are half the time and half the time, learns , and bootstraps door A's value from it: . 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 ; 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 reaches at best the optimal ε-soft policy; GLIE schedules let exploration fade.
- Importance sampling corrects for a behavior policy with ratios that need no model. Ordinary IS is unbiased with possibly infinite variance; weighted IS is biased, consistent and much steadier, with an incremental update .
- 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.
An undiscounted episode visits , then , then again, then terminates, with rewards , , . What do first-visit and every-visit MC each estimate for from this episode alone?
- Both
- First-visit , every-visit
- First-visit , every-visit
- First-visit , every-visit
Show the answer
B. First-visit , every-visit
The returns are after the first visit to , after , and after the second visit to . First-visit uses only ; every-visit averages both visits, .
Monte Carlo control with a deterministic greedy policy and episodes that always start in the same state can get stuck. Why?
- The returns are biased because they are averaged
- Actions the policy never takes are never tried, so their estimates never change and a better action can stay hidden
- Monte Carlo needs a discount factor below 1
- 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 in state , 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.
The target policy is greedy and deterministic; the behavior policy picks each of 2 actions with probability . In a 3-step episode the behavior happened to choose the greedy action every time. What is the importance sampling ratio ?
Show the answer
C.
Each step contributes , so . 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.
Both and are soft, so every trajectory has a positive weight. After exactly one visit to , what does the weighted importance-sampling estimate equal?
- , the weighted return
- The observed return itself, so in expectation it estimates
- exactly
Show the answer
B. The observed return itself, so in expectation it estimates
With one return, : the weight cancels, so the estimate is the behavior policy's return and its expectation is , not . That is the bias of weighted IS. It vanishes as returns accumulate, because the weights then reshape the average toward 's distribution.
In which situation is Monte Carlo most clearly preferable to TD(0)?
- A continuing task with no episodes
- A task with long episodes and very noisy rewards at every step
- The agent's observations merge states whose futures differ, so they are not Markov
- 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
- Monte Carlo Estimation in Depth · First-visit and every-visit estimators: bias, variance and convergence.
- Off-Policy Monte Carlo & Importance Sampling · Ordinary and weighted importance sampling, and why their variance can explode.
- Monte Carlo Control & Its Convergence · Exploring starts, soft policies and a long-open convergence question.
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).