Skip to main content
Deep Reinforcement Learning

Monte Carlo Methods: On-Policy Prediction and Control

[Published] Published: 2026-07-21
[Level] Level: postgraduate
[Audience] Audience: Postgraduate students in Machine Learning and Artificial Intelligence

Monte Carlo Methods: On-Policy Prediction and Control

8.1 Monte Carlo Fundamentals and Exploration

8.1.1 Model-Free Approach

Hook: What if you had to learn chess by playing games, but nobody gave you the rulebook? That is exactly the situation Monte Carlo methods handle — they learn optimal behavior from raw experience alone, with zero knowledge of how the world works underneath.

Monte Carlo (MC) methods represent a fundamental shift from model-based to model-free reinforcement learning. In model-based approaches (like the dynamic programming methods we saw in earlier lectures), we need to know the environment's dynamics — the transition probabilities (what happens if I take action in state ) and reward probabilities (what rewards I get for each outcome). MC methods eliminate this requirement entirely.

Model-free means the agent never needs to know (or learn) the transition function or the reward function . Instead, it learns directly from sample episodes — actual sequences of states, actions, and rewards produced by interacting with the environment.

The key insight: instead of needing a perfect model of the environment, we let an agent actually interact with the environment, collect real experience, and learn from that experience directly. All we need is the ability to simulate or play out episodes — actual interactions with the world.

Why this matters practically. Many real-world problems have dynamics that are too complex to write down explicitly. Consider blackjack: computing the exact probability of winning when your hand totals 14 and the dealer shows a 6 requires tracking all possible card sequences — tedious and error-prone. But simulating a thousand blackjack games is easy. MC methods exploit this asymmetry: generating sample experience is often far simpler than constructing an explicit probabilistic model.

Contrast with dynamic programming:

Aspect Dynamic Programming Monte Carlo
Requires model Yes No
Learns from Computed expectations Sample episodes
Updates Every state, every sweep Only visited states after an episode
Bootstraps Yes (uses to update ) No (uses actual returns)

The textbook (Sutton & Barto) emphasizes a third advantage: even when a model is available, MC can be more efficient when you only need values for a small subset of states. You generate episodes starting from those states and ignore the rest — DP cannot do this because it must sweep through the entire state space.

8.1.2 Trajectories and Episodes

Intuition: Think of a trajectory like a game replay — a frame-by-frame record of every move made, every reward earned, and every state visited from start to game-over. An episode is one complete game replay.

Data in MC methods comes in the form of trajectories. A trajectory is a sequence of states, actions, and rewards generated through actual interaction:

where is the terminal time step. Each element has a precise role:

- — the state at time step , drawn from state space

- — the action taken at time step , chosen by policy from action space

- — the reward received after taking action in state , a scalar signal from the environment

The complete trajectory from start to terminal state is called an episode. An episode is one full play-through of the game or one complete interaction sequence. MC methods are defined only for episodic tasks — tasks where every episode is guaranteed to terminate eventually, no matter what actions are selected. We collect many such episodes and use the entire set as the basis for learning.

Worked Example: A Single Trajectory in a Grid World

Imagine a grid with states Left, Center, and Right. The agent starts in Center, with available actions Move-Left and Move-Right.

Step () State () Action () Reward () Next State ()
Center Move-Right Right
Right Move-Right Terminal

Trajectory sequence:

The episode terminates at step . There is one complete episode here — the agent reached a terminal state.

Key properties of episodes:

1. Finite length. Every episode ends. There are no infinite trajectories. This is what makes returns (cumulative rewards) well-defined — they are finite sums.

2. Independence. Each episode starts fresh from some initial state. The outcome of one episode does not affect the starting conditions of the next (though the policy we derive from past episodes will influence future episodes).

3. No step-by-step updates. Unlike temporal-difference methods (covered later), MC methods wait until an episode is complete before updating value estimates. They are "episode-by-episode" learners, not "step-by-step" learners.

There is no perfect model that exists on paper — you must actually start from a starting state, interact with the world, play the game until completion, store the trajectory, and that constitutes an episode.

8.1.3 The Exploration Problem

Hook: Imagine being locked in a building where you only ever walk the same hallway to the exit. You would never discover that a side room holds a treasure chest. That is the exploration problem — your policy determines which states you visit, and if it is too narrow, you miss valuable states entirely.

A critical challenge with MC methods is exploration. Since we learn from actual episodes, there's no guarantee that all states are visited, or that from each state all possible actions are tried, or that all possible outcomes from each state-action pair are observed. This is not just a theoretical concern — it is the primary obstacle in designing practical MC algorithms.

The core issue is circular: to find the best action in each state, we need to try all actions and observe their returns. But if our current policy already favors one action, we never collect returns for the alternatives. Without returns for alternatives, we cannot improve the policy. The agent gets stuck.

Exploration in MC means ensuring that every state-action pair is visited infinitely often (in the limit). Without this guarantee, the value estimates for unvisited pairs remain at their initial values — arbitrary and uninformative — and the policy can never discover that those actions might be better.

Three key approaches to ensuring exploration:

1. Exploring starts — Assume that every state-action pair has a non-zero probability of being the starting point of an episode. In simulated environments (like blackjack), this is easy to arrange: just pick any starting state and action at random. In real-world environments, it is unrealistic — you cannot teleport an agent to arbitrary states.

2. Epsilon-soft policies — The policy must never completely rule out any action. Formally, for all states and actions , for some . This ensures that if we generate episodes infinitely, we will eventually visit all state-action combinations. This is the approach used in the epsilon-greedy algorithm (Section 8.3).

