AI Wiki中文/EN

Monte Carlo learning: count complete returns, not just visits

蒙特卡洛强化学习

Compare first-visit and every-visit prediction, reject censored episodes and connect return estimates to policy improvement.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

One state, two visits, two different averages

Consider a made-up episode with states 0 → 1 → 0 → terminal and rewards 0, 1.6, 2. At discount 0.9, the returns after the three nonterminal visits are 3.06, 3.4 and 2. State 0 appears twice. Should its estimate use 3.06, or average 3.06 and 2 to obtain 2.53?

Both conventions are useful. They are called first-visit and every-visit Monte Carlo prediction. The difference is which observations enter the average, not whether the return is calculated from left to right or right to left. Sutton and Barto, Section 5.1 and Silver’s prediction lecture define the two conventions.

This hand-built episode can arise under a policy that allows leaving state 0 on a later visit. It is separate from the fixed advance/spin policy used in the training experiment below. Mixing those policies would change the quantity being estimated.

Repeated visits change the average; a separate training run compares first-visit and every-visit estimates with fresh-seed evaluation and a known-model value.
Repeated visits change the average; a separate training run compares first-visit and every-visit estimates with fresh-seed evaluation and a known-model value.

Average returns under a specified policy

Assume a finite Markov decision process, a fixed stationary policy pi, and episodes that terminate. State S_t is followed by reward R_(t+1) and the next state. The terminal time is T; gamma discounts future rewards. A complete return is

Gt=∑k=0T−t−1γkRt+k+1,vπ(s)=Eπ[Gt∣St=s].G_t=\sum_{k=0}^{T-t-1}\gamma^kR_{t+k+1},\qquad v_\pi(s)=\mathbb E_\pi[G_t\mid S_t=s].

Finite episodes permit gamma equal to 1, but termination alone does not guarantee finite expected returns or finite variance. Bounded rewards plus a discount strictly below 1 bound each return; undiscounted problems need suitable episode-length or return assumptions. The examples here satisfy these requirements.

For each episode i that visits state s, let tau_i(s) be its earliest visit. If N(s) such episodes have been observed, first-visit prediction uses

v^first(s)=1N(s)∑i: s∈iGτi(s)(i).\widehat v_{\mathrm{first}}(s)=\frac{1}{N(s)}\sum_{i:\,s\in i}G^{(i)}_{\tau_i(s)}.

Every-visit prediction instead uses all visit times. Its denominator counts visits, not episodes:

v^every(s)=∑i∑t=0Ti−11[St(i)=s]Gt(i)∑i∑t=0Ti−11[St(i)=s].\widehat v_{\mathrm{every}}(s)= \frac{\sum_i\sum_{t=0}^{T_i-1}\mathbf 1[S_t^{(i)}=s]G_t^{(i)}} {\sum_i\sum_{t=0}^{T_i-1}\mathbf 1[S_t^{(i)}=s]}.

In the opening example those denominators are 1 and 2 for state 0. Returns from repeated visits within one episode can be dependent. Under independent resets, a fixed Markov policy and finite-variance returns, first-visit samples from different episodes have the usual sample-mean interpretation. Every-visit consistency requires a separate argument; treating its visit count as a number of independent episodes is not valid. The working draft explicitly distinguishes these theoretical cases.

Neither method needs to keep every old return. Given a new accepted sample g, increment the count before updating the mean:

N(s)←N(s)+1,V(s)←V(s)+g−V(s)N(s).N(s)\leftarrow N(s)+1,\qquad V(s)\leftarrow V(s)+\frac{g-V(s)}{N(s)}.

This follows by writing the new sum as the old count times the old mean plus g. A fixed step size replaces the exact sample mean with an exponentially weighted estimate; that can track change, but it is a different estimator. An unvisited state’s initialized zero is not evidence that its value is zero.

From prediction to control

For control, average returns after state–action visits to estimate action values. For a selected collection J(s,a) of such visits,

Q(s,a)=1∣J(s,a)∣∑(i,t)∈J(s,a)Gt(i),St(i)=s, At(i)=a.Q(s,a)=\frac{1}{|J(s,a)|}\sum_{(i,t)\in J(s,a)}G_t^{(i)}, \qquad S_t^{(i)}=s,\ A_t^{(i)}=a.

The action is taken once, then the episode follows the policy being evaluated. Improving the policy uses the action with the largest estimated long-term return:

πgreedy(s)∈arg max⁡aQ(s,a).\pi_{\mathrm{greedy}}(s)\in\operatorname*{arg\,max}_{a}Q(s,a).

A practical on-policy loop collects exploratory episodes, updates visited action values, then adjusts the behavior policy toward promising actions while retaining coverage. This is the sampled counterpart of policy iteration. Finite noisy estimates do not inherit the exact improvement theorem automatically. If some actions never occur, their values cannot be inferred by averaging. Returns from a different behavior policy also cannot simply be relabeled as target-policy returns; off-policy estimation needs additional assumptions and, often, importance weighting. The chapter introduction separates prediction, improvement and control.

