Monte Carlo Methods
Prerequisite Knowledge
This lecture builds on the following concepts from earlier lectures. If any feel unfamiliar, review the linked notes before proceeding.
Previously Covered in This Subject
- RL Fundamentals and the Interaction Loop — covered in Lecture 1
- Value Functions: V(s) and Q(s,a) — covered in Lecture 2
- Multi-Armed Bandits and Epsilon-Greedy — covered in Lectures 2 and 3
- MDPs and the Markov Property — covered in Lecture 4
- Bellman Equations and Dynamic Programming — covered in Lectures 5 and 6
- Generalized Policy Iteration (GPI) — covered in Lecture 6
Monte Carlo Methods
7.1 Foundations Review: The Journey So Far
The lecture opened with a comprehensive review of everything covered in the first six lectures. A student volunteered to walk through the entire arc, providing a useful map of the conceptual terrain that leads into Monte Carlo methods.
7.1.1 RL vs Supervised vs Unsupervised Learning
Reinforcement learning differs from supervised and unsupervised learning in a fundamental way. In supervised learning, we have labeled input-output pairs \(\, — the correct answer is provided for every training example. In unsupervised learning, we do tasks like clustering or market basket analysis without labels — the algorithm discovers structure on its own. Reinforcement learning is different: an agent interacts with an environment and learns from experience by maximizing the reward it receives. The key insight is that the agent learns what to do by actually doing things and observing consequences, not by being told the right answer.
The fundamental distinction. In supervised learning, the teacher provides the correct answer. In reinforcement learning, the agent must discover what to do by trying actions and seeing what happens — there is no teacher telling it the right move.
When to use RL. Reinforcement learning is the right tool when a model of the environment is not known but an analytical solution is also not available. Whenever a solid analytical solution exists, supervised or unsupervised learning is preferred. The textbook emphasizes that RL is designed for situations where an agent learns by interacting with its environment — it requires no prior knowledge of the environment's dynamics, yet can still attain optimal behavior.
Scope: RL is not always the best choice. If you have labeled data, use supervised learning. If you need to find hidden structure, use unsupervised learning. RL is for sequential decision-making under uncertainty where learning from interaction is the only option.
7.1.2 Core Elements and Value Functions
Core elements of RL. The fundamental elements are: the agent (the learner we are training), the environment (where the agent interacts), actions (what the agent does), states (the agent's current situation or point in the environment), rewards (feedback from the environment), policies (the agent's strategy), and value functions (how good a state or state-action pair is under a given policy).
A policy is a mapping from states to probabilities of selecting each possible action. If the policy is deterministic, it maps each state to a single action. If stochastic, it maps each state to a probability distribution over actions.
Value functions. There are two types: state value functions and action value functions . The state value function estimates the expected return starting from a given state under policy :
where is the return (cumulative discounted reward) from time . The action value function goes one step further — it estimates the expected return starting from a state, taking a specific action, and then following policy afterward:
As the student described it: "state value function is from the current point and action value function is after taking action, whatever value I can generate."
Why two value functions? State values are sufficient when we have a model — we can look ahead one step and pick the best action. Action values are essential when we have no model — we need to know the value of each action directly, without simulating the environment.
7.1.3 Multi-Armed Bandits and MDPs
Multi-armed bandits. The multi-armed bandit problem introduced the exploration-exploitation tradeoff. Given some unknown population distribution (like a slot machine with multiple arms), the goal is to estimate which arm is best. Algorithms for this include:
- Greedy bandits: Always pick the arm with highest estimated value. Simple but may miss better arms.
- Epsilon-greedy: Pick the best arm most of the time, but randomly explore a fraction of the time. Balances exploitation with exploration.
- UCB (Upper Confidence Bound): Creates a confidence interval around each arm's estimated value and picks the arm with the highest upper bound. Naturally balances exploration and exploitation based on uncertainty.
The exploration-exploitation dilemma. Do you stick with the arm that seems best (exploit), or try other arms to learn more (explore)? This is a fundamental tradeoff in RL that has no perfect solution — different algorithms make different tradeoffs.
Agent-environment interface and MDPs. The transition from bandits to Markov Decision Processes introduced state into the picture. In bandits, actions are stateless — each pull is independent. In an MDP, the agent moves from state to state: at time , the agent is in state , takes action , receives reward , and transitions to state . This is the ordering.
The MDP framework is defined by:
- A set of states
- A set of actions
- A transition probability function — the probability of reaching state from state after taking action
- A reward function — the reward received for transitioning from to via action
- A discount factor — how much we value future rewards relative to immediate ones
Critical requirement for MDPs. The Markov property: the future depends only on the current state, not on how we got there. If the state doesn't capture all relevant information, the MDP framework breaks down.
7.1.4 Returns and Bellman Equations
Q: In practice, which value function is more useful — state values or action values?
A: Action values are often preferred because computing expectations over all outcomes at each step is tedious in non-deterministic environments. With state values alone, you would need to simulate every possible next state to decide which action is best. With action values, you can directly compare the expected returns of different actions.
Q: You say model — do you mean model dynamics?
A: Yes, model dynamics. We do not want those model dynamics anymore. This is the key transition: from knowledge-based methods (which need transition probabilities) to experience-based methods (which learn from experience alone).
Returns. Two types of returns were covered. Episodic return is a simple sum of all future rewards:
where is the terminal time step. Discounted return uses a discount factor to weight future rewards:
The discount factor controls how much we value distant future rewards relative to immediate ones.
Why discounting matters. There are several reasons to use discounting:
- Mathematical convenience. Without discounting (), the return might be infinite for continuing tasks. Discounting ensures the return is finite.
- Uncertainty about the future. Future rewards are less certain than immediate ones — discounting reflects this uncertainty.
- Economic reasoning. A dollar today is worth more than a dollar tomorrow (time value of money).
- Animal behavior. Animals (including humans) tend to prefer immediate rewards over delayed ones.
Q: The discount factor controls how many steps ahead we look, right?
A: Not exactly — this is a common misconception. The discount factor does not directly say "look this many steps ahead." It controls the relative weighting of future rewards versus immediate ones. A close to 0 makes the agent very short-sighted (only cares about immediate reward); a close to 1 makes it value distant rewards almost as much as immediate ones. The professor flagged this as something to revisit. Think of as a "patience" parameter — how much the agent is willing to wait for future rewards.
Bellman equations. The Bellman equation expresses the value of a state in terms of the values of successor states:
This equation says: the value of state is the expected immediate reward plus the discounted value of the next state, averaged over all possible actions (weighted by the policy) and all possible next states (weighted by transition probabilities).
The Bellman optimality equation gives the value under the optimal policy:
Here, instead of averaging over actions according to the policy, we pick the best action (the one that maximizes the expected return).
The Bellman equation is recursive. It defines the value of a state in terms of the values of successor states. This is the foundation of dynamic programming — we can solve for by iteratively applying this equation until convergence.
A critical requirement: the Bellman equation assumes the model dynamics are known. If model dynamics are not well defined, the Bellman equation cannot be applied directly. This is the key limitation that motivates Monte Carlo methods.
Dynamic programming and Generalized Policy Iteration (GPI). Dynamic programming solves the Bellman equation by iteratively computing value functions. It alternates between:
- Policy evaluation: Compute for the current policy . Start with arbitrary values and repeatedly apply the Bellman equation until the values converge.
- Policy improvement: Update the policy greedily with respect to the current values. For each state, choose the action that maximizes the expected return.
When policy improvement finds no improvement (the policy is already greedy with respect to its own values), the policy is optimal. This iteration between evaluation and improvement is the essence of Generalized Policy Iteration (GPI). Value iteration is one instance of GPI.
GPI is the big picture. Whether we use dynamic programming or Monte Carlo methods, the framework is the same: alternate between evaluating the current policy and improving it. The difference is how we do the evaluation — DP uses the model, MC uses experience.
Exam note: This review is foundational. All of these concepts — MDPs, value functions, Bellman equations, GPI — underpin the Monte Carlo methods covered in this lecture. Solid understanding of this review is essential. Expect exam questions that test whether you can connect these concepts to the new material.
7.1.5 Symbol Registry
- — state value function under policy — scalar, expected return from state
- — action value function under policy — scalar, expected return from
- — policy: probability of action in state — scalar in
- — discount factor — scalar in
- — return (cumulative discounted reward) — scalar
- — reward at time step — scalar
- — state at time step — state variable
- — action at time step — action variable
- — transition probability — scalar in
- — optimal state value function — scalar
7.2 Model-Based vs Model-Free Approaches
7.2.1 The Model-Based Paradigm and Its Limitations
Everything discussed in the previous lectures — dynamic programming, policy evaluation, policy improvement — relied on having a model of the environment. This is called a model-based approach. The model means we know the transition probabilities and rewards for every state-action pair. With this model, we can compute the optimal policy even without ever interacting with the real environment — we work entirely with the model, which is a simulation of the real world. This is sometimes called planning or offline learning: we learn the policy offline using the model, then deploy it.
Model-based = planning. When we have a model, we can plan: simulate many possible futures and pick the best action. Dynamic programming is a model-based method — it uses the model to compute values without ever touching the real environment.
The problem is that in many real-world scenarios, we do not have a model. We do not know the transition probabilities or rewards in advance. Consider these examples:
- Autonomous driving. We cannot write down the exact probability distribution of how other cars will react to our actions.
- Game playing. In complex games like Go or chess, writing down all possible transitions is infeasible.
- Robotics. The physics of a robot's interaction with the world is too complex to model exactly.
- Finance. Stock prices and market dynamics are not governed by known equations.
This motivates model-free approaches, where the agent learns directly from experience — from actually interacting with the environment (or from recorded interactions) rather than from a known model.
The key transition. We are moving from "know the rules, compute the answer" (model-based) to "interact with the world, learn from what happens" (model-free). This is a fundamental shift in how we approach RL problems.
The core distinction. Both model-based and model-free approaches are value-based methods: they learn value functions and use them to derive policies. The difference is that model-based methods require a model to compute values, while model-free methods estimate values from data alone.
Scope: Model-based methods are not always worse than model-free. If you have a good model, model-based methods can be more sample-efficient (they can plan without real interaction). The problem is that good models are often unavailable or expensive to build. The choice depends on the problem: if the model is available and accurate, use it; if not, go model-free.
Why model-free matters. For many problems — physical behavior modeling, computational biology, computer graphics, finance, game prediction, weather prediction — exact mathematical models are not available. These are not exhaustive examples; there are many domains where no precise model exists. In practice, data-driven (model-free) approaches are often preferred because they adapt as the environment changes, rather than relying on a fixed model that may become stale.
7.2.2 From Model-Based DP to Data-Driven MC Learning
The transition from model-based DP to data-driven MC learning can be illustrated using the race-car problem under two distinct operational paradigms:
| Model-Based DP View | Data-Driven MC View |
|---|---|
| Requires full transition probabilities and reward dynamics . | Model unavailable or unknown; relies entirely on observed state-action trajectories. |
| Computes expected Bellman backups analytically over all possible successor states. | Averages returns actually obtained following visits to each state across sample episodes. |
Example: Explicit probability table for transition from Cool to Warm under action. |
Example: Observes sample trajectories like Cool → Warm → Overheated or Cool → Cool → Cool. |
Why MC is useful in RL. Monte Carlo makes reinforcement learning data-driven. The agent can estimate value functions directly from actual or simulated experience even when the underlying transition model is completely unknown, difficult to write down, or computationally intractable for exact DP backups.
Exam note: Know the difference between model-based and model-free approaches and when to use each. Model-based requires ; model-free learns from experience. Both follow GPI, but differ in how they evaluate policies.
7.3 Monte Carlo Methods: The Core Idea
7.3.1 The Darts Analogy
The professor introduced Monte Carlo methods through a vivid analogy. Imagine you have an 8×8 wall with an irregularly shaped piece of art on it, and you want to estimate the area the art covers. The shape is arbitrary — computing it with formal geometry or numerical methods would be tedious. The Monte Carlo approach is simple: take darts and throw them randomly at the wall. After many throws, count how many landed inside the shape versus outside. If you threw 100 darts and 63 landed inside the shape, the estimated area is:
Worked example: Darts on a wall.
- Wall dimensions: 8 × 8 = 64 square units
- Darts thrown: 100
- Darts landing inside the art: 63
Estimated area:
If we throw 1000 darts and 627 land inside:
More samples → more accurate estimate. The true area is approximated by the fraction of hits times the total area.
This is an estimate. If you throw 1000 darts instead of 100, you get more data and a better estimate. As you keep repeating the experiment with more samples, the estimate improves.
Why does this work? Each dart is a random sample. The probability of landing inside the shape is proportional to the shape's area relative to the wall's area. By the law of large numbers, as we throw more darts, the fraction that lands inside converges to this probability. This is the essence of Monte Carlo: use random sampling to estimate quantities that are hard to compute directly.
This is the heart of Monte Carlo methods: estimation without formal math, entirely driven by data. Instead of knowing the model and computing values analytically, we collect experiences and estimate values from those experiences.
Monte Carlo in one sentence. Estimate an expected value by averaging many random samples. The more samples, the better the estimate. This is exactly what we do when we estimate by averaging returns from many episodes.
Formal connection. The darts analogy maps directly to RL:
| Darts Analogy | RL Equivalent |
| --------------- | --------------- |
| Wall with art | State space |
| Shape's area | Value of a state |
| Throwing a dart | Generating an episode |
| Dart landing inside shape | Episode visiting state |
| Fraction of darts inside | Average return after visiting |
| More darts → better estimate | More episodes → better estimate |
The textbook notes that the term "Monte Carlo" is often used broadly for any estimation method involving a significant random component. In RL, we use it specifically for methods based on averaging complete returns (as opposed to methods that learn from partial returns, which we will cover in the next chapter on temporal difference learning).
7.3.2 Experience Replaces Model
Experience replaces model. Consider the race car problem that was used in earlier lectures. In the dynamic programming solution, we needed to know every transition probability — from "cool," if we take a certain action, what is the probability of reaching "warm"? What reward do we get? With Monte Carlo methods, all of those transition probabilities are immaterial. We do not need the model at all. All we need is experience: records of what actually happened when agents interacted with the environment.
The shift from computation to estimation. Dynamic programming computes values exactly using the model. Monte Carlo estimates values by averaging samples. DP requires ; MC requires only episodes. This is why MC is model-free — it never needs to know the transition probabilities.
Sources of experience. Experience can come from three places:
- Actual experience. Real recorded data from actual interactions. For example, recorded trajectories of a defender across 1000 soccer games, or millions of recorded chess games, or driving data from cars with smart features and sensors. The textbook emphasizes that learning from actual experience is "striking because it requires no prior knowledge of the environment's dynamics, yet can still attain optimal behavior."
- Simulated experience. For problems where real interaction is expensive or dangerous — like an agent that needs to uncover land mines or explore tunnels — we simulate the environment and generate experience from the simulation. The agent learns from simulated data, then we deploy the learned policy in the real environment. The textbook notes that "although a model is required, the model need only generate sample transitions, not the complete probability distributions."
- Model-generated experience. We may have an imprecise model of the environment. Rather than using dynamic programming with that model, we use it to randomly generate a large number of experiences. The model acts as a planner — it generates an initial policy, and then the agent interacts with the actual environment to refine it.
When to use which source. Use actual experience when you have it (e.g., recorded game data). Use simulated experience when real interaction is dangerous or expensive. Use model-generated experience when you have an imprecise model — it can bootstrap learning, but the agent should still interact with the real environment to refine the policy.
Real-world: The professor highlighted autonomous driving as a case where experience data is abundant — manufacturers record sensor data from every car with smart features on the road, providing massive datasets for learning driving policies.
The episode assumption. For the Monte Carlo approach covered in this lecture, we assume that experience is collected as episodes. An episode is a complete sequence from a starting state through a series of state-action-reward transitions until a terminal state is reached:
Each episode is one complete experience. Multiple episodes give us a collection of experiences to learn from. The textbook defines MC methods as "only for episodic tasks" — all episodes must eventually terminate, no matter what actions are selected.
Why episodes? We need complete returns to estimate values. Without a terminal state, the return might be infinite (if ) or hard to compute. Episodes guarantee well-defined returns.
The professor acknowledged the question of what to do when we do not have complete episodes, and deferred it to a later module. For now, the assumption is: we have complete episodes, either generated or recorded.
Scope limitation. MC methods only work for episodic tasks. For continuing tasks (no terminal state), we need other methods — this is deferred to later lectures. The episode assumption is a real limitation, not just a mathematical convenience.
7.4 Monte Carlo Policy Evaluation (First Visit)
The first concrete algorithm is Monte Carlo policy evaluation, also called Monte Carlo prediction. The goal: given a policy , estimate the state value function for every state , using experience collected under that policy. This is the same policy evaluation we did with dynamic programming, except now we do it from data instead of a model.
The problem. Given a policy , estimate for all states . In DP, we computed this exactly using the model. In MC, we estimate it by averaging returns from episodes.
Setup. A policy is given (for example, from state A, probability of going left is some value, probability of going right is some other value). We want to estimate , , , etc. Initially, all values are set to zero. For each state, we maintain a return list — initially empty — where we will accumulate the returns computed from each episode.
7.4.1 The First-Visit MC Prediction Algorithm
The formal algorithm for First-Visit Monte Carlo Prediction estimates by accumulating returns from sampled episodes and updating running averages:
First-Visit Monte Carlo Prediction Algorithm (for estimating )
Input: a policy π to be evaluated
Initialize:
V(s) ∈ ℝ arbitrarily for all s ∈ 𝒮
Returns(s) ← empty list for all s ∈ 𝒮
Repeat for each episode:
(a) Generate one complete episode following π: S₀, A₀, R₁, S₁, A₁, R₂, ..., S_{T-1}, A_{T-1}, R_T, S_T
(b) G ← 0
(c) Scan the episode backward from t = T-1 down to 0:
G ← γG + R_{t+1}
If S_t does not appear earlier in S₀, S₁, ..., S_{t-1}:
Append G to Returns(S_t)
V(S_t) ← average(Returns(S_t))
Why scanning backward helps. Moving backward allows us to compute each return recursively using . The value estimate is updated only when the scanned occurrence is the first visit of state in the episode.
7.4.2 Worked Example: Five-State Grid Prediction
Consider a five-state linear layout with nonterminal states A, B, C, D, E. Moving between adjacent states yields an ordinary step reward of -1. State A exits to the left into a penalty terminal state with reward -10, while state D exits to the right into a goal terminal state with reward +10. We evaluate a fixed policy under undiscounted returns ().
Environment Layout & Transition Rewards ():
Observed Episodes & Backward Return Calculations:
Following the First-Visit MC algorithm, each episode is scanned backward from termination () applying . Only the first occurrence of a state in each episode appends its return to :
| Ep | Forward Trajectory | Backward Return Computation () | Appended Returns |
|---|---|---|---|
| 1 |
|
||
| 2 |
|
||
| 3 |
|
||
| 4 |
|
Sequential Evolution of Value Estimates :
As each episode finishes, state values are updated by taking the average of all accumulated returns in :
| After Ep | |||||
|---|---|---|---|---|---|
| 1 | — (unvisited) | — (unvisited) | |||
| 2 | — (unvisited) | — (unvisited) | |||
| 3 | |||||
| 4 |
Final State Value Estimates & Physical Intuition:
- State D (): Exits directly to the high-reward goal state ().
- State B (): Takes two steps to reach the goal exit: .
- State A (): Exits to the left penalty terminal state ().
- State C (): Sits in the middle. Visited in trajectories heading to the right goal () three times and once heading left to the penalty exit (), giving .
- State E (): Visited twice: once leading to left exit () and once leading to right exit (), giving .
7.4.3 Five-Episode Example with Repeated Visits
Consider an episodic task with nonterminal states A, B, C, D, E, G and terminal state T. State G gives a final transition reward of +10. Other transition rewards are shown below. We use discount factor . Because states appear multiple times in single episodes, first-visit and every-visit MC yield different estimates.
Observed Episode Trajectories:
- Episode 1:
First-visit returns: - Episode 2:
First-visit returns: - Episode 3:
First-visit returns: - Episode 4:
First-visit returns: - Episode 5:
First-visit returns:
First-Visit MC Running Updates:
| After Ep | ||||||
|---|---|---|---|---|---|---|
| 1 | 2.84 | 4.27 | 4.75 | 7.09 | 6.29 | 10.00 |
| 2 | 3.33 | 5.04 | 4.49 | 7.14 | 6.02 | 10.00 |
| 3 | 3.87 | 4.51 | 5.03 | 7.39 | 6.44 | 10.00 |
| 4 | 4.83 | 4.56 | 4.58 | 7.68 | 6.66 | 10.00 |
| 5 | 4.63 | 4.73 | 4.65 | 7.34 | 6.64 | 10.00 |
Side-by-Side Comparison: First-Visit vs Every-Visit MC:
| State | First-Visit MC Estimate | Every-Visit MC Estimate |
|---|---|---|
| A | Average of 5 returns = 4.63 | |
| B | Average of 10 returns = 5.40 | |
| C | Average of 10 returns = 5.62 | |
| D | Average of 10 returns = 7.47 | |
| E | Average of 10 returns = 7.73 | |
| G | 10.00 | Average of 5 returns = 10.00 |
Key takeaway: First-visit MC treats each episode as contributing at most one return per state. Every-visit MC gives repeated states additional weight because every single visit contributes its own return to the average.
7.4.4 Student Q&A on Policy Evaluation
Q: I understood the reward summation, but how exactly are the values 0, 5, and 3 computed as first-visit returns?
A: Start from the first occurrence of the state. For state A, the first occurrence is near the end — the only reward following it is 0, so the return is 0. For state B, the first occurrence is at the beginning — the rewards that follow are 2, 1, 2, 0, so the return is 5. For state C, the first occurrence is after the first B — the rewards that follow are 1, 2, 0, so the return is 3. You start from the first visit of that state and sum everything that follows.
Q: We are computing the value of a state irrespective of the order of actions taken. The MDP had an order — state transitions were sequential. Here the value function computation seems to go outside that idea of state transitions. Why?
A: The model is not available. You only have experience. Think of it this way: you want to know how to drive from Bangalore to Chennai. You have a driver who takes you based on his own actions — that is all you have. Multiple drivers give you multiple experiences. Each driver has his own way of navigating, taking actions at each step. You do not have the model — you do not have the transition probabilities. You only have the recorded experiences. The value function is estimated from those experiences alone.
Q: Why don't we learn the model dynamics from the experiences and then use dynamic programming instead?
A: You are taking a risky route. With enough data, you could reliably compute model dynamics. But you are committing to a behavior model with, say, 10 or 1000 episodes — you do not know if the model behavior will change. When you stick to truly data-driven approaches, as the behavior changes, new episodes will reflect that. If you go the route of computing model dynamics from data and then applying dynamic programming, every time a new experience comes in, you need to update the model dynamics and recompute the policy from scratch. That is a much more complicated sequence. Data-driven approaches have their value in practice. The key question is: am I using everything I can from my data for learning? Making the best use of available data is what matters.
Key pitfall: Why not just learn the model? The professor's answer highlights a practical concern: learning a model and then using DP requires recomputing the policy every time new data arrives. MC methods update incrementally — each new episode refines the estimates without recomputing from scratch. This is a significant advantage in non-stationary environments.
7.4.5 Symbol Registry
- — policy being evaluated — function: states action probabilities
- — state value under policy — scalar
- — return (sum of rewards from first visit) — scalar
- — discount factor — scalar in
- — reward at step — scalar
- — terminal time step — positive integer
- — list of returns for state — list of scalars
7.5 Returns: Forward and Backward Computation
Computing returns efficiently is critical for Monte Carlo methods. There are two approaches: forward (naive) and backward (efficient). The textbook strongly recommends the backward method.
7.5.1 Forward Computation
The straightforward way to compute returns is forward: for each state's first occurrence, scan forward through the episode, summing rewards. For a long episode with many states, this means recomputing overlapping sums — the return for state includes all rewards from to , and the return for state includes all rewards from to . This is redundant.
Why forward computation is inefficient. If an episode has steps and we need returns for states, forward computation takes time in the worst case. Each state's return recomputes most of the same rewards. This is wasteful.
Example of redundancy. Consider an episode with rewards: .
- Return from step 0:
- Return from step 1:
- Return from step 2:
Each return recomputes part of the previous one. The sum appears in both and .
7.5.2 Backward Computation (Efficient Method)
The textbook recommends computing returns backward, scanning from the end of the episode to the beginning. This is computationally more efficient — in a single backward scan, you compute the return for every state.
The method works as follows. Consider an episode: state S, action A, reward 4 → state Y, action B, reward 8 → state T, action A, reward 1 → terminal.
We want to compute the return for each of S, Y, and T.
Backward scan walkthrough:
Step 1: Start at the end.
- The last reward is 1 (from T, action A).
- Initialize running return .
- State T does not appear earlier in the episode, so store .
Step 2: Move one step back.
- Update: (with ).
- We have reached state Y. Y does not appear earlier, so store .
Step 3: Move one more step back.
- Update: (with ).
- We have reached state S. S does not appear earlier, so store .
Result: In one backward pass, we computed returns for all three states:
The backward update rule. At each step, multiply the running total by and add the new reward:
This single operation accumulates the discounted return in one pass. No redundant computation.
Why this works mathematically. The return from time is:
We can rewrite this recursively:
The backward scan exploits this recursion. Starting from (the last reward), we work backward using the recurrence.
Backward scan with discounting ():
Same episode: S → (A, +4) → Y → (B, +8) → T → (A, +1) → terminal.
Check: . Correct.
Exam note: The textbook algorithms all compute returns using this backward scan. Students must understand how backward computation works, as it appears in every subsequent algorithm. The update rule is the key operation.
7.5.3 Symbol Registry
- — running return (accumulated backward) — scalar
- — discount factor — scalar in
- — return from time — scalar
- — terminal time step — positive integer
7.6 First-Visit vs Every-Visit MC
7.6.1 Definitions and Comparison
There are two variants of Monte Carlo policy evaluation:
First-visit MC. For each episode, only the return following the first occurrence of a state is used. If state B appears twice in an episode, only the return from the first occurrence is added to B's return list.
Every-visit MC. For each episode, the return following every occurrence of a state is used. If state B appears twice, both returns are added.
Consider an episode where B appears at positions 1 and 3. Under first-visit, we add the return from position 1 (which includes the reward from position 3 and everything after). Under every-visit, we add returns from both position 1 and position 3. The return from position 3 is entirely contained within the return from position 1, so certain portions of the experience are heavily reused.
First-visit vs every-visit comparison:
Episode: B(+2) → C(+1) → B(+3) → A(0) → terminal. ()
First-visit MC for state B:
- First occurrence at position 0: return = 2 + 1 + 3 + 0 = 6
- Return list for B: [6]
Every-visit MC for state B:
- First occurrence at position 0: return = 2 + 1 + 3 + 0 = 6
- Second occurrence at position 2: return = 3 + 0 = 3
- Return list for B: [6, 3]
Notice: the return from position 3 is entirely contained within the return from position 0. Every-visit reuses this overlapping data.
Convergence properties. Both approaches converge to as the number of visits (or first visits) to goes to infinity. The textbook provides formal convergence guarantees:
- First-visit MC. Each return is an independent, identically distributed estimate of with finite variance. By the law of large numbers, the sequence of averages converges to the expected value. The standard deviation of the error falls as , where is the number of returns averaged.
- Every-visit MC. Less straightforward because the returns are not independent (they share overlapping subsequences). However, estimates also converge to . The convergence rate is similar but the analysis is more complex (Singh and Sutton, 1996).
Why first-visit is preferred:
- First-visit returns are independent samples — simpler convergence analysis.
- Every-visit creates higher variance due to reuse of overlapping return segments.
- First-visit has been more widely studied and is the standard in textbooks.
- Every-visit extends more naturally to function approximation and eligibility traces (covered in later chapters).
The professor noted that if asked to compute every-visit returns on an exam, students should be comfortable doing so. The computation is the same — just don't skip subsequent occurrences of the same state.
Exam note: Know the difference between first-visit and every-visit MC. Both converge, but first-visit is preferred for its simpler properties. Be able to compute both. If a state appears multiple times in an episode, first-visit uses only the first return; every-visit uses all of them.
7.6.2 Symbol Registry
- — return from episode for a given state — scalar
- — number of times state has been visited — non-negative integer
- — estimated value of state — scalar
7.7 Monte Carlo Control and GPI
We now move from the prediction (evaluation) problem to the control problem. In prediction, a policy is given and we estimate values. In control, we learn the policy itself. We start with a random policy and iteratively improve it by interacting with the environment.
Prediction vs Control. Prediction: given , estimate or . Control: find the optimal policy . Both use GPI, but control adds policy improvement to the loop.
The overall framework follows Generalized Policy Iteration (GPI):
- Start with an initial policy .
- Generate an episode using .
- Use the episode to compute (or update) — the action values for all state-action pairs.
- Use the updated action values to improve the policy (make it greedy with respect to the new Q-values).
- Use the improved policy to generate a new episode.
- Repeat.
Why action values, not state values? For control, we need to compare actions. State values tell us how good a state is, but not which action to take. Action values tell us how good each action is from each state — this is what we need to improve the policy. The textbook emphasizes: "If a model is not available, then it is particularly useful to estimate action values rather than state values."
7.7.1 Worked Example: MC Control with GPI
Consider an environment with states W, X, Y, Z, C where Y, Z, C are terminal states and W, X are non-terminal. Actions are {N, E, S, W} (north, east, south, west). Rewards: from U, exit gives +1; from W, exit gives +10; from Z, exit gives −1.
Initial policy: From W, always go E. From X, always go N. Terminal states have only exit actions.
Episode 1: W → (E, reward 0) → X → (N, reward 0) → Z → (exit, reward −1) → terminal.
With , compute action values (state-action returns):
Episode 1 — Return computation (backward):
- at Z: reward from Z→terminal = −1. So .
- at X: reward from X→Z = 0, plus . So .
- at W: reward from W→X = 0, plus . So .
Update policy: From W, E gives −1 while all other actions give 0 (by initialization). So switch W's action from E to W (breaking ties, choosing among the equally-valued 0 actions). From X, N gives −1 while others give 0. Switch X's action from N to E (tie-breaking).
Episode 2: W → (W, reward 0) → U → (exit, reward +1) → terminal.
Compute action values:
Episode 2 — Return computation (backward):
- at U: reward from U→terminal = +1. So .
- at W: reward from W→U = 0, plus . So .
Update policy: From W, the action W now has value 1 (the highest). From X, E still has value −1 and other actions have value 0, so X's policy remains E.
The convergence problem. After this update, the policy says: from W, always go W; from X, always go E. If we generate new episodes using this deterministic policy, the agent from W will always go left to U and exit with +1. It will never go right through X to reach Z (where exit gives −1) or discover other paths. The policy has converged to a local optimum, not the global optimum.
The exploration problem. A deterministic policy shuts the door for exploration. Once the policy always chooses the same action from a state, the agent can never discover whether other actions might lead to better outcomes. This is why we need stochastic policies — to maintain exploration.
Q: Is it possible to compute every-visit returns for this example?
A: Yes, you should be comfortable doing that. For every-visit, if a state appears multiple times, you would add the return after each occurrence to the return list. The computation is the same — just don't skip subsequent occurrences.
7.7.2 Symbol Registry
- — policy being improved — function: states action probabilities
- — action value function — scalar
- — state value function — scalar
- — return — scalar
- — discount factor — scalar in
- — set of actions — set
7.8 Exploration: Epsilon-Soft and Epsilon-Greedy Policies
The fundamental problem identified in the previous section is maintaining exploration. Two solutions are discussed:
Exploring starts. The idea is to ensure that every state-action pair has a non-zero probability of being selected as a starting state. If we can start from any state and take any action, a deterministic policy is fine — we will cover everything through varied starting conditions. However, this assumption is often unrealistic. You would not start a car in 4th gear with the brake pressed. In most problems, the starting state is fixed.
Why exploring starts is unrealistic. In many real problems, you cannot choose arbitrary starting states. A robot starts where it is. A game starts from the initial position. An autonomous car starts parked. The exploring starts assumption cannot be relied upon in general.
Stochastic policies (the practical solution). Instead of deterministic policies, we use stochastic policies that maintain a non-zero probability for every action from every state. This is the approach used in practice.
7.8.1 Epsilon-Soft Policies
An epsilon-soft policy is one where, from each state, every action has a non-zero probability. Formally, for all states and all actions :
More precisely, an -soft policy satisfies:
where is the number of actions available in state . This ensures every action has at least a minimum probability of being selected.
Epsilon-soft guarantees exploration. Because every action has non-zero probability, the agent will eventually try every action from every state. This is the key to learning the optimal policy — you must explore to discover which actions are best.
No action is completely ruled out. For example, a state with four actions might have probabilities (0.001, 0.0003, 0.4997, 0.499) — as long as none are exactly zero, it is epsilon-soft.
7.8.2 Epsilon-Greedy Policies
An epsilon-greedy policy is a special case of epsilon-soft. It has a parameter and works as follows:
- The greedy action (the one with the highest estimated value) gets probability
- Every non-greedy action gets probability
where is the total number of actions.
Epsilon-greedy formula. For state with greedy action :
The greedy action gets most of the probability, but every action keeps a minimum floor of .
Epsilon-greedy example.
Suppose a state has 4 actions and . The greedy action is (highest Q-value).
- Base probability for each action:
- Greedy action gets:
- Non-greedy actions each get:
Policy: , , ,
Total: . Correct.
Epsilon-soft vs epsilon-greedy. Every epsilon-greedy policy is epsilon-soft, but not every epsilon-soft policy is epsilon-greedy. Epsilon-greedy is the more structured version: it specifically boosts the greedy action while maintaining a minimum exploration floor for all others.
The relationship. -greedy -soft. Every -greedy policy is -soft, but not vice versa. Epsilon-greedy is the specific form used in the on-policy MC control algorithm.
Initialization vs update. In practice, we initialize with an epsilon-soft policy (random probabilities that are all non-zero) and update using the epsilon-greedy rule. The general GPI framework does not enforce this, but the specific algorithms are explicit: initialize as epsilon-soft, update as epsilon-greedy.
Exam note: Know the definitions of epsilon-soft and epsilon-greedy. Epsilon-soft: for all . Epsilon-greedy: greedy action gets , others get . Be able to compute epsilon-greedy probabilities given and the number of actions.
7.8.3 Symbol Registry
- — exploration parameter — scalar in
- — policy probability of action in state — scalar in
- — number of actions — positive integer
- — greedy action (highest Q-value) — action
7.9 On-Policy First-Visit MC Control (Epsilon-Soft)
This algorithm combines Monte Carlo estimation with GPI to learn an optimal policy from experience. The full name tells you exactly what it does:
- On-policy: the policy used to generate episodes is the same policy being improved (as opposed to off-policy, covered later).
- First-visit: returns are computed based on the first occurrence of each state-action pair in each episode.
- MC control: it learns a policy (not just evaluates one), using Monte Carlo (data-driven) methods.
- Epsilon-soft: the policy maintains non-zero probabilities for all actions throughout.
The complete algorithm. This is the textbook's on-policy first-visit MC control algorithm for -soft policies. It learns the optimal policy by alternating between evaluating Q-values from episodes and improving the policy with epsilon-greedy updates.
7.9.1 Algorithm: Initialization
Step 1. Initialize to be an epsilon-soft policy. For each state with actions, assign random probabilities to each action and normalize so they sum to 1. Ensure every action gets non-zero probability. This is straightforward: generate random numbers and normalize.
Step 2. Initialize all action values arbitrarily for every state-action pair (e.g., all zeros).
Step 3. For each state-action pair \(\,, initialize an empty return list .
7.9.2 Algorithm: Main Loop
The main loop runs indefinitely (repeat forever):
Step 1 — Generate an episode. Use the current policy to generate a complete episode. This involves real interaction with the environment: for each state, consult to choose an action, execute it, observe the reward and next state, and continue until termination.
Step 2 — Estimate Q-values. For each state-action pair \(\, appearing in the episode, compute the return following the first occurrence of \(\,. Append to . Update:
Step 3 — Improve the policy (epsilon-greedy update). For each state appearing in the episode, identify the greedy action — the action with the highest . Update the policy using the epsilon-greedy rule:
Then return to Step 1 and generate a new episode with the updated policy.
Textbook pseudocode (backward scan version):
Initialize:
pi(s) ← epsilon-soft policy, for all s
Q(s,a) ← arbitrary, for all s,a
Returns(s,a) ← empty list, for all s,a
Loop forever:
Generate episode following pi: S0,A0,R1,...,S_{T-1},A_{T-1},R_T
G ← 0
Loop for each step t = T-1, T-2, ..., 0:
G ← gamma * G + R_{t+1}
Unless (St, At) appears earlier in episode:
Append G to Returns(St, At)
Q(St, At) ← average(Returns(St, At))
A* ← argmax_a Q(St, a)
For all a in A(St):
pi(a|St) ← { 1 - eps + eps/|A| if a = A*
{ eps/|A| if a != A*
7.9.3 Example 1: Four-State Line World (On-Policy MC Control)
Consider a line-world environment with nonterminal decision states x, y, state w (which exits to a bad terminal state with reward -100), and state z (which exits to a good terminal state with reward +10). Ordinary moves between x and y receive reward 0. We set discount factor and exploration parameter .
Episode 1:
- Backward scan returns: , ,
- Action-value updates: , ,
- Policy updates (): and
Episode 2:
- Backward scan returns: ,
- Action-value updates: ,
- Policy update: Since , action R remains greedy at x. Policy stays .
Episode 3:
- First-visit returns: , , ,
- Policy update: , so policy at y remains greedy toward R.
Episode 4:
- First-visit returns:
- Action-value average update:
- Final greedy choices: Action R at x and action R at y.
- Final -soft policy ():
Exam interpretation tip. When exam questions present a series of sequential episodes, treat each episode as being generated after the policy update from the previous episode to demonstrate return calculation, Q-averaging, and -greedy policy revision.
7.9.4 Example 2: Five-State Grid Control Example
Consider again the five-state grid layout. State D exits with reward +10, state A exits with reward -10, and step moves receive reward -1. Actions are , , and from C either toward D or toward A. We use and .
- Episode 1: .
- Episode 2: .
- Episode 3: .
- Episode 4: .
Action-Value Summary & Policy Implication Table:
| State-Action Pair | Returns Averaged | Action-Value | Policy Implication () |
|---|---|---|---|
| 6.20, 6.20 | 6.20 | Only displayed action from B; choose E. | |
| -10.00, 6.20 | -1.90 | Only displayed action from E; choose N. | |
| 8, 8, 8 | 8.00 | Greedy action at C: . | |
| -10 | -10.00 | Nongreedy action at C: . |
7.9.5 Symbol Registry
- — -soft policy — function: states action probabilities
- — action value function — scalar
- — exploration parameter — scalar in
- — discount factor — scalar in
- — number of actions per state — positive integer
- — greedy action — action
- — list of returns for state-action pair — list of scalars
- — return — scalar
7.10 On-Policy and Off-Policy Learning
In Monte Carlo control, the policy used to generate data determines what the agent experiences. Sutton and Barto distinguish two primary learning paradigms based on whether the data-generating policy matches the policy being evaluated and improved:
On-Policy Learning: Evaluates and improves the same policy that is used to make decisions and generate experience. In on-policy control, the current -soft policy generates episodes, its returns update , and that exact policy shifts toward the -greedy policy with respect to updated .
Off-Policy Learning: Separates data generation from policy evaluation/improvement. A behaviour policy generates exploratory trajectories, while a different target policy (often purely greedy or closer to optimal) is evaluated or improved.
| Learning Type | Target Policy (Policy Being Learned) | Behaviour Policy (Data-Generating Policy) |
|---|---|---|
| On-Policy | The same exploratory policy used for action selection is evaluated and improved. | Episodes are generated by the current policy (e.g., -soft policy with built-in exploration). |
| Off-Policy | A target policy is evaluated/improved; it may be greedy or closer to optimal. | A separate behaviour policy generates episodes and must explore enough to cover target actions. |
Why off-policy is more delicate. A return observed while following behaviour policy is not automatically an unbiased estimate for target policy . Off-policy methods require mathematical correction terms, such as importance sampling, to reweight returns according to the probability mismatch between and . This provides great flexibility but can introduce high variance.
7.11 Review Questions
Below are comprehensive review questions covering conceptual, numerical, and modeling aspects of Monte Carlo methods, complete with step-by-step solutions:
1. Explain how Monte Carlo methods differ from dynamic programming methods in terms of model requirement, backup structure, and use of complete episodes.
Solution: Dynamic programming requires a full environment model ( and ), performs expected backups over all possible successor states, and operates step-by-step. Monte Carlo is model-free (requires no transition probabilities), performs sample backups along individual experienced paths, and requires complete sample episodes to compute returns.
2. Define the return for an episodic task. For rewards and , compute .
Solution: The discounted return is .
Computing for the three steps:
3. Distinguish first-visit MC and every-visit MC. Construct a short episode in which the two methods append different numbers of returns for the same state.
Solution: First-visit MC appends only the return following the first occurrence of state in an episode. Every-visit MC appends returns for every occurrence of .
Example Episode: ().
First-visit appends 1 return for : .
Every-visit appends 2 returns for : and .
4. In the five-state grid example, recompute the running estimate of after each of the four displayed episodes when .
Solution:
Ep 1: C returns 9
Ep 2: C returns 9
Ep 3: C returns -11
Ep 4: C returns 9
5. In the repeated-visit example, explain why differs under first-visit MC and every-visit MC. What does every-visit MC count that first-visit MC ignores?
Solution: First-visit MC averages 5 returns (one per episode, yielding 4.73), treating each episode equally. Every-visit MC averages 10 returns (yielding 5.40) because state B was visited multiple times in several episodes. Every-visit MC counts the shorter, suffix returns of later visits within the same episode, which first-visit MC ignores.
6. A robot can be in states Safe, Risky, and Goal. It follows a fixed policy for 100 episodes. Describe precisely how first-visit MC prediction would estimate .
Solution: For each of the 100 episodes, check if state Risky appears. If it appears, find its first visit, calculate the discounted return from that point to the episode termination, and record it in . If Risky does not appear, ignore the episode. Finally, set .
7. Why are state values alone sufficient for action selection in DP when a model is known, but not sufficient in model-free Monte Carlo control?
Solution: With a model, state values allow one-step expected lookahead: . Without a model, is unknown, so lookahead cannot be computed. Action values directly provide expected returns for each action without needing transition probabilities.
8. Define a visit to a state-action pair. Why is maintaining exploration more serious for action-value estimation than for state-value estimation?
Solution: A pair is visited at time if and . For state values under a fixed policy, passive observation eventually covers reachable states. For action values in control, if an action is never chosen in state , its return can never be sampled, rendering unestimable and preventing policy improvement from evaluating that action.
9. In the line-world example, compute for with . Compute for .
Solution:
10. Suppose and . Under an -greedy improvement step that produces an -soft policy, what probability is assigned to the greedy action and to each nongreedy action?
Solution:
Nongreedy actions: each.
Greedy action: .
11. In a state s, assume , , and . For , write the improved -soft policy over the three actions.
Solution: . The greedy action is ().
Base probability: .
12. Explain how on-policy first-visit MC control fits the generalized policy iteration idea. Identify the evaluation part and the improvement part.
Solution: GPI alternates between policy evaluation and policy improvement.
Evaluation step: Generating episodes using current -soft policy and updating via first-visit return averaging.
Improvement step: Updating to be -greedy with respect to updated .
13. A recommender system shows one of four content categories to a user during a session and observes session-level reward only at the end. Formulate this as an episodic MC control problem by identifying states, actions, rewards, episodes, and the reason an -soft policy may be useful.
Solution:
State: User profile / session context.
Action: Content category selected ().
Reward: User engagement score observed at session end.
Episode: Single user session from entry to exit.
-soft utility: Ensures all content categories continue to be sampled, discovering changing user preferences and preventing premature convergence to sub-optimal recommendations.
14. A simulator generates episodes under an exploratory policy, but the designer wants to evaluate a greedy target policy. Explain why this is an off-policy setting and why correction for the policy mismatch is needed.
Solution: It is off-policy because the data-generating behaviour policy differs from the evaluated target policy . Returns sampled under reflect 's action probabilities, making them biased estimates of 's expected return. Importance sampling correction ratios are required to produce unbiased estimates for .
15. In the grid-control example, explain why the updated policy at C favours action E even though action N is still assigned nonzero probability.
Solution: is significantly higher than , making E the greedy action. Under -greedy improvement with , the greedy action E receives probability , while non-greedy N retains a floor probability of to maintain exploration.
Exam Guidance Summary
- Monte Carlo methods — understand the core idea of estimation from data without a model. Know the area-estimation analogy (darts on a wall).
- Model-based vs model-free — know the difference, when to use each, and why model-free is preferred when models are unavailable. Model-based requires ; model-free learns from experience.
- MC policy evaluation — be able to compute state values from episodes using first-visit returns, with and without discounting. Know the formula: .
- First-visit vs every-visit — know the difference, why first-visit is preferred, and be able to compute every-visit returns. First-visit uses only the return after the first occurrence; every-visit uses returns after every occurrence.
- Backward computation — understand how to compute returns efficiently by scanning backward through an episode. The update rule is the key operation — it appears in every subsequent algorithm.
- MC control with GPI — understand the evaluate-improve cycle. Be able to trace through the algorithm with numerical examples. Action values are needed (not ) because we need to compare actions without a model.
- Epsilon-soft vs epsilon-greedy — know the definitions, the relationship (epsilon-greedy is a special case of epsilon-soft), and how the epsilon-greedy update works. Be able to compute probabilities given and .
- Maintaining exploration — understand why deterministic policies fail (converge to local optima) and how stochastic policies solve this.
- On-policy vs off-policy — know the distinction (same policy for behavior and target vs different policies). This distinction is fundamental and will appear on the exam.
- Expect numerical problems where you trace through episodes, compute returns, update Q-values, and perform epsilon-greedy policy updates.
- The professor emphasized spending time with the textbook algorithm for backward computation, as it appears in all subsequent algorithms.
Key Industry Applications
- Autonomous driving: Manufacturers record sensor data from cars with smart features, providing massive experience datasets for learning driving policies. Model-free methods can learn from this recorded experience without needing to model the complex dynamics of traffic, weather, and human behavior.
- Game playing: Recorded trajectories from thousands of soccer games or chess matches serve as experience for training RL agents (defenders, players). Monte Carlo methods can evaluate strategies by averaging outcomes from recorded games.
- Demining / hazardous exploration: Agents for uncovering land mines or exploring tunnels learn from simulated experience because real interaction is too dangerous. The agent learns a policy in simulation, then deploys it in the real environment.
- Physical behavior, computational biology, computer graphics, finance, business, weather prediction: All cited as domains where exact mathematical models are unavailable, making data-driven (model-free) approaches essential. In these fields, the environment is too complex to model precisely, but experience data is often abundant.
DRL Lecture 7 Notes · Monte Carlo Methods
Sections Breakdown
Lecture title for Monte Carlo Methods in DRL
Section covering 7.1 Foundations Review: The Journey So Far
Section covering 7.2 Model-Based vs Model-Free Approaches
Section covering 7.3 Monte Carlo Methods: The Core Idea
Section covering 7.4 Monte Carlo Policy Evaluation (First Visit)
Section covering 7.5 Returns: Forward and Backward Computation
Section covering 7.6 First-Visit vs Every-Visit MC
Section covering 7.7 Monte Carlo Control and GPI
Section covering 7.8 Exploration: Epsilon-Soft and Epsilon-Greedy Policies
Section covering 7.9 On-Policy First-Visit MC Control (Epsilon-Soft)
Section covering 7.10 On-Policy and Off-Policy Learning
Section covering 7.11 Review Questions with worked solutions
Key examinable topics for Monte Carlo methods
Real-world applications of Monte Carlo methods
Exam Revision Notes
Below is the distilled, exam-ready core. Every entry comes from the full explanation above. Use this section for rapid review; return to the main notes when a point needs more context.
Foundations Review: The Journey So Far
Must-know: Foundational review: RL learns from interaction, not labels. Value functions V_pi(s) and Q_pi(s,a) estimate expected returns. Bellman equations express value recursively in terms of successor states. GPI alternates between policy evaluation and improvement. The Bellman equation requires known model dynamics P(s'|s,a) — this limitation motivates Monte Carlo methods.
Top pitfall: The discount factor gamma does NOT control how many steps to look ahead — it controls the relative weighting of future vs immediate rewards.
Self-check: What is the difference between V_pi(s) and Q_pi(s,a)? Why do we need both?
Connects to: 7.2, 7.3, 7.4
Model-Based vs Model-Free Approaches
Must-know: Model-based methods require known P(s'|s,a) and use planning. Model-free methods learn from experience without a model. Both use GPI but differ in policy evaluation. Model-free is preferred when models are unavailable, inaccurate, or too complex to specify.
Top pitfall: Assuming model-based is always better. Even with a model, sample-based methods can be simpler and more robust.
Self-check: Give an example of a problem where model-free methods are preferred over model-based methods. Why?
Connects to: 7.1, 7.3
Monte Carlo Methods: The Core Idea
Must-know: MC methods estimate values by averaging sample returns from episodes. No model needed — only experience. The darts analogy: random sampling converges to true expected values by the law of large numbers. MC requires episodic tasks with terminal states.
Top pitfall: Assuming MC works for continuing tasks. MC requires complete episodes with terminal states to compute returns.
Self-check: Explain the darts analogy. How does it map to estimating V_pi(s)?
Connects to: 7.2, 7.4
Monte Carlo Policy Evaluation (First Visit)
Must-know: First-visit MC: for each state s, average returns following first visits across episodes. V(s) = average(Returns(s)). Returns are computed from first visit to terminal state. If state doesn't appear in an episode, it contributes nothing. Algorithm converges by law of large numbers.
Top pitfall: Confusing first-visit with every-visit. First-visit only uses the return after the FIRST occurrence of a state in each episode.
Self-check: Given episode B(+2)→C(+1)→B(+2)→A(0)→terminal, compute V(B) using first-visit MC with gamma=1.
Connects to: 7.3, 7.5, 7.6
Returns: Forward and Backward Computation
Must-know: Backward computation: start from terminal state, work backward. Update rule: R = gamma * R + R_{t+1}. Computes all returns in one pass O(T). This is the textbook standard — all MC algorithms use this method.
Top pitfall: Using forward computation in practice. It's O(nT) and redundant. Always use backward scan.
Self-check: Given episode S(+4)→Y(+8)→T(+1)→terminal with gamma=0.9, compute returns using backward scan.
Connects to: 7.4, 7.6
First-Visit vs Every-Visit MC
Must-know: First-visit MC: use return only after first occurrence of state in each episode. Every-visit MC: use returns after every occurrence. Both converge. First-visit preferred: independent samples, simpler analysis, textbook standard. Every-visit: higher variance, extends to function approximation.
Top pitfall: Confusing the two. First-visit = first occurrence only. Every-visit = all occurrences. Be able to compute both on an exam.
Self-check: Episode B(+2)→C(+1)→B(+3)→A(0)→terminal. What is V(B) under first-visit vs every-visit with gamma=1?
Connects to: 7.4, 7.7
Monte Carlo Control and GPI
Must-know: MC control uses GPI: evaluate Q-values from episodes, improve policy greedily. Action values Q(s,a) needed (not V(s)) because we need to compare actions without a model. Deterministic policies block exploration — need stochastic policies.
Top pitfall: Using state values V(s) for control without a model. Action values Q(s,a) are required to compare actions.
Self-check: Why can't we use state values V(s) for MC control? What do we need instead?
Connects to: 7.6, 7.8
Exploration: Epsilon-Soft and Epsilon-Greedy Policies
Must-know: Epsilon-soft: pi(a|s) >= epsilon/|A| for all a. Epsilon-greedy: greedy action gets 1-epsilon+epsilon/|A|, non-greedy get epsilon/|A|. Every epsilon-greedy is epsilon-soft, not vice versa. Exploring starts is unrealistic; stochastic policies are the practical solution.
Top pitfall: Confusing epsilon-soft with epsilon-greedy. Epsilon-greedy is a special case of epsilon-soft with a specific probability structure.
Self-check: A state has 3 actions and epsilon=0.3. The greedy action is A. What are the probabilities for each action under epsilon-greedy?
Connects to: 7.7, 7.9
On-Policy First-Visit MC Control (Epsilon-Soft)
Must-know: On-policy MC control: (1) initialize epsilon-soft policy, (2) generate episode, (3) compute returns backward, (4) update Q-values, (5) update policy with epsilon-greedy. Repeat forever. On-policy = same policy for behavior and target. Expect numerical tracing problems on exam.
Top pitfall: Confusing on-policy with off-policy. On-policy: behavior = target. Off-policy: behavior != target.
Self-check: Given episode S(A,+2)→X(B,+2)→Y(A,+2)→Z(exit,0)→terminal with gamma=0.9, compute Q-values using backward scan.
Connects to: 7.8, 7.5
Was this lecture useful?
BitsNotes AI Assistant
Subject Notes AssistantConfigure AI Chat
Choose how to access the chatbotSigned in as
Powered by BitsNotes — 20 messages per day. No API key needed. Want unlimited access? Use "Bring Your Own Key" mode.
Sign in to use AI Chat
Get 20 free AI messages per day to ask questions about your lecture notes. Sign in with Google or GitHub — it takes 5 seconds.
Sign In to BitsNotesSwitch to "Bring Your Own Key" tab above for unlimited access with any OpenAI-compatible provider.