3. The "repeat forever" structure — MC algorithms have a characteristic loop structure: "repeat forever." This means the algorithm never formally terminates. In practice, you can stop after any number of episodes (say 20 or 300) and use the current estimates to derive a policy. The algorithm doesn't force you to wait for convergence — you extract the best policy available at any point.

Q: Why does the algorithm say "repeat forever"? Doesn't it ever converge? A: The "repeat forever" structure exists because theoretically, you need infinite episodes to guarantee visiting all state-action pairs and seeing all outcomes — a requirement from the law of large numbers. Each return is an independent, identically distributed (i.i.d.) estimate of the true value . By the law of large numbers, the average of such returns converges to as , with the standard deviation of the error falling as . In practice, you stop whenever you've exhausted your computational budget (e.g., after 20 episodes) and use the current value estimates to derive a working policy. The estimates keep improving with each episode, so at any stopping point you have the best policy learned so far.
Pitfall — Confusing "repeat forever" with "never converges." The algorithm does converge — the value estimates improve with every episode. The "repeat forever" is a theoretical guarantee, not a practical requirement. In practice, you choose a stopping criterion (number of episodes, time budget, or when estimates stabilize) and extract the policy at that point.
MC methods trade the need for a perfect environment model for the need to collect many sample episodes. The exploration problem — ensuring all state-action pairs are visited — is the central challenge, addressed by epsilon-soft policies or exploring starts.

8.2 Monte Carlo Prediction (Policy Evaluation)

8.2.1 Computing Returns from Episodes

Hook: If someone asked you "how good is this state?", the most natural answer is: "play from here many times and average your total reward." That is exactly what MC prediction does — it estimates state values by averaging actual returns from real episodes.

The prediction problem in MC is: given a fixed policy , estimate the value function or the action-value function for all states or state-action pairs. Recall from earlier lectures that is the expected return starting from state and following policy thereafter. MC methods estimate this by simply averaging the returns observed after visits to .

Monte Carlo prediction estimates by averaging the actual returns observed after visits to state under policy . As the number of visits grows, the average converges to the true expected value by the law of large numbers.

Symbol registry — Monte Carlo Returns:

- — state at time step — state in state space

- — action taken at time step — action in action space

- — reward received after taking action in state — scalar

- — discount factor — scalar in

- — return from time step — cumulative discounted reward, scalar

- — value of state under policy — expected return, scalar

- — action-value of state-action pair under policy — expected return, scalar

To estimate state values, we first need to compute returns from episodes. The return from time step is the cumulative discounted reward — the sum of every reward received from step onward, with each future reward discounted by a power of . The professor describes it as: "the sum of every reward that you actually get after that, with gamma raised to successive powers."

where is the terminal time step of the episode. Written compactly:

Why discount? The discount factor controls how much the agent cares about future rewards versus immediate ones. When , all rewards are weighted equally (undiscounted). When , rewards further in the future are worth less. The return satisfies a useful recursive relationship:

This recursion is the backbone of backward computation in MC — once you know , you can compute in one step.

Worked Example: Computing from an Episode

Consider an episode with three states and actions :

Step () State () Action () Reward () Next State ()
Terminal
Assuming (undiscounted), we compute returns working backward: - (return from the terminal step) - - - First-visit returns (using only the first occurrence of each state): - Return for : First visit is at step 0. - Return for : First visit is at step 2. - Return for : First visit is at step 3. After one episode: , , . With : The return for becomes:
After the second episode (returns: , , ): After the third episode (returns: , , ): Sense-check: As you go through episode after episode, the values keep improving. Each new episode adds one more return to the average, smoothing out the noise from any single episode. This is what policy evaluation is all about — the average of many independent returns converges to the true expected return. Convergence guarantee. For first-visit MC, each return is an independent, identically distributed (i.i.d.) estimate of with finite variance. By the law of large numbers, the average of such returns converges to as . The standard deviation of the estimation error falls as , where is the number of returns averaged. This is true regardless of the environment's dynamics — no model needed.
Pitfall — Confusing reward and return. The reward is the immediate signal from the environment at one step. The return is the total discounted reward from step onward through the end of the episode. MC methods average returns, not individual rewards.

8.2.2 Computing Q(S, A) from Episodes

The same algorithm works for estimating — instead of tracking returns per state, we track returns per state-action pair. A state-action pair is said to be visited in an episode if ever state is visited and action is taken there.

To estimate , collect all episodes, and for each first visit to , compute the return from that point onward. Average these returns across episodes.

Worked Example: Computing from an Episode

Using the same episode as before ():

Step () State () Action () Return from here ()
First-visit state-action returns: - : return = 6 - : return = 5 - : return = 3 - : return = 2 Sense-check: From , taking action leads to staying in (getting more total reward), while action moves to (fewer future rewards). So — consistent with action being slightly better from .
Q: Should we estimate or in practice? A: In practice, is the more useful quantity because it directly tells you the value of each action in each state, which is what you need for control. With alone, you would still need the model to decide which action is best. With , you can directly compare actions: pick . This is true regardless of what appears on exams.

Why Q-values sidestep the model requirement. This point deserves emphasis. In DP methods, the greedy policy is — you need the transition model. In MC, the greedy policy is simply — no model needed. This is why MC methods estimate rather than .

8.2.3 First-Visit vs Every-Visit MC

Two variants exist for how to handle multiple visits to the same state within one episode:

- First-visit MC: Only the first occurrence of a state (or state-action pair) in an episode contributes to its return estimate. If a state appears multiple times in one episode, only the first visit counts. - Every-visit MC: Every occurrence of a state in an episode contributes a return to its average. If a state appears three times in one episode, three returns are added to its running average.
Worked Example: First-visit vs every-visit Consider the episode from the previous example with states : State appears at steps 0 and 1. First-visit MC: Only the return from step 0 () contributes. After this episode, . Every-visit MC: Returns from both step 0 () and step 1 () contribute. After this episode, .

