Monte Carlo Methods: First-Visit, Every-Visit, and Monte Carlo Control
3620 words
18 min read
Visual companion
Python
Type and operator map
Python Week 1: the first filter for runtime behavior
View
Revision summary
What this note is really saying
Short form
# Monte Carlo Methods: First-Visit, Every-Visit, and Monte Carlo Control ## 🎯 Learning Objectives - Understand why Monte Carlo methods work without a model of the environment - Implement first-visit and every-visit Monte Carlo prediction - Apply Monte Carlo control for optimal policy learning - Compare on-policy an...

Monte Carlo Methods: First-Visit, Every-Visit, and Monte Carlo Control
🎯 Learning Objectives
- Understand why Monte Carlo methods work without a model of the environment
- Implement first-visit and every-visit Monte Carlo prediction
- Apply Monte Carlo control for optimal policy learning
- Compare on-policy and off-policy Monte Carlo methods
- Understand the bias-variance tradeoff in Monte Carlo estimation
📋 Prerequisites
- MDPs (Week 2): States, actions, rewards, episodes, returns
- Dynamic Programming (Week 3): Policy evaluation and improvement concepts
- Probability: Expectation, sample means, law of large numbers
1. 📖 Core Content
1.1 Intuition: Learning from Complete Episodes
Imagine you're learning to play a new board game. You try a strategy (policy), play through the entire game, and at the end you see if you won or lost. Your only feedback is: "Did this strategy lead to a win or not?"
That's Monte Carlo reinforcement learning.
Monte Carlo (MC) methods learn from complete episodes — you wait until the episode ends, observe the total return Gt, and update your value estimates based on that return.
Key idea: Value = expected return. We can estimate this expectation by averaging observed returns.
Why does this matter? Unlike DP, MC methods don't need a model of the environment:
- No transition probabilities P(s′∣s,a) needed
- No reward function needed (just observe rewards)
- Learn from real experience, not simulated experience
1.2 MC vs DP: The Fundamental Difference
| Aspect | Dynamic Programming | Monte Carlo |
|---|---|---|
| Environment model | Required | Not required |
| Updates | Bootstrapping (uses next state's value) | No bootstrapping (uses complete return) |
| Experience | Simulated from model | Real or simulated episodes |
| Bias | Zero (exact computation) | Zero (unbiased estimate) |
| Variance | Low | High (need full episode to estimate) |
| State coverage | All states each iteration | Only visited states |
1.3 MC Prediction (Policy Evaluation)
MC prediction estimates Vπ(s) from episodes generated by following π.
1.3.1 The Algorithm
textInitialize V(s) arbitrarily, Returns(s) = empty list loop for each episode: Generate episode following π: S0, A0, R1, S1, A1, R2, ..., ST G = 0 for t = T-1, T-2, ..., 0: G = γ * G + R_{t+1} if S_t is first visit (first-visit MC): Append G to Returns(S_t) V(S_t) = average(Returns(S_t))
1.3.2 First-Visit vs Every-Visit MC
First-visit MC: Only the first occurrence of each state in an episode contributes to its value estimate.
Every-visit MC: Every occurrence of each state contributes.
Both converge to Vπ(s) as the number of episodes → ∞, but:
- First-visit MC: Lower variance, easier to analyze theoretically
- Every-visit MC: Lower bias (uses more data), but introduces correlation between updates
Worked Example 1: First-Visit MC on a Simple MDP
Consider a 3-state MDP (A, B, C) with policy π. We collect episodes:
Episode 1: A → B → C → (terminal), returns: G₀ = 3, G₁ = 2, G₂ = 1 Episode 2: B → C → (terminal), returns: G₀ = 2, G₁ = 1 Episode 3: A → C → (terminal), returns: G₀ = 4, G₁ = 1
First-visit MC:
- State A: first visit at t=0 in episode 1 (G=3), first visit at t=0 in episode 3 (G=4). V(A) = (3+4)/2 = 3.5
- State B: first visit at t=1 in episode 1 (G=2), first visit at t=0 in episode 2 (G=2). V(B) = (2+2)/2 = 2.0
- State C: first visit at t=2 in episode 1 (G=1), first visit at t=1 in episode 2 (G=1), t=1 in episode 3 (G=1). V(C) = (1+1+1)/3 = 1.0 Every-visit MC:
- State A: visited at t=0 in episode 1 (G=3), t=0 in episode 3 (G=4). V(A) = 3.5 (same, each visited once)
- State B: visited at t=1 episode 1 (2), t=0 episode 2 (2). V(B) = 2.0 (same)
- State C: visited at t=2 episode 1 (1), t=1 episode 2 (1), t=1 episode 3 (1). V(C) = 1.0 (same) In this case, they give the same result because no state was visited multiple times in the same episode.
Worked Example 2: When First-Visit and Every-Visit Differ
Episode: A → B → A → B → C → (terminal), γ = 1, rewards: A→B: +1, B→A: -1, A→B: +1, B→C: +2, C→terminal: 0
Returns at each timestep (γ=1):
- t=0 (A): G = 1 + (-1) + 1 + 2 + 0 = 3
- t=1 (B): G = -1 + 1 + 2 + 0 = 2
- t=2 (A): G = 1 + 2 + 0 = 3
- t=3 (B): G = 2 + 0 = 2
- t=4 (C): G = 0 First-visit MC:
- A: first visit at t=0 (G=3). V(A) = 3
- B: first visit at t=1 (G=2). V(B) = 2
- C: first visit at t=4 (G=0). V(C) = 0 Every-visit MC:
- A: visits at t=0 (3), t=2 (3). V(A) = 3
- B: visits at t=1 (2), t=3 (2). V(B) = 2
- C: visit at t=4 (0). V(C) = 0 Still the same! Let's try a case where they differ... Actually, with γ=1 and deterministic returns, every occurrence of A in the same episode has the same return (since the rest of the episode is the same). The difference shows when returns differ: Episode: A → B → A → C → (terminal), γ=1. Rewards: A→B: +5, B→A: -3, A→C: +10.
- t=0 (A): G = 5 + (-3) + 10 = 12
- t=1 (B): G = -3 + 10 = 7
- t=2 (A): G = 10 First-visit MC: V(A) = 12 (only t=0). Every-visit MC: V(A) = (12+10)/2 = 11. Every-visit MC uses both observations, giving a different estimate. The first visit's return (12) reflects the total discounted return from the first visit onward, while the second visit's return (10) is the remainder. First-visit MC is theoretically cleaner (each state contributes at most once per episode to avoid correlation).
1.4 Incremental MC Updates
Instead of storing all returns, we can update incrementally:
where α=1/n(s) for the sample mean, or a constant α∈(0,1] for exponential recency weighting.
Worked Example 3: Incremental MC Update
Starting with V(A)=0, α=0.1.
Episode returns for A: 3, 4, 2, 5, 3
- After G=3: V(A) = 0 + 0.1(3-0) = 0.3
- After G=4: V(A) = 0.3 + 0.1(4-0.3) = 0.3 + 0.37 = 0.67
- After G=2: V(A) = 0.67 + 0.1(2-0.67) = 0.67 + 0.133 = 0.803
- After G=5: V(A) = 0.803 + 0.1(5-0.803) = 0.803 + 0.420 = 1.223
- After G=3: V(A) = 1.223 + 0.1(3-1.223) = 1.223 + 0.178 = 1.401 Sample mean: (3+4+2+5+3)/5 = 17/5 = 3.4. With α=0.1, our estimate 1.401 is far from 3.4. That's because constant α gives more weight to recent observations. For the true average, use α=1/n.
1.5 MC Control (Policy Improvement)
MC control extends MC prediction to find optimal policies.
1.5.1 MC with Exploring Starts
To improve a policy, we need to estimate qπ(s,a) for all (s,a) pairs. We use the same MC approach but average over state-action returns.
textInitialize Q(s,a) arbitrarily, π(s) arbitrarily, Returns(s,a) = empty list loop for each episode: Generate episode following π, starting from a random (s,a) pair (exploring starts) G = 0 for t = T-1, ..., 0: G = γ * G + R_{t+1} if (S_t, A_t) is first visit: 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: Every episode begins from a randomly chosen state-action pair. This ensures all (s,a) pairs are visited infinitely often.
1.5.2 On-Policy MC Control (ε-Soft Policies)
Exploring starts is often impractical (can't start at any state-action pair). Instead, we use on-policy methods with ε-soft policies:
Common choice: ε-greedy:
- With probability 1−ε: choose greedy action (argmaxaQ(s,a))
- With probability ε: choose random action
textInitialize Q(s,a) arbitrarily Initialize π as ε-greedy w.r.t. Q loop for each episode: Generate episode following π G = 0 for t = T-1, ..., 0: G = γ * G + R_{t+1} if (S_t, A_t) is first visit: Q(S_t, A_t) = average(Returns(S_t, A_t)) # Policy improvement (implicit via ε-greedy) # Next episode uses updated ε-greedy policy
1.5.3 Off-Policy MC Control (Importance Sampling)
Off-policy methods learn about a target policy π while following a behavior policy b.
Why off-policy? We can learn the optimal (deterministic) policy while behaving ε-greedily for exploration.
Importance sampling ratio:
This ratio corrects for the mismatch between behavior and target policies.
Off-policy MC prediction:
(weighted importance sampling)
1.6 Bias, Variance, and Convergence
| Method | Bias | Variance | Convergence |
|---|---|---|---|
| DP | 0 (exact) | 0 | Exact given model |
| First-visit MC | 0 | High (full episode variance) | To Vπ |
| Every-visit MC | Small bias | Slightly lower than first-visit | To Vπ |
| MC with IS | 0 | Very high (product of ratios) | To Vπ |
MC methods are unbiased but high variance:
- Each episode provides one noisy return sample
- Variance grows with episode length (product of noisy rewards)
- Importance sampling variance grows exponentially with episode length
1.7 Edge Cases & Gotchas
- Non-episodic tasks: MC only works for episodic tasks (those that terminate). For continuing tasks, use TD learning.
- Episodes must terminate: If episodes don't terminate, returns are infinite. MC breaks.
- State-space coverage: MC only estimates values for visited states. States with low probability under π are estimated poorly.
- Importance sampling degeneracy: If π and b diverge significantly, importance sampling ratios have enormous variance.
- Off-policy MC with deterministic target: If π is deterministic and b takes a different action, ρ=0 and the sample is discarded.
1.8 Why This Matters
Monte Carlo methods are the simplest RL algorithms — they directly implement the definition of value (expected return). While TD methods are generally more sample-efficient, MC methods remain important for:
- Off-policy learning: Understanding importance sampling for MC is prerequisite for off-policy TD (Q-learning)
- Monte Carlo Tree Search: MCTS uses MC rollouts for state evaluation (used in AlphaGo)
- Gradient estimation: REINFORCE uses the MC return directly for policy gradient
- Evaluation: MC provides an unbiased baseline for comparing TD methods
2. 📐 Key Formulas / Concepts
| Concept | Formula | Description |
|---|---|---|
| MC return | Gt=∑k=0T−t−1γkRt+k+1 | Total discounted reward from t |
| MC update | V(s)←V(s)+α(Gt−V(s)) | Incremental value update |
| First-visit MC | Average Gt for first visits only | Lower variance per-state estimate |
| Exploring starts | Episodes start from random (s,a) | Ensures coverage of all pairs |
| ε-greedy | $\pi(a | s) = 1-\varepsilon + \varepsilon/|A| (greedy), \varepsilon/|A|$ (others) |
| Importance ratio | $\rho_{t:T-1} = \prod \pi(A_k | S_k)/b(A_k |
3. ⚠️ Common Pitfalls
Pitfall 1: Using MC for Continuing (Non-Episodic) Tasks
Mistake: Applying MC to a continuing task where episodes don't naturally terminate.
Why: MC requires complete episodes to compute Gt. Without termination, returns are infinite (or undefined).
Correct approach: Either (a) use TD methods for continuing tasks, (b) artificially split the continuing task into episodes (e.g., fixed-length windows), or (c) use discounting + pseudo-termination.
Pitfall 2: Not Handling the First-Visit Check Correctly
Mistake: Updating V(s) at every occurrence of a state in an episode when the implementation expects first-visit MC.
Why: The resulting estimate converges to a weighted average of returns from different positions within the episode, which introduces bias.
Correct approach: For first-visit MC, maintain a set of states visited so far in the current episode and only update on the first visit. For every-visit MC, be aware you're using every-visit and understand the bias implications.
Pitfall 3: Off-Policy MC with Extremely High Variance
Mistake: Using ordinary importance sampling for off-policy MC with long episodes.
Why: The importance sampling ratio is a product of many probability ratios, each potentially > 1. The product grows exponentially with episode length and has extremely high variance.
Correct approach: Use weighted importance sampling (which is biased but has finite variance) or truncate the importance ratio. Better yet, prefer off-policy TD methods over off-policy MC.
Pitfall 4: Confusing On-Policy and Off-Policy MC
Mistake: Using an ε-greedy behavior policy but updating Q-values as if the target policy is greedy.
Why: On-policy MC learns the value of the ε-greedy policy itself, not the optimal deterministic policy. Off-policy MC uses importance sampling to learn about a different (target) policy.
Correct approach: In on-policy MC, accept that you're learning the value of the exploration-inclusive policy. In off-policy MC, correctly apply importance sampling for the target policy.
4. 📝 Practice Questions
Q1: For a 4-state chain MDP, three episodes are generated following a uniform random policy. Episode 1: s1→s2→s3→s4(terminal), rewards +1,+1,+2. Episode 2: s2→s3→s4(terminal), rewards +1,+2. Episode 3: s1→s2→s4(terminal), rewards +1,+3. Compute first-visit MC estimates for all states (γ=1).Episode 1: G(t=0,s1)=1+1+2=4, G(t=1,s2)=1+2=3, G(t=2,s3)=2, G(t=3,s4)=0 Episode 2: G(t=0,s2)=1+2=3, G(t=1,s3)=2, G(t=2,s4)=0 Episode 3: G(t=0,s1)=1+3=4, G(t=1,s2)=3, G(t=2,s4)=0First-visit MC:
- s1: visits in ep1 (4) and ep3 (4). V(s1) = (4+4)/2 = 4
- s2: visits in ep1 (3), ep2 (3), ep3 (3). V(s2) = (3+3+3)/3 = 3
- s3: visits in ep1 (2), ep2 (2). V(s3) = (2+2)/2 = 2
- s4: terminal, V(s4) = 0 Q2: Explain the difference between exploring starts and ε-greedy for MC control.
Exploring starts ensures all (s,a) pairs are visited by starting each episode from a randomly chosen state-action pair. This guarantees infinite visits to all pairs as number of episodes → ∞. It's simple but impractical — we can't control the starting state in many real environments.ε-greedy ensures all actions are taken with at least ε/|A| probability from every state. This allows exploring starts to be dropped (the policy itself handles exploration). However, the learned policy is ε-soft (never fully greedy), so we learn a near-optimal policy, not the truly optimal one.In practice, ε-greedy is preferred because we can anneal ε → 0 over time, converging to the optimal deterministic policy. Q3: Derive the importance sampling ratio for a trajectory of length T and show how it's used in off-policy MC.For a trajectory S0,A0,R1,S1,A1,...,ST:Under behavior policy b: Pb(τ)=∏t=0T−1b(At∣St)P(St+1∣St,At)Under target policy π: Pπ(τ)=∏t=0T−1π(At∣St)P(St+1∣St,At)The importance sampling ratio:ρ0:T−1=Pb(τ)Pπ(τ)=∏b(At∣St)P(St+1∣St,At)∏π(At∣St)P(St+1∣St,At)=∏t=0T−1b(At∣St)π(At∣St)Notice that the transition probabilities cancel — the ratio depends only on the action probabilities, not the environment dynamics.For off-policy MC prediction:V(s)=∑t∈T(s)ρt:T−1∑t∈T(s)ρt:T−1Gt(weighted importance sampling — divides by sum of importance weights for normalization) Q4: An MC agent learns to play Blackjack. After 10,000 episodes, state values seem stable but the agent still loses money. Diagnose the problem.Possible diagnoses:
Insufficient state representation: Blackjack requires knowing the sum of cards AND the dealer's visible card AND whether you have an ace. If the agent only tracks the sum, it's missing critical information. Policy is suboptimal due to low ε: If ε was annealed too quickly, the agent may have converged to a locally optimal ε-greedy policy that's still globally suboptimal. Exploration didn't cover all states: Some state combinations (e.g., sum=20 with dealer showing 6) might be rare in natural play. If exploring starts wasn't used and ε is small, these states might have poor value estimates. High variance in returns: Blackjack has high reward variance (win/loss is all-or-nothing). Even 10,000 episodes might not be enough for low-variance estimates, especially for rare states. Incorrect discount factor: If γ < 1 in Blackjack (which is actually episodic), the agent might undervalue the current hand's true win probability.Fix: Increase exploration, ensure state visits include all relevant (sum, dealer, ace) triples, use every-visit MC for more data efficiency, and increase the number of episodes. Q5: Compare the variance of first-visit MC and TD(0) for policy evaluation. Why is MC variance higher?MC variance: Gt=Rt+1+γRt+2+γ2Rt+3+... — the sum of many random variables. If each reward has variance σ2, then under the assumption of independent rewards:Var(Gt)=σ2+γ2σ2+γ4σ2+...=1−γ2σ2For γ = 0.99: Var(G) ≈ 50σ². The variance grows as the effective horizon expands.TD(0) variance: TD(0) uses Rt+1+γV(St+1), which has:Var(TD target)=Var(Rt+1)+γ2Var(Vestimate)≈σ2+(small bootstrap bias)TD's lower variance comes from only having one source of randomness at a time (the immediate reward), plus the current value estimate which has been averaged over many updates.Tradeoff: MC is unbiased but high variance. TD is biased (uses current estimate) but lower variance. This is the classic bias-variance tradeoff. Q6: In on-policy MC control with ε-greedy, why can't we set ε=0 and learn the optimal policy?If ε=0, the policy is deterministic (always greedy). The agent will only take the current best action from each state. It will never explore alternative actions that might have higher long-term value.Without exploration:
- The agent might settle on a suboptimal action because the value of the optimal action was never accurately estimated
- State-action pairs not taken never get their Q-values updated
- The agent can't discover better actions
This is the exploration-exploitation dilemma: narrowing ε too fast trades off exploration for exploitation, potentially locking in a suboptimal policy.Standard practice: start with ε=0.5 or ε=1.0, anneal to ε=0.01 or 0.05, and never fully set ε=0 (or do so only after very many episodes when you're confident the policy has converged). Q7: For off-policy MC, if the target policy is deterministic and the behavior policy takes a different action at time t, what happens to the importance sampling ratio and the corresponding return?If π(At∣St)=0 (deterministic target policy chooses action a*, but behavior policy took action a' ≠ a*):ρt:T−1=∏k=tT−1b(Ak∣Sk)π(Ak∣Sk)At step t: π(At∣St)=0 (since the target policy would never take action A_t). This makes the entire product 0.When ρ=0, the sample contributes nothing to the weighted average. The episode's return from that point forward is effectively discarded for learning about the target policy.This means off-policy MC is very sample-inefficient when the target and behavior policies differ significantly — most episodes are partially or entirely discarded. Q8: Propose a way to reduce the variance of MC returns without introducing bias.Control variates: Use a baseline to reduce variance. Instead of estimating V(s) from raw returns:V(s)←V(s)+α[(Gt−b(s))−V(s)]where b(s) is a baseline (e.g., current estimate of V(s)). Since E[b(s)] is subtracted and expected back, the estimate remains unbiased, but the variance is reduced if b(s) correlates with Gt.This is the same trick used in policy gradient methods (REINFORCE with baseline). The optimal baseline is E[Gt2]/E[Gt], but the simplest is the current value estimate itself.Disadvantage: This introduces bias if the baseline is correlated with the gradient estimate. In practice, using the current value estimate as a baseline is biased but reduces variance enough that it's nearly always beneficial. Q9: Given episodes with γ=0.9. At t=0, state A, action X, reward 5. At t=1, state B, action Y, reward -2. At t=2, state C (terminal). Compute first-visit MC return for (A,X).G0=R1+γR2+γ2R3=5+0.9(−2)+0.92(0)=5−1.8=3.2The first-visit MC return for (A,X) is 3.2.If this is the only episode where (A,X) appears, then Q(A,X) = 3.2.For incremental update with α=0.2: Q_new = Q_old + 0.2(3.2 - Q_old) If Q_old = 0: Q_new = 0.64 Q10: Explain why weighted importance sampling has lower variance than ordinary importance sampling for off-policy MC.Ordinary importance sampling:V(s)=∣T(s)∣1∑t∈T(s)ρtGtEach return is scaled by the importance ratio ρt. If the behavior and target policies are very different, individual ρt can be very large (e.g., 1000), giving that single return 1000× weight. Other returns might have near-zero ρt. The result: estimator variance is dominated by the occasional huge ρt, leading to extremely high variance.Weighted importance sampling:V(s)=∑t∈T(s)ρt∑t∈T(s)ρtGtThe denominator normalizes the weights so they sum to 1. This bounds the maximum contribution of any single sample to at most 1 (if all other weights are 0). The variance is much lower because no single sample can dominate.Tradeoff: Weighted IS is biased (estimate converges to Vπ only asymptotically, not in expectation for finite samples), but has finite variance. Ordinary IS is unbiased but has infinite variance in many practical cases.
5. 🔗 Cross-References
- Previous: Dynamic Programming (Week 3) — GPI framework that MC implements
- Next: TD Learning (Week 5) — Combining MC and DP ideas
- Related: Q-Learning & SARSA (Week 6) — Off-policy and on-policy TD control
- External: Sutton & Barto, "Reinforcement Learning" — Chapters 5-6 on MC and TD Join Discord PreviousDynamic ProgrammingNextTD Learning