Compute backward; select visits forward

Save the standalone program as monte_carlo.py and run it with Python 3.12; it needs only the standard library. returns builds all suffix returns backward. estimate then scans visits in chronological order with a fresh seen set for each episode. Terminal states receive no samples.

"""Original monte_carlo teaching example; synthetic episodes, not benchmark reproduction."""
import json
import math
import random


def unit(x, name):
    if isinstance(x, bool) or not isinstance(x, (int, float)) or not math.isfinite(x) or not 0 <= x <= 1:
        raise ValueError(name+' must be finite in [0,1]')


def sequence(states, rewards, values, terminated):
    if type(terminated) is not bool or len(values)<2 or any(not math.isfinite(x) for x in values) or values[-1]!=0:
        raise ValueError('finite values with a zero terminal component required')
    if not rewards or len(states)!=len(rewards)+1 or any(not math.isfinite(r) for r in rewards):
        raise ValueError('nonempty finite rewards and one extra state required')
    terminal=len(values)-1
    if any(type(s) is not int or not 0<=s<=terminal for s in states):
        raise ValueError('state index outside table')
    if terminal in states[:-1] or (states[-1]==terminal)!=terminated:
        raise ValueError('termination flag must match the final state only')


class Arcade:
    def __init__(self, seed):
        self.rng = random.Random(seed)
        self.state = 2

    def reset(self):
        self.state = 0
        return self.state

    def step(self, action):
        if type(action) is not int or action not in (0, 1) or self.state == 2:
            raise ValueError('valid action and a nonterminal state required')
        if self.state == 0:
            self.state, reward = (2, 2.0) if action == 0 else (1, 0.0)
        elif action == 0:
            self.state, reward = 2, 4.0
        else:
            u = self.rng.random()
            self.state = 0 if u < .4 else 1 if u < .8 else 2
            reward = 1.6
        return self.state, reward, self.state == 2


def sample_episode(env, policy=(1,1), max_steps=10000):
    if len(policy)!=2 or any(type(a) is not int or a not in (0,1) for a in policy):
        raise ValueError('two valid deterministic actions required')
    if type(max_steps) is not int or max_steps<1:raise ValueError('positive step budget required')
    states=[env.reset()];rewards=[]
    for _ in range(max_steps):
        nxt,reward,done=env.step(policy[states[-1]])
        states.append(nxt);rewards.append(reward)
        if done:return states,rewards
    raise RuntimeError('incomplete episode: do not silently treat the cutoff as termination')


def returns(rewards,gamma=.9):
    unit(gamma,'gamma');out=[0.0]*len(rewards);g=0.0
    if any(not math.isfinite(r) for r in rewards):raise ValueError('finite rewards required')
    for t in range(len(rewards)-1,-1,-1):g=rewards[t]+gamma*g;out[t]=g
    return out


def estimate(episodes,gamma=.9,mode='first'):
    unit(gamma,'gamma')
    if mode not in ('first','every'):raise ValueError('unknown visit convention')
    v=[0.0]*3;count=[0]*3
    for states,rewards in episodes:
        sequence(states,rewards,v,True);targets=returns(rewards,gamma);seen=set()
        for s,g in zip(states[:-1],targets):
            if mode=='every' or s not in seen:
                count[s]+=1;v[s]+=(g-v[s])/count[s]
            seen.add(s)
    return dict(values=v,counts=count)


def demo():
    path=([0,1,0,2],[0.,1.6,2.]);env=Arcade(31)
    samples=[sample_episode(env) for _ in range(5000)]
    test_env=Arcade(37);test=[returns(sample_episode(test_env)[1])[0] for _ in range(2000)]
    return dict(repeated_visit_targets=returns(path[1]),first=estimate([path]),every=estimate([path],mode='every'),
                trained={mode:estimate(samples,mode=mode) for mode in ['first','every']},
                heldout_entry_mean=math.fsum(test)/len(test),model_reference=[360/79,400/79,0],
                episodes=5000,stored_transitions=sum(len(r) for s,r in samples))


if __name__=='__main__':
    print(json.dumps(demo(),indent=2,allow_nan=False))

The training environment is the original three-state arcade from the reinforcement-learning article: advance from entry for reward 0; in the room, spin for 1.6, then move to entry, room or terminal with probabilities 0.4, 0.4 and 0.2. The fixed policy always advances or spins. Its model values, used only for comparison, are approximately 4.556962 and 5.063291.

Seed 31 produces 5,000 complete episodes and 39,512 transitions. First-visit estimates are approximately [4.536619, 5.040688], using 5,000 samples per state; every-visit estimates are [4.515450, 5.024588], using 14,816 and 24,696 visits. A separate seed 37 gives entry mean 4.476224 across 2,000 episodes. These are sampled results, not a ranking of which estimator is universally better or a confidence interval.