Which is better? Both converge to the true value as the number of episodes grows. First-visit MC has been most widely studied and is the focus of this course. Its key advantage: each return is truly i.i.d., so the convergence analysis is straightforward (law of large numbers). Every-visit MC is slightly biased for finite samples, but the bias vanishes asymptotically (Singh and Sutton, 1996). Every-visit MC extends more naturally to function approximation and eligibility traces (Chapters 9 and 12 of Sutton & Barto).

The algorithm for first-visit MC prediction:

1. Initialize arbitrarily for all ; initialize Returns as an empty list for each state.

2. Repeat forever:

- Generate an episode following :

- Set

- Loop for each step :

- (use the recursive return formula)

- Unless appears earlier in the episode (i.e., in ):

- Append to Returns)

- average(Returns))

Pitfall — Confusing first-visit with every-visit in hand calculations. When working numerical problems by hand, always check whether the question asks for first-visit or every-visit MC. The difference only matters when a state repeats within one episode. If no state repeats, both methods give identical results.
MC prediction estimates and by averaging actual returns from episodes. First-visit MC uses only the first occurrence per episode; every-visit uses all occurrences. In practice, is preferred because it enables model-free control.

8.3 Epsilon-Greedy Policies

8.3.1 Definition and Computation

Hook: Once you have Q-value estimates, how do you turn them into a policy that mostly exploits the best action but still occasionally explores? The epsilon-greedy policy is the standard answer: "trust your best guess most of the time, but keep a small door open for experimentation."

Once we have estimated values, we need to derive a policy from them. The epsilon-greedy policy is the standard approach. The professor describes it as: "the greedy action gets one minus epsilon, and everybody gets an equal share of epsilon."

An epsilon-greedy policy with parameter selects the greedy action (the one with the highest estimated Q-value) with probability , and every action (including the greedy one) with at least probability :

Symbol registry — Epsilon-Greedy Policy:

- — exploration parameter — scalar in

- — probability of taking action in state under policy — scalar in

- — number of available actions in state — positive integer

- — the greedy action (highest Q-value) in state — action

Why the formula works. The total probability must sum to 1 over all actions. The greedy action gets the lion's share: (the "trust" portion) plus its equal share of the exploration budget . Every other action gets only its equal share of .

Connection to epsilon-soft policies. An epsilon-soft policy is any policy where for all states and actions. The epsilon-greedy policy is a special case — it is the epsilon-soft policy closest to greedy. Among all epsilon-soft policies, epsilon-greedy puts the maximum possible probability on the best action while still satisfying the exploration constraint. This makes it the natural choice for on-policy MC control.

where is the number of available actions in state . Scope: Epsilon-greedy assumes you have Q-value estimates to be greedy with respect to. If all Q-values are initialized to the same value (e.g., zero), the greedy action is arbitrary — ties are broken randomly. This is actually fine: it means early exploration is roughly uniform, and as estimates improve, the policy naturally concentrates on the best actions.

8.3.2 Worked Example: Epsilon-Greedy Computation

Worked Example: Epsilon-greedy with Given estimated values:
State-Action Pair Value
70
30
10
40
20
30
With and actions per state: Step 1: Identify the greedy action in each state. - : (Q = 70 > 30) - : (Q = 40 > 10) - : (Q = 30 > 20) Step 2: Compute probabilities. Each action gets a baseline of . The greedy action gets the extra . For :

Effect of on exploration:

Greedy action prob Non-greedy action prob Behavior
0.1 0.95 0.05 Mostly exploits, minimal exploration
0.4 0.80 0.20 Balanced — exploits but explores regularly
1.0 0.50 0.50 Pure random — no exploitation
For : For : Sense-check: In every state, the greedy action (highest Q-value) gets probability 0.8, and the non-greedy action gets 0.2. The probabilities sum to 1.0 in each state. The greedy action is favored 4:1 over the alternative, yet every action retains a non-zero chance of being selected. Pitfall — Forgetting that the greedy action also gets . A common mistake is to give the greedy action probability and split among the other actions only. This is wrong. The correct formula gives the greedy action and every action (including the greedy one) at least . The greedy action's total probability is more than , not equal to it.
The epsilon-greedy policy balances exploitation (choosing the best-known action) with exploration (trying alternatives). The greedy action gets probability ; all others get . It is the epsilon-soft policy closest to greedy.

8.4 On-Policy Monte Carlo Control

8.4.1 The Epsilon-Greedy MC Control Algorithm

Hook: Prediction tells you how good your current policy is. Control asks the harder question: can you find the best policy? The on-policy MC control algorithm does this by cycling through three steps — play a game, learn from it, adjust your strategy — forever.

The control problem goes beyond prediction: starting from a random policy, find the optimal policy through interaction with the environment. This is the goal of Generalized Policy Iteration (GPI) introduced in the DP chapter: maintain both an approximate policy and an approximate value function, and alternate between improving each.

Purpose: The on-policy MC control algorithm finds the best epsilon-soft policy by alternating between policy evaluation (estimating from episodes) and policy improvement (making epsilon-greedy with respect to the updated ). Unlike DP methods, it needs no model of the environment.

Inputs & Outputs:

- Inputs: A way to generate episodes (an environment or simulator), a discount factor , an exploration parameter

- Outputs: An approximately optimal epsilon-soft policy and its action-value function

Initialization:

- Initialize to an arbitrary epsilon-soft policy — a policy where all actions have non-zero probability

- Initialize arbitrarily (typically 0) for all state-action pairs

- Initialize Returns list as empty for each state-action pair

