Monte Carlo Prediction
Imagine teaching an agent to play blackjack purely by watching thousands of hands play out. No rulebook of transition probabilities exists in the agent's head. Only the raw experience of cards dealt, decisions made, and chips won or lost at the end. Monte Carlo prediction turns this raw experience into estimates of how good each situation actually is. It does this simply by averaging what happened afterward. This matters because most real-world sequential decision problems do not come with a known Markov Decision Process model. A robot does not know its exact friction coefficients. A trading agent does not know tomorrow's price distribution. Whenever an agent can only sample trajectories — by acting or by observing — rather than query a transition model, Monte Carlo methods provide a direct, model-free route to evaluating a policy. This is the foundational move. It separates dynamic-programming style reasoning, which assumes perfect knowledge of the environment, from learning purely from interaction. The big picture is simple and powerful. The value of a state under a policy is defined as an expected return. An expectation can be estimated by an average of samples. Monte Carlo prediction is exactly this idea applied to full episodes. It requires no model of the environment's dynamics. It requires no bootstrapping from other estimates. Its correctness rests entirely on the law of large numbers. This article builds Monte Carlo prediction from first principles. It covers the precise problem definition, the first-visit and every-visit algorithms with full pseudocode. It also includes a rigorous complexity and convergence discussion, a hand-traced numerical example, and common implementation traps. Finally, it traces the historical lineage connecting this method to the broader development of reinforcement learning. It sets up the natural next steps — Monte Carlo control and temporal-difference learning — without requiring them yet.
- Monte Carlo (MC) prediction estimates by averaging observed returns following visits to across sampled episodes.
- It requires only episodic experience — no model of transition probabilities or rewards is needed.
- Two variants exist: first-visit MC (average return after the first visit per episode) and every-visit MC (average return after every visit).
- Estimates are unbiased (first-visit) or asymptotically unbiased (every-visit), and both converge almost surely by the law of large numbers.
- MC prediction only updates values at episode end, unlike bootstrapping methods, so it needs complete episodes and has higher variance but no bias from initial estimates.
- It is the natural precursor to Monte Carlo control and stands in direct contrast to temporal-difference methods like TD(0).
Estimate a state's value by literally averaging the total return that followed every time the agent visited that state, across many sampled episodes.
The idea
Recall that the value of state under policy is defined as the expected return starting from and following thereafter:
where is the Return — the discounted sum of future rewards from time to the end of the episode. Monte Carlo prediction estimates this expectation directly from data: run the policy to generate complete episodes, record the return that follows each visit to , and average those returns. As more episodes are collected, this sample average converges to the true expectation by the law of large numbers — no model of the environment's transition or reward dynamics is ever consulted. This is fundamentally different from dynamic programming approaches to the same problem, which compute by solving the Bellman Equation using a known model . Monte Carlo prediction instead treats the environment as a black box that can only be sampled, one episode at a time. It is also different from bootstrapping methods, which we have not yet introduced, in that Monte Carlo never uses one value estimate to update another — it only uses actual, realized returns. This makes each Monte Carlo estimate for a given state independent of the estimates of all other states, a property that will matter later when comparing bias and variance against TD methods. Two bookkeeping conventions exist because a single episode may visit the same state multiple times (in problems with cycles). First-visit MC counts, for each episode, only the return following the first time is entered, and averages these across episodes. Every-visit MC counts the return following every occurrence of within an episode. Both converge to , but they have different statistical properties: first-visit returns from different episodes are independent and identically distributed samples of , giving a classical unbiased estimator; every-visit returns within the same episode are correlated, so the every-visit estimator is only asymptotically unbiased, though in practice it usually has lower variance because it uses more data per episode.
How it works
The mechanism has three moving parts: a way to generate episodes under the policy being evaluated, a per-state return accumulator, and an averaging step. Concretely: 1. Generate an episode. Starting from some initial state, follow policy (which may be stochastic) until a terminal state is reached, recording the sequence . 2. Compute returns backward. Walk the episode from the end to the start, maintaining a running return . This computes all values in a single backward pass in time instead of recomputing each sum from scratch. 3. Update the average for each visited state, either only on first visit or on every visit, using an incremental mean update so no growing list of past returns needs to be stored. Here is the full first-visit Monte Carlo prediction algorithm, followed by the small modification needed for every-visit. ``` Algorithm: First-Visit Monte Carlo Prediction Input: policy π to be evaluated, discount factor γ ∈ (0,1] Initialize: V(s) ← arbitrary, for all states s # value estimate N(s) ← 0, for all states s # visit counter Returns_sum(s) ← 0, for all states s # running sum of returns Repeat for each episode: Generate an episode following π: S0, A0, R1, S1, A1, R2, ..., S_{T-1}, A_{T-1}, R_T (terminal at time T) G ← 0 visited_in_this_episode ← empty set for t = T-1 downto 0: G ← γ G + R_{t+1} if S_t is NOT in visited_in_this_episode: add S_t to visited_in_this_episode N(S_t) ← N(S_t) + 1 Returns_sum(S_t) ← Returns_sum(S_t) + G V(S_t) ← Returns_sum(S_t) / N(S_t) Output: V ≈ v_π ``` ``` Algorithm: Every-Visit Monte Carlo Prediction (identical, but remove the "if S_t is NOT in visited_in_this_episode" guard — update N(S_t) and Returns_sum(S_t) on every occurrence of S_t in the episode) ``` An equivalent and more memory-friendly formulation avoids storing `Returns_sum` explicitly and instead uses the incremental sample-mean update: ``` N(S_t) ← N(S_t) + 1 V(S_t) ← V(S_t) + (1 / N(S_t)) (G - V(S_t)) ``` This is mathematically identical to recomputing the mean of all returns seen so far, but it only requires extra memory per state rather than storing every past return. It also generalizes naturally to a constant step-size variant, `V(S_t) ← V(S_t) + α (G - V(S_t))`, which trades the guarantee of exact averaging for the ability to track a slowly changing (non-stationary) policy or environment — a preview of ideas used heavily in Monte Carlo control and TD learning.
Complexity & correctness
Time complexity. Generating one episode of length under policy costs environment steps (this cost is intrinsic to sampling, not to the algorithm). Computing all returns via the backward pass is , since each step does work (`G ← γG + R`) and there are steps. Updating the value table with the incremental-mean formula is per visited state, so first-visit MC costs total per episode (each state contributes at most once), and every-visit MC also costs total per episode (each of the time steps contributes exactly one update). Over episodes, total time is where is average episode length — linear in the total amount of experience generated, which is optimal since every reward must be read at least once.
Space complexity. The algorithm needs one counter and one value per state, so space is , independent of the number of episodes — this is the payoff of the incremental-mean update over naively storing every observed return. If the state space is continuous or function-approximated, this becomes where is the number of parameters, but that extension belongs to later material.
Correctness argument. Fix a state that has nonzero probability of being visited under . Under first-visit MC, each episode in which occurs contributes exactly one return sample , and these samples across episodes are independent and identically distributed draws from the conditional distribution of (independence follows because episodes are generated independently of one another, assuming the policy and environment are fixed and memoryless given the state). By definition,
The sample mean after visits is
By the strong law of large numbers, almost surely as , provided the returns have finite variance (guaranteed when rewards are bounded and , or when but the episode is guaranteed to terminate in finite expected time). Moreover is an unbiased estimator of for every finite , since exactly — this is the classical unbiasedness of a sample mean of i.i.d. draws. For every-visit MC the argument is subtler: within a single episode, multiple returns following repeated visits to are not independent (they share tail rewards and later states). The estimator is therefore biased for small , but it remains consistent: as the number of episodes grows, the bias vanishes and almost surely, a result that follows from a law of large numbers for suitably mixing/martingale sequences rather than the plain i.i.d. case. In practice both estimators are used, and the every-visit version is often preferred with function approximation because it makes more efficient use of each episode's data.
Key tradeoff versus dynamic programming and TD. Monte Carlo prediction needs no model, unlike DP. It has zero bias (first-visit) because it never bootstraps off a possibly-wrong current estimate, unlike TD(0), which we build toward next. But it pays for this with two costs: it needs the episode to actually terminate before any update can happen, so it cannot be used in continuing (non-episodic) tasks without modification, and its variance can be large because a single return accumulates noise from an entire trajectory of random rewards and transitions, whereas TD updates use only one step of real reward plus a bootstrapped estimate.
Worked example
Consider a tiny episodic gridworld-like problem simplified to a single Markov chain with states , a fixed policy (deterministic transitions given here for concreteness), discount factor , and the following three sampled episodes (state sequence with rewards received on each transition):
| Episode | Trajectory (state → reward → state ...) |
|---|---|
| 1 | A → +2 → B → +1 → A → +0 → C → +3 → terminal |
| 2 | B → −1 → C → +4 → terminal |
| 3 | A → +2 → C → +1 → B → +0 → C → +2 → terminal |
We compute first-visit MC estimates for , , .
Episode 1: sequence with rewards . Backward pass (, so ):
| t (backward) | state | R | G after update |
|---|---|---|---|
| 3 | C | 3 | 3 |
| 2 | A (2nd visit) | 0 | 3 |
| 1 | B | 1 | 4 |
| 0 | A (1st visit) | 2 | 6 |
First-visit rule: A's first visit is at with ; the later revisit of A at (giving ) is ignored. B's only visit gives . C's only visit gives . Contributions from episode 1: , , .
Episode 2: sequence with rewards .
| t (backward) | state | R | G |
|---|---|---|---|
| 1 | C | 4 | 4 |
| 0 | B | −1 | 3 |
Contributions: , .
Episode 3: sequence with rewards .
| t (backward) | state | R | G |
|---|---|---|---|
| 3 | C (2nd visit) | 2 | 2 |
| 2 | B | 0 | 2 |
| 1 | C (1st visit) | 1 | 3 |
| 0 | A | 2 | 5 |
First-visit C is at with (the later occurrence at , , is discarded). B's only visit gives . A's only visit gives . Contributions: , , .
Averaging across episodes (first-visit):
| State | Returns collected | ||
|---|---|---|---|
| A | 6, 5 | 2 | 5.5 |
| B | 4, 3, 2 | 3 | 3.0 |
| C | 3, 4, 3 | 3 | 3.33 |
These are the first-visit Monte Carlo estimates after just three episodes. Note how episode 1 contributed only one A-sample (6, from the first visit) even though A was visited twice — this is exactly the first-visit rule in action. An every-visit version would additionally fold in the second A-return (3) from episode 1, giving and — noticeably different at this small sample size, illustrating why the two estimators can disagree substantially before convergence, even though both converge to the same in the limit.
Common pitfalls & traps
| Pitfall | Why it happens | Fix |
|---|---|---|
| Computing returns forward instead of backward | Recomputing from scratch for every costs per episode | Always accumulate walking from down to |
| Forgetting the first-visit guard, thinking it's "the same algorithm" | First-visit and every-visit give different (though both convergent) estimates, especially early on | Explicitly track a per-episode visited-set and only decide once which rule you're using |
| Applying MC prediction to a non-terminating (continuing) task | No episode ever ends, so is never fully realized and no update ever fires | Use TD methods for continuing tasks, or truncate/wrap the task into episodes explicitly |
| Using with returns that don't provably terminate | If the policy can loop forever with positive probability, has infinite variance or is undefined | Ensure the policy-environment pair guarantees termination, or discount with |
| Confusing sample averaging with a fixed learning rate | Using constant makes MC track non-stationary targets but loses the exact-mean guarantee | Use step size for the classical estimator; use constant only intentionally |
| Updating mid-episode using an in-progress, incomplete return | Breaks the "complete episode" requirement that makes the sample an honest realization of | Only update after the terminal state is reached and the full backward pass is done |
Pioneers & history
Monte Carlo estimation as a general numerical technique predates reinforcement learning by decades, but its formal integration into value-function estimation for sequential decision problems was crystallized in the reinforcement learning literature of the late 20th century, building on decades of work in stochastic approximation, statistics, and simulation.
Origins · 1 minStanislaw Ulam and how this was discovered
Ulam, working alongside John von Neumann, conceived the Monte Carlo method while considering the probability of winning at solitaire and later applying the same sampling logic to neutron diffusion problems for nuclear weapons design. The core insight — that a hard-to-compute expectation can be approximated by simulating many random trials and averaging the outcomes — is the direct mathematical ancestor of every Monte Carlo method used in reinforcement learning today, including Monte Carlo prediction.
Where this matters
Monte Carlo prediction is the conceptual seed for Monte Carlo control, where the same return-averaging idea is applied to action-value functions and combined with policy improvement to learn optimal behavior directly from episodes — used historically in classic game-playing agents and still taught as the cleanest bridge from prediction to control. It is also the direct comparison point for temporal-difference learning: TD(0), which replaces the full-episode return with a one-step bootstrapped target, trading some bias for dramatically reduced variance and the ability to learn online without waiting for episode termination; understanding Monte Carlo prediction thoroughly is what makes the tradeoffs of TD learning legible. In applied systems, Monte Carlo estimation of value functions underlies Monte Carlo Tree Search (MCTS), the search technique behind AlphaGo and its successors, where rollouts to the end of a simulated game are averaged to estimate the value of a board position exactly as in Monte Carlo prediction. Return-averaging ideas also appear in off-policy evaluation for recommendation systems and clinical trial analysis, where historical logged episodes (user sessions, treatment courses) are used to estimate the value of a candidate policy before it is ever deployed, precisely because no accurate simulator of user behavior or patient physiology exists. Any setting where an agent or analyst has only logged trajectories, and not a model, is a natural home for Monte Carlo prediction or its variance-reduced cousins.
Ask the tutor: How does the bias–variance tradeoff between Monte Carlo prediction and TD(0) actually play out in a concrete multi-state example?
Does Monte Carlo prediction require knowing the environment's transition probabilities?
No — that is precisely its defining advantage. Monte Carlo prediction only requires the ability to sample episodes by following the policy, either through direct interaction with an environment or through a simulator whose internal dynamics need not be known analytically. Dynamic programming methods, by contrast, need the full transition and reward model to solve the Bellman equations exactly. This makes Monte Carlo prediction applicable to any problem where you can generate experience — games, robotics, logged human behavior — even when writing down exact transition probabilities would be impossible or intractable.
Why does Monte Carlo prediction need complete episodes rather than working step by step?
The return is defined as the sum of all discounted future rewards from time until the episode ends. Until the terminal state is actually reached, this sum is incomplete and cannot serve as a valid sample of the true expected return. Waiting for termination guarantees that every update uses a genuine, unbiased realization of , at the cost of not being able to update value estimates online, mid-episode. This is the central structural difference from temporal-difference methods, which build targets from a single reward plus a bootstrapped estimate and can update after every single step.
Is the Monte Carlo value estimate biased?
The first-visit estimator is exactly unbiased for every finite number of episodes, because each episode contributes one independent sample from the true conditional distribution of the return given that state. The every-visit estimator is biased for small sample sizes because returns from repeated visits within the same episode are statistically correlated, sharing overlapping future rewards, but this bias vanishes asymptotically and the estimator remains consistent. In practice, with enough episodes, both estimators converge to the same true value .
How does Monte Carlo prediction handle states that are never visited under the policy?
It simply never updates them — their value estimate stays at its arbitrary initialization forever, since no return is ever attributed to a state that never occurs on a sampled trajectory. This is a genuine limitation: Monte Carlo prediction can only learn about states (and, in the control setting, actions) that have nonzero probability of occurring under the behavior generating the episodes. This is exactly why exploration — ensuring enough visitation coverage — becomes a central concern once Monte Carlo ideas are extended from prediction to control.
What is the variance tradeoff of Monte Carlo prediction compared to bootstrapping methods?
Monte Carlo returns accumulate randomness from every reward and every transition across an entire episode, so a single return sample can have high variance, especially in long or highly stochastic episodes. Bootstrapping methods like TD(0) instead build a target from only one real reward plus a current value estimate, which has much lower variance per update but introduces bias whenever that current estimate is inaccurate. This bias-variance tradeoff is the central theoretical comparison point between Monte Carlo prediction and temporal-difference learning, and neither method dominates the other in every setting.
Can Monte Carlo prediction be used with a constant learning rate instead of an exact sample average?
Yes, and this is a common practical variant: instead of `V(s) ← V(s) + (1/N(s))(G − V(s))`, one uses `V(s) ← V(s) + α(G − V(s))` for a fixed step size α. The exact-average version is optimal for a fixed, unchanging policy in a stationary environment, since it weights every past return equally. The constant-α version instead gives more weight to recent returns, letting the value estimate track a policy or environment that changes over time — a property that becomes essential once Monte Carlo methods are combined with policy improvement in Monte Carlo control.
How does Monte Carlo prediction relate to Monte Carlo Tree Search?
Monte Carlo Tree Search uses the same core statistical idea — estimate a value by averaging outcomes of simulated rollouts — but applies it inside a search tree during planning rather than to a fixed dataset of past episodes. Each simulated rollout in MCTS plays out a full trajectory (often to a terminal state or a fixed depth) and the resulting return is averaged into the value estimate of every tree node visited along the way, exactly mirroring first-visit or every-visit Monte Carlo prediction. This shared foundation is why understanding Monte Carlo prediction directly clarifies how modern search-based game-playing agents estimate position values.