The sampler raises an error if its safety budget expires. It never silently treats that cutoff as natural termination, and never quietly discards long episodes until a desired sample count is reached. For total observed transitions M, return computation and estimation take O(M) time in this fixed three-state example. The estimator’s working space is O(S + T_max) for its table, visit set and one episode’s returns. This demonstration additionally stores all training episodes so both conventions use identical data: O(M) storage. A streaming version could avoid that storage.

A complete observed episode is part of the estimator

Plain episodic MC must wait for the final reward before updating a visit. In a continuing task, a time-limited prefix is not automatically a complete return. Bootstrapping its missing tail leads toward TD learning or n-step returns, rather than the estimator implemented here.

Rare states, long episodes and variable rewards can make averages slow to stabilize. Repeated visits increase data but also create dependence. Approximate state representations can merge different futures; no amount of averaging repairs a definition of state that omits relevant information. The program demonstrates fixed-policy prediction; it does not implement a complete MC control or off-policy algorithm.

Choose the samples before calculating the answer

  1. Returns are computed backward. Does this make the last visit the first visit?

    Answer: No. First means earliest in episode time. Compute suffix returns backward, then use chronological visits or explicitly retain the earliest index.

  2. For the opening episode, calculate both state-0 estimates and their counts.

    Answer: The first return is 0 + 0.9 × 1.6 + 0.9² × 2 = 3.06. The later return is 2. First-visit uses 3.06 with count 1; every-visit uses (3.06 + 2)/2 = 2.53 with count 2.

  3. You stop collecting at 100 steps and assign zero to the unseen future. Is this still an unbiased complete-return estimate of the original continuing task?

    Answer: Not generally. You changed the target by removing the remaining return. Declare a finite-horizon task, bound the omitted tail where possible, or use a justified bootstrap; do not disguise a collection limit as termination.

  4. A controller has only ever chosen action 0 in a state. Can greedy improvement prove that action 0 is best?

    Answer: No. There is no sampled return for the alternatives. Gather action coverage or bring in a justified model; initialized values are not observations. Even with coverage, finite estimation error must be considered.

The model-free part is the expectation, not the goal

Silver’s lecture connects incremental means to prediction without a transition table. Sutton and Barto’s working draft places that prediction inside generalized policy iteration. Both still require a defined policy, reward objective and episode convention. Here the programs and episodes are original; no textbook blackjack experiment is reproduced.

Make a prediction, then check

A state appears twice in one episode. Which return does first-visit MC use?

Choose one answer

Learning objectives

  • Calculate first-visit and every-visit estimates on an episode with a repeated state.
  • State the sampling assumptions and explain why control needs action coverage and policy improvement.

Prerequisites & connections

Explore related knowledge →

References

  1. Reinforcement Learning: An Introduction — second-edition working draft (2014–2015)
    Richard S. Sutton; Andrew G. Barto · 2015
  2. Lecture 4: Model-Free Prediction
    David Silver · 2015

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-23 · Single AI author. Scoped reading: PDF127–129 chapter5 opening/§5.1: complete episodic returns, first/every visits and iid versus dependent samples. Read2026-09-23. Author teaching page identifies the 2015 course; 2025 upload path is not the lecture year. Read PDF1,3–7,10–13,16–18,29,32,35,37,40–45. MC visit conventions, incremental means, TD targets, n-step returns, accumulating traces and explicitly offline equivalence. General bias/variance summaries are teaching heuristics, not unconditional variance or efficiency theorems. No slides/images copied. 6 paired equations and four explained exercises. Checked backward returns by direct sums, chronological first visits, repeat counts, episode reset, missing samples, incomplete-episode failure, seeded training and independent evaluation. Hand path and training policy are different experiments.

  • Checked backward returns by direct sums, chronological first visits, repeat counts, episode reset, missing samples, incomplete-episode failure, seeded training and independent evaluation. Hand path and training policy are different experiments.
  • Four computed SVG variants per topic;12 numeric/geometry tests and36 responsive cases passed. All twelve selected current captures directly viewed; browser inputs bound by SHA before integration. Full article acceptance recorded separately.

Source locations checked:

  • Reinforcement Learning: An Introduction — second-edition working draft (2014–2015) · PDF127–129 chapter5 opening/§5.1: complete episodic returns, first/every visits and iid versus dependent samples. Read2026-09-23.
  • Lecture 4: Model-Free Prediction · Author teaching page identifies the 2015 course; 2025 upload path is not the lecture year. Read PDF1,3–7,10–13,16–18,29,32,35,37,40–45. MC visit conventions, incremental means, TD targets, n-step returns, accumulating traces and explicitly offline equivalence. General bias/variance summaries are teaching heuristics, not unconditional variance or efficiency theorems. No slides/images copied.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.