The Algorithm (pseudocode):
Repeat forever (for each episode):
1. GENERATE: Use current policy π to generate a complete episode:
   S_0, A_0, R_1, S_1, A_1, R_2, ..., S_{T-1}, A_{T-1}, R_T
2. EVALUATE: For each first-visited (S_t, A_t) in the episode:
   - Compute return G_t (working backward: G ← γ * G + R_{t+1})
   - Append G_t to Returns(S_t, A_t)
   - Q(S_t, A_t) ← average(Returns(S_t, A_t))
3. IMPROVE: For each state S_t visited in the episode:
   - A* ← argmax_a Q(S_t, a)
   - For all a ∈ A(S_t):
     π(a|S_t) ← 1 - ε + ε/|A(S_t)|  if a = A*
     π(a|S_t) ← ε/|A(S_t)|            otherwise

The critical distinction: the same policy serves two roles — it generates the behavior (episodes) AND it is the policy being improved. This is what makes it "on-policy."

The policy improvement theorem guarantees progress. For any epsilon-soft policy , any epsilon-greedy policy with respect to satisfies for all states . This is proven in Sutton & Barto (Section 5.4): the epsilon-greedy policy concentrates as much probability as allowed on the best action, which yields a higher or equal expected value. Equality holds only when is already optimal among epsilon-soft policies.

Assumptions & Scope: - Exploring starts (or epsilon-soft): The algorithm requires that all state-action pairs are visited infinitely often. The epsilon-greedy policy guarantees this by giving every action at least probability . - Episodic tasks only: MC methods require episodes that terminate. Continuing tasks cannot be handled directly. - The algorithm finds the best epsilon-soft policy, not the truly optimal deterministic policy. The agent always explores with probability , so it never commits fully to the greedy policy. This is a fundamental trade-off: exploration costs some performance but ensures continued learning.

8.4.2 Worked Example: Five-State Grid World

Worked Example: Five-state grid (A, B, C, D, exit) Environment setup: - States arranged linearly: A — B — C — D — exit - Actions: East (move right), West (move left), Exit (terminate) - State D: reward for taking "exit"; State A: reward for taking "exit" - All other moves: reward - , Episode 1: Starting from state B, following the current policy (which favors East):
Step State Action Reward Next State
0 B East C
1 C East D
2 D Exit Terminal
Computing returns (working backward from the tail): First-visit state-action pairs from this episode: , , Using the recursive formula :
Update Q values (first episode, so averages equal the single return): - - - Update policy using epsilon-greedy (, ): From state C, East has Q-value 8. Assuming the other action (say, West) has Q-value 0: Sense-check: After one episode, the agent has learned that going East from C and exiting from D yields a good return. The policy now strongly favors East from C. Over many more episodes, the Q-values will converge and the policy will stabilize. Q: Why are we computing returns backward from the end of the episode? A: When computing by hand, you can start from either end and get the correct answer. But computationally, working backward from the tail of the episode allows incremental updates: the return at step uses the already-computed return at step . This avoids recomputing the entire tail for each state-action pair. The recursive relationship is:

8.4.3 Worked Example: Textbook Grid World (W, X, Y, Z)

Start from and work backward. Each step is a single multiplication and addition. Worked Example: Four-state grid (W, X, Y, Z) Environment setup: - States: W — X — Y — Z (linear arrangement) - From W: only action "exit" - From Z: only action "exit" - From X: actions "left" (to W) and "right" (to Y) - From Y: actions "left" (to X) and "right" (to Z) - Initial Q values (given arbitrarily): - , - , - , Initial policy (epsilon-greedy with dominant actions): - From X: go left (Q = 4 > 3) - From Y: go left (Q = 2 > 1) Episode 1: Start at X, follow policy (left):
Step State Action Reward Next State
0 X left 0 W
1 W exit Terminal
Computing returns (first-visit):
Update Q values: - - Revised policy: From X, left now has Q-value and right has Q-value . The greedy action from X switches to "right." This is a dramatic policy flip — the agent learned that going left from X leads to a terrible exit. Episode 2: Start at X, follow updated policy (right):
Step State Action Reward Next State
0 X right 0 Y
1 Y left 0 X
2 X left 0 W
3 W exit Terminal
Computing returns (first-visit only): > Note on first-visit rule: appears twice in this episode (steps 2 and 0). Only the first visit (step 0, where the agent first enters X and takes "left") contributes. The earlier occurrence at step 0 is the first visit; the occurrence at step 2 is a repeat visit and is skipped. Wait — let me clarify: scanning the episode from left to right, the first time appears is at step 2 (after returning from Y). At step 0, the action from X was "right", not "left". So at step 2 is the first visit, and it contributes . Updated Q values after Episode 2:
State-Action Q Value
Revised optimal actions after Episode 2: - From X: right () - From Y: left (, only updated action for Y) Sense-check: Each episode improves the value estimates. After episode 1, the agent learned that left from X is bad. After episode 2, it learned the relative values of going right vs. left from X, confirming right is better. The policy is updated greedily with respect to the latest Q-estimates after each episode. Q: For Y left, why is the reward 0 and not ? A: The reward is whatever the environment gives you at that immediate step. When you take action "left" from Y, the environment gives you reward 0 for that transition. The return then includes the discounted future return: . The reward is the immediate signal; the return is the total discounted future reward from that point. Analogy: The reward is the toll you pay at one toll booth. The return is the total cost of your entire trip from that point to your destination. The toll is 0 now, but the trip ahead costs 90 (discounted by 0.9).
Pitfall — Confusing "policy update after each episode" with "policy update after each step." In this on-policy MC algorithm, the policy is updated only at the end of each episode, after all returns have been computed. Within an episode, the agent follows the same policy throughout. This is different from TD methods (next lectures), which update after every step.
On-policy MC control alternates between generating episodes under the current epsilon-greedy policy and updating Q-values from returns. Each episode improves the value estimates, and the policy is greedified (with epsilon-exploration) after every episode. The algorithm converges to the best epsilon-soft policy.

8.5 Why "On-Policy" and Policy Update Dynamics

8.5.1 Same Policy for Behavior and Target

Hook: What does it actually mean for an algorithm to be "on-policy"? It means the agent uses the same strategy to explore the world and to define what it is trying to learn. The policy generating experience is identical to the policy being improved — there is no separation between "the explorer" and "the learner."

The term "on-policy" refers to a specific property of the algorithm: the same policy is used for both generating behavior AND as the target of learning.

In the MC control algorithm:

- Behavior role: Use policy to generate episodes — the agent acts in the world according to

- Target role: Compute value estimates for — these estimates answer "how good is it to follow ?"

- Improvement: Update the same based on those estimates — make it epsilon-greedy wrt the new Q-values

The policy that generates experience is identical to the policy being improved. This creates a tight coupling: the agent explores using its current knowledge and immediately updates that same knowledge.

On-policy = behavior policy = target policy. The agent learns about the same policy it uses to act. This simplifies the algorithm (no importance sampling needed) but creates a compromise: the agent must keep exploring (epsilon-soft), so it never learns the truly optimal deterministic policy — only the best epsilon-soft policy.

8.5.2 The Iterative Nature of Policy Updates

Q: Why do we completely flip the policy instead of making gradual updates? If the current policy says "go West with 0.8 probability" and one episode suggests East is good, why jump to "go East with 0.8" instead of incrementally shifting? A: This is a valid concern. The epsilon-greedy update does make abrupt jumps. However, several factors ensure this works: 1. Each episode is just one instance. The update is based on a single episode's return, which may not be representative. But the Q-value is an average of all returns seen so far. A single bad episode shifts the average slightly, not dramatically. 2. The environment provides the real signal. Policy is not the only factor determining outcomes. The environment's rewards are the major component. If going East consistently gives better returns than the current dominant direction, the running averages will reflect this. 3. It's iterative. You don't commit to one update forever. After the policy changes, you generate new episodes with the new policy, collect new evidence, and update again. The cycle of "behave → observe → update → behave" continues. 4. Theoretically, you'd wait for infinite episodes. Ideally, you'd wait for many episodes before updating, getting accurate value estimates. But computationally, that's impractical. In practice, you might update after every single episode. 5. Analogy: Someone who observes everything for a year and then changes behavior vs. someone who adjusts daily based on each experience. Both are valid strategies; the algorithm chooses the frequent-update approach.

The key insight: the policy update doesn't act alone. With each episode, the environment's feedback is the dominant factor. If your preferred action consistently yields lower returns than an alternative, the evidence accumulates through averaging, and the policy update naturally corrects toward the better action.

Pitfall — Worrying about one bad episode. A single episode with a poor return does not ruin the policy. The Q-value is an average of all returns for that state-action pair. One outlier shifts the average slightly. It takes a pattern of consistently bad returns to move the policy away from an action.

8.5.3 Softmax vs Epsilon-Greedy

Q: Why not use softmax over Q values instead of epsilon-greedy? A: The choice depends on the nature of the optimal policy:

The professor makes a key distinction here — between learning the environment and learning to behave optimally:

When to use epsilon-greedy: - The goal is to find one optimal deterministic policy - Optimal policies in most environments have a clear dominant action — even a slight edge (0.51 vs 0.49) means one action is optimal - Epsilon-greedy pushes toward this determinism: the greedy action gets , concentrating probability mass on the best action - You can gradually decrease over time (annealing), reducing exploration as estimates improve When to use softmax: - The environment is inherently stochastic (card games, gambling, poker) - There may be no single dominant action — the optimal behavior is a probability distribution - Learning the full distribution is the goal, not a means to determinism

Convergence direction comparison:

Property Epsilon-Greedy Softmax
Converges toward Near-deterministic policy Stochastic distribution
Greedy action probability (close to 1 for small ) Depends on Q-value differences
Exploration Uniform over non-greedy actions Proportional to Q-values
Best for Most RL problems (deterministic optimal) Inherently stochastic environments

The professor's key insight: There is a difference between learning how the environment works (model learning) and learning how to behave optimally (policy learning). For model learning, you might want a stochastic policy to explore all outcomes. For policy learning — which is what MC control does — if one action gives an edge, go there. That is the optimal behavior.

8.5.4 RL vs Supervised Learning Approach

Q: Why not use random exploration (any sample, like supervised learning)? A: Reinforcement learning is fundamentally about learning by interaction. In supervised learning, you have a fixed dataset and learn a mapping. In RL, the agent's behavior affects the data it collects. This creates a feedback loop:

The fundamental loop that distinguishes RL from supervised learning:

This feedback loop has two critical consequences:

1. Non-stationarity. The world evolves. A policy learned from historical data may become outdated. Being able to incrementally improve behavior as the world changes is a key RL capability. Supervised learning assumes the data distribution is fixed; RL does not.

2. Targeted learning. The experiences most useful for learning are those generated by the current policy. If you are trying to learn whether turning left or right at an intersection is better, random wandering through the entire city wastes samples on irrelevant parts of the state space. RL focuses exploration on the states and actions that matter for the current policy.

Pitfall — Thinking RL is just supervised learning with rewards. In supervised learning, you have labeled data and minimize prediction error. In RL, the agent chooses what data to collect (through its policy), the data distribution shifts as the policy changes, and the goal is to maximize cumulative reward, not minimize prediction error. The feedback loop is the key difference.
"On-policy" means the same policy is both the behavior generator and the learning target. Policy updates are abrupt (epsilon-greedy jumps) but self-correcting through averaging. Epsilon-greedy is preferred over softmax for finding deterministic optimal policies. RL differs from supervised learning because the agent's behavior shapes its own training data.

8.6 On-Policy vs Off-Policy: Introduction

8.6.1 Behavior Policy vs Target Policy

Hook: What if you could learn from a teacher's experience — even a flawed teacher — and end up better than them? Off-policy methods make this possible by separating who generates the experience from what policy you are trying to learn.

The defining feature of on-policy methods is that the same policy generates behavior and is the learning target. Off-policy methods decouple these two roles.

In off-policy learning, two distinct policies exist: - Behavior policy ( or ) — The policy used to generate episodes. It provides the experience from which learning happens. It must explore broadly enough to cover all actions the target policy might take (coverage assumption). - Target policy () — The policy being learned. The agent uses experience from the behavior policy to improve this target policy. It can be deterministic. On-policy is a special case of off-policy where .

Side-by-side comparison:

Property On-Policy Off-Policy
Behavior policy = target policy? Yes No
Exploration Built into the policy (epsilon-soft) Handled by the behavior policy
Learns optimal deterministic policy? No (best epsilon-soft) Yes (target can be greedy)
Complexity Simpler Needs importance sampling
Data reuse Each episode used once Can reuse data from any source

8.6.2 Why Decouple Behavior and Target?

The decoupling of behavior and target policies offers several advantages:

- Use prior knowledge. The behavior policy can be a teacher or expert whose experience provides useful learning signals. The learner doesn't have to rediscover everything from scratch.

- Learn beyond the teacher. The target policy can potentially learn better behavior than the behavior policy. A student may surpass the teacher.

- Reuse data. Historical data or expert demonstrations can serve as the behavior policy while learning a new target policy. You can learn from logged data without ever interacting with the environment yourself.

Professor's analogies for off-policy learning: - Teacher-student: A math teacher provides examples and explanations (behavior), but the student may develop deeper insights (target). The student eventually surpasses the teacher by learning from the teacher's demonstrations and then going beyond them. - Cooking recipe: A recipe is a guide (behavior policy), but you adjust to taste (target policy). You learn from the recipe, but your final dish may be different — and better suited to your preferences.
Q: Is off-policy like model distillation? A: Broadly yes, but with a key difference: the target policy is expected to surpass the behavior policy. In distillation, the student typically tries to match the teacher. In off-policy RL, the learner eventually generates its own experience and improves independently. The decoupling allows the student to go beyond the teacher.

8.6.3 Off-Policy Challenges

In off-policy learning, the distribution of experience generated by the behavior policy may differ from the distribution expected by the target policy. This creates a distribution mismatch: the data you have is not the data you want.

To correct for this mismatch, off-policy methods use importance sampling — weighting returns by the ratio of the probabilities of taking the observed actions under the two policies. This ratio transforms returns from the behavior policy's distribution to the target policy's distribution.

Why this makes off-policy harder:

1. High variance. The importance sampling ratio can be very large (when the two policies disagree) or very small, leading to high-variance estimates. In extreme cases, the variance can be infinite.

2. Coverage requirement. The behavior policy must assign non-zero probability to every action the target policy might take. If implies . This limits the choice of behavior policy.

3. Slower convergence. Due to higher variance, off-policy methods typically need more episodes to converge than on-policy methods.

Off-policy learning separates the behavior policy (generates experience) from the target policy (being learned). This enables learning from any data source and potentially finding the optimal deterministic policy, but at the cost of higher variance and the need for importance sampling.
Exam note: Off-policy Monte Carlo methods are not included in the examination syllabus. However, understanding the conceptual distinction between on-policy and off-policy — that on-policy uses the same policy for behavior and learning, while off-policy separates them — provides important context for the field and for understanding future lectures on Q-learning and SARSA.

8.7 Exam Guidance Summary

Exam note: The examination covers topics up to on-policy Monte Carlo methods. Off-policy Monte Carlo is explicitly excluded.

8.7.1 Syllabus Coverage

The exam covers four modules: RL Fundamentals (Chapter 1), Multi-Armed Bandits (Chapter 2), MDP (Chapters 3-4), and Monte Carlo (Chapter 5, on-policy only). Below is the professor's detailed guidance on what to study for each.

8.7.2 Chapter 1: RL Fundamentals

- Understand what RL is and identify whether a given scenario is RL or not

- Tic-tac-toe problem: understand value updates (how the value of each board position changes with experience)

- Distinguish RL from supervised learning for given scenarios — the key differentiator is the feedback loop: the agent's behavior affects future training data

- Discuss stationary vs non-stationary environments — stationary means the reward and transition distributions do not change over time

- Early history of RL is not on the exam but worth reading for background

8.7.3 Module 2: Multi-Armed Bandits

Exam note: UCB (Upper Confidence Bound) is highlighted as "very important for the entire course and research." Be ready to solve numerical problems using UCB.

- Model a given scenario as a MAB problem: identify arms, rewards, and verify the modeling is correct

- Action value computations: incremental updates, tracking non-stationarity

- Understand vs constant — the step-size parameter controls how much weight you give to new rewards vs old ones

- Optimistic initial values: know why it's a hack (encourages exploration early on), why it's not a general technique (fails in non-stationary settings), when it works (short, stationary problems) and when it fails

- Solve numerical problems using MAB

- UCB (Upper Confidence Bound): If given a scenario, be able to solve it using UCB. Working knowledge of UCB is valuable beyond the exam

- Gradient bandit: not currently covered, will be discussed later

- Contextual bandits: model verification, understand the difference between classic MAB, contextual bandit, and full RL. If given a scenario, tag it correctly as MAB, contextual bandit, or full RL

8.7.4 Module 3: MDP

- Model any full RL scenario as an MDP — identify all MDP elements (states, actions, transitions, rewards, discount factor)

- Goals, rewards, returns, episodes: observe these concepts carefully

- Bellman equations: Two versions — expected update and optimal update. Understand the difference between them. The expected Bellman equation averages over actions according to the policy; the optimal Bellman equation takes the max over actions.

- Write custom Bellman equations for specific scenarios (not just copy the generic form)

- Model dynamics: role in Bellman updates when outcomes and rewards are stochastic

- Policy evaluation and prediction: very important

- Value iteration: More important than policy iteration for exams. Understand both in-place and not-in-place updates.

- Key terminology note: Exam papers may use "asynchronous dynamic programming" when they actually mean "in-place update." Navigate this carefully.

Exam note: The professor warns that exam papers may use "asynchronous dynamic programming" when they mean "in-place update." If you see this term, think: "update values one state at a time using the most recent estimates, rather than sweeping through all states simultaneously."

8.7.5 Module 4: Monte Carlo

- Monte Carlo prediction: estimate and — know the worked examples (computing returns from episodes, averaging across episodes)

- Monte Carlo control: the full epsilon-greedy MC control algorithm — be able to trace through multiple episodes by hand, computing returns backward, updating Q-values, and updating the policy

- Without exploring starts: use epsilon-soft policies instead of random starting states

- Each update makes an epsilon-greedy update

8.7.6 General Exam Advice

- Focus on understanding, not sample question papers — understand why each algorithm works, not just the mechanics

- Show work in tables for numerical problems — it is easier to grade and helps you avoid arithmetic errors

- Post doubts on TEAMS — responses within 24 hours

- Show partial work when asking for help, not just the problem

- Plan study time well; don't leave everything to the last minute

- Take care of health during exam preparation

8.8 Key Industry Applications

8.8.1 Game Playing and Robotics

MC methods apply to any domain where you can simulate or play out episodes — game playing (chess, Go, Atari), robotics (trial-and-error learning), traffic signal optimization, medical treatment planning, and recommendation systems.

The key requirement is episodic interaction: the problem must be decomposable into complete episodes that start and end. This makes MC natural for:

- Game playing. Each game is an episode. AlphaGo's early training used MC tree search — simulating many complete games from the current board position to estimate the value of each move.

- Robotics. Each trial (pick up object, walk across room, balance a pole) is an episode. The robot learns from repeated attempts, improving after each one.

- Medical treatment planning. A treatment course from diagnosis to outcome is an episode. MC methods can evaluate treatment policies from historical patient data.

8.8.2 Adaptive Systems

The concept of learning from interaction (rather than from a pre-existing dataset) is fundamental to applications where the environment changes over time — stock trading, adaptive systems, personalized recommendations.

In these domains, the agent cannot rely on a fixed model of the environment. Stock market dynamics shift, user preferences evolve, and traffic patterns change. MC methods adapt naturally because they learn from the most recent episodes, automatically incorporating new patterns.

8.8.3 UCB in Industry

UCB (Upper Confidence Bound) — from the MAB module — is widely used in A/B testing, clinical trials, ad placement, and any scenario requiring exploration-exploitation trade-offs. It is one of the most practically deployed RL techniques in industry.

- A/B testing. Instead of a fixed split (50/50), UCB dynamically allocates more traffic to the better-performing variant while still exploring the alternative.

- Clinical trials. UCB-based adaptive trial designs assign more patients to treatments that appear effective, reducing the number of patients receiving inferior treatments.

- Ad placement. UCB selects which ad to show by balancing the ad with the highest known click-through rate (exploitation) against ads with uncertain performance (exploration).

8.8.4 Imitation and Transfer Learning

The off-policy concept (learning from a teacher, then surpassing them) maps to imitation learning, apprenticeship learning, and transfer learning in industry AI systems.

- Imitation learning. A human expert demonstrates a task (behavior policy). The agent learns a policy from these demonstrations and can potentially improve upon them.

- Transfer learning. Knowledge from one task (source domain) is transferred to a new task (target domain). The source task's policy serves as the behavior policy; the target task's policy is what we learn.

- Robot learning from demonstration. A robot watches a human perform a task and learns a policy that replicates and eventually refines the demonstrated behavior.

DRL Lecture 8 notes · Monte Carlo Methods: On-Policy Prediction and Control

Deep Reinforcement Learning· postgraduate· 2026-07-21

Sections Breakdown

1Monte Carlo Fundamentals and Exploration

MC methods learn from actual episodes without needing a model of the environment's dynamics. Trajectories are sequences of (state, action, reward) tuples; complete trajectories are episodes. The exploration problem — ensuring all state-action pairs are visited — is addressed by exploring starts or epsilon-soft policies.

2Monte Carlo Prediction (Policy Evaluation)

MC prediction estimates V(s) and Q(s,a) by averaging returns from episodes. The return G_t is the cumulative discounted reward from step t onward. First-visit MC uses only the first occurrence of each state per episode; every-visit MC uses all occurrences. Convergence follows from the law of large numbers with error decreasing as 1/sqrt(n).

3Epsilon-Greedy Policies

Epsilon-greedy policies balance exploitation and exploration by assigning probability 1-epsilon+epsilon/|A| to the greedy action and epsilon/|A| to all others. They are the epsilon-soft policies closest to greedy, ensuring all actions have non-zero selection probability.

4On-Policy Monte Carlo Control

The on-policy MC control algorithm uses epsilon-greedy policies to balance exploration and exploitation. It cycles: generate episode, compute returns, update Q-values, make policy epsilon-greedy wrt updated Q. The same policy is both the behavior policy and the target being improved.

5Why "On-Policy" and Policy Update Dynamics

On-policy means the same policy generates behavior and is the learning target. Epsilon-greedy updates are abrupt but self-correct through averaging. Epsilon-greedy is preferred over softmax for deterministic optimal policies. RL differs from supervised learning due to the policy-experience feedback loop.

6On-Policy vs Off-Policy: Introduction

Off-policy methods separate behavior policy (generates episodes) from target policy (being learned). This enables learning from any data source and finding optimal deterministic policies, but requires importance sampling and has higher variance. On-policy is a special case where behavior = target.

7Exam Guidance Summary

Exam covers RL fundamentals, MAB (especially UCB), MDP (Bellman equations, value iteration), and on-policy MC methods. Off-policy MC is excluded. Professor emphasizes understanding over memorization and warns about terminology traps like 'asynchronous dynamic programming' meaning 'in-place update'.

8Key Industry Applications

MC methods apply to game playing, robotics, medical treatment, and adaptive systems where episodic interaction is possible. UCB is widely deployed for A/B testing and clinical trials. Off-policy concepts map to imitation learning and transfer learning.

Postgraduate students in Machine Learning and Artificial Intelligence

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.

Monte Carlo Fundamentals and Exploration

Must-know: MC methods are model-free: they learn from sample episodes, not environment dynamics. Exploration is ensured by epsilon-soft policies or exploring starts.

Top pitfall: Confusing 'repeat forever' with 'never converges' — the estimates improve every episode; 'repeat forever' is a theoretical guarantee, not a practical requirement.

Self-check: Why do MC methods require episodic tasks rather than continuing tasks?

Connects to: 8.2, 8.3, 8.4

Monte Carlo Prediction (Policy Evaluation)

Must-know: Compute G_t using the recursive formula G_t = R_{t+1} + gamma * G_{t+1}. Average returns across episodes to estimate V(s) or Q(s,a). Q(s,a) is preferred for control because it eliminates the need for a model.

Top pitfall: Confusing reward (immediate signal) with return (total discounted future reward). MC averages returns, not rewards.

Self-check: Given an episode with rewards [1, 2, 3] and gamma=0.9, what is G_0?

Connects to: 8.1, 8.3, 8.4

Epsilon-Greedy Policies

Must-know: Compute epsilon-greedy probabilities: greedy action gets 1-epsilon+epsilon/|A|, all others get epsilon/|A|. Epsilon-greedy is the epsilon-soft policy closest to greedy.

Top pitfall: Forgetting that the greedy action also gets epsilon/|A| on top of the 1-epsilon share.

Self-check: With epsilon=0.3 and 3 actions, what is the probability of the greedy action?

Connects to: 8.2, 8.4, 8.5

On-Policy Monte Carlo Control

Must-know: The full epsilon-greedy MC control algorithm: initialize pi epsilon-soft, generate episode, compute returns backward, update Q as average, make pi epsilon-greedy wrt Q. Repeat forever.

Top pitfall: Confusing policy update after each episode (MC) with policy update after each step (TD). MC updates only at episode end.

Self-check: In the W,X,Y,Z grid example, after Episode 1, why does the policy from X switch from left to right?

Connects to: 8.2, 8.3, 8.5

Why "On-Policy" and Policy Update Dynamics

Must-know: On-policy = behavior policy = target policy. Epsilon-greedy converges toward deterministic optimal; softmax converges toward stochastic distribution. RL feedback loop (policy → experience → learning → policy) distinguishes it from supervised learning.

Top pitfall: Thinking RL is supervised learning with rewards — the feedback loop (agent's behavior shapes its own data) is the fundamental difference.

Self-check: Why is epsilon-greedy preferred over softmax for most RL control problems?

Connects to: 8.3, 8.4, 8.6

On-Policy vs Off-Policy: Introduction

Must-know: Off-policy separates behavior (mu) from target (pi). On-policy is the special case mu=pi. Off-policy can find optimal deterministic policy but needs importance sampling.

Top pitfall: Forgetting the coverage requirement: behavior policy must assign non-zero probability to every action the target policy might take.

Self-check: What is the main advantage of off-policy over on-policy methods? What is the main disadvantage?

Connects to: 8.5, 8.4

Exam Guidance Summary

Must-know: Exam covers up to on-policy MC. Key topics: MAB numerical problems (UCB), Bellman equations (expected vs optimal), value iteration, epsilon-greedy MC control algorithm trace-through.

Top pitfall: 'Asynchronous dynamic programming' in exam papers often means 'in-place update' — update one state at a time using most recent estimates.

Self-check: Is off-policy MC on the exam?

Connects to: 8.2, 8.3, 8.4

Key Industry Applications

Must-know: MC requires episodic tasks. Key domains: game playing, robotics, adaptive systems. UCB is practically deployed for A/B testing and clinical trials.

Self-check: Name two industry domains where MC methods are naturally applicable and explain why.

Connects to: 8.1, 8.6

Was this lecture useful?

Loading comments…
🤖

BitsNotes AI Assistant

Subject Notes Assistant

Configure AI Chat

Choose how to access the chatbot
Have your own API key?

Switch to "Bring Your Own Key" tab above for unlimited access with any OpenAI-compatible provider.

🔑 Enter API key above to fetch live models from provider, or enter model name manually.
OpenAI-Compatible API Support

Choose any provider preset (Gemini, DeepSeek, Kimi, GLM, MiniMax, Qwen, OpenAI, Groq, Ollama, etc.) or enter a custom endpoint URL.

Security & Privacy First

Your API key is sent directly from your browser to your specified provider. BitsNotes servers never store or see your key.