Module contents
Lesson 9 of 37Core 100 min

Monte Carlo learning: evaluation and control by averaging episodes

Estimate and control episodic returns using Monte Carlo methods, first and every visit, and off-policy importance sampling.

After this lesson you can

  • Compare first-visit and every-visit prediction, including finite-sample bias.
  • Explain exploring starts, ε-soft policies and GLIE conditions.
  • Derive ordinary and weighted off-policy importance sampling.
  • Analyze horizon effects, infinite variance and per-decision correction.
  • Implement incremental weighted importance sampling.

Before you start

Learning from complete episodes

Evaluating a policy using Bellman equations required the transition model. If we can generate episodes but do not know that model, we can still observe and average the return following a visit. In blackjack it is easy to deal simulated cards, though writing all transition probabilities and consequences of each hand is laborious.

Monte Carlo prediction estimates Vπ(s)=Eπ[Gt∣St=s]V^\pi(s)=\mathbb E_\pi[G_t\mid S_t=s] from episodes generated following π\pi. Here we assume a fixed policy, stationary Markov dynamics and independent episodes that terminate almost surely, with integrable returns. Continuing processes need a different construction: truncation is not automatically equivalent to observing a complete episode and can introduce tail bias.

First visit and every visit

In first visit, each episode reaching ss contributes the return from its first occurrence. Conditional on having reached ss, the Markov property and fixed policy give the same expected value Vπ(s)V^\pi(s). With independent episodes and a positive number of returns, their mean is unbiased; if variance is also finite, typical error decreases with the square root of the number of relevant episodes. Without visits there is no estimate, not a zero value.

In every visit, an episode contributes a return for each occurrence of ss. Those returns can be correlated and the number of visits depends on the trajectory. Their pooled average can be biased for few episodes, although under suitable conditions it converges to the same value. Not every task has this bias: it depends on the process and averaging method.

InteractiveRevisiting does not create independent episodes

Preparing visits.

Follow a trajectory and compare the returns included in each estimator.

For example, consider two states, AA and terminal. From AA reward one is received and the process returns to AA with probability 1/21/2; otherwise it terminates. With γ=1\gamma=1, duration LL is geometric and V(A)=E[L]=2V(A)=\mathbb E[L]=2. First visit contributes LL and has expectation two. With one episode, every visit averages L,L−1,…,1L,L-1,\ldots,1, namely (L+1)/2(L+1)/2, whose expectation is 3/23/2. For nn independent episodes, pooling all visits gives

∑i=1nLi(Li+1)/2∑i=1nLi→c.s.E[L(L+1)/2]E[L]=2.\frac{\sum_{i=1}^n L_i(L_i+1)/2}{\sum_{i=1}^n L_i} \xrightarrow{\mathrm{c.s.}}\frac{\mathbb E[L(L+1)/2]}{\mathbb E[L]}=2.

The strong law applies here to per-episode sums with finite moments; returns within an episode are not treated as independent samples. This comparison is studied in Singh and Sutton. To update an exact mean when adding return number nn, use Q←Q+(G−Q)/nQ\leftarrow Q+(G-Q)/n; a constant step gives different weighting and is not the same mean.

Blackjack and model-free decisions

We use Sutton and Barto’s model, example 5.1: an infinite deck with replacement, cards two to nine and ace each with probability 1/131/13, and value ten with probability 4/134/13. An ace is usable if it can count as eleven without exceeding 21. The dealer hits until reaching at least 17, including standing on soft 17; win, draw or loss give terminal reward +1+1, 00 or −1-1. An initial player natural ends in a win unless the dealer also has a natural, which draws. Distinguish this from 21 reached later.

A decision representation uses the player’s sum, dealer’s visible card and presence of a usable ace. The reference policy hits below 20 and stands on 20 or 21. Unvisited cells have no estimated value; a surface from few episodes is noisy and may not cover them. In the decision states considered, a card increases the sum while the usable-ace indicator stays unchanged; on losing that indicator the sum can decrease, but the indicator cannot turn on again for a sum of at least 12. Thus the same complete state is not repeated in an episode and first and every visit coincide in this representation.

InteractiveBlackjack values and decisions

Preparing the blackjack simulator.

Generate reproducible episodes and examine visited states, coverage and the estimated policy.

Without a model, knowing only V(s′)V(s') does not let us evaluate ∑s′P(s′∣s,a)V(s′)\sum_{s'}P(s'\mid s,a)V(s') to compare actions. Monte Carlo control estimates Q(s,a)Q(s,a) from returns following state–action pairs and improves the policy using those values. With exploring starts, the experiment must be able to begin in each relevant pair with positive probability; shuffling natural games is insufficient if some pairs never occur at the start. The forced abstract state must be consistent with the simulator’s hidden-variable distribution.

An ε\varepsilon-soft policy assigns at least ε/∣A(s)∣\varepsilon/|\mathcal A(s)| to each available action. An ε\varepsilon-greedy policy is a special case: it distributes remaining mass among greedy actions according to the chosen tie rule. Fixed ε\varepsilon maintains exploration: if there are non-greedy actions, they retain positive probability. GLIE simultaneously requires infinitely many visits to each relevant pair and a policy that becomes greedy. εt→0\varepsilon_t\to0 does not guarantee the first condition: if reaching a pair requires multiple consecutive explorations, their probabilities may be summable. Nor is invoking GLIE enough to prove convergence of arbitrary MC control that changes policy during learning. Analysis of MC with exploring starts requires additional assumptions; Wang and colleagues study specific classes.

Evaluating one policy with trajectories from another

In off-policy learning, behavior bb generates data and target policy π\pi is the one we wish to evaluate. For a finite episode and a visit to ss at tt, define

ρt:T−1=∏k=tT−1π(Ak∣Sk)b(Ak∣Sk).\rho_{t:T-1}=\prod_{k=t}^{T-1}\frac{\pi(A_k\mid S_k)}{b(A_k\mid S_k)}.

Behavior must cover actions the target can take in relevant states and trajectories. Dynamics are the same under both policies: when forming the ratio of trajectory probabilities, transitions cancel. Under necessary integrability conditions, ordinary estimator n−1∑iρiGin^{-1}\sum_i\rho_iG_i has expectation Vπ(s)V^\pi(s). If evaluating Q(s,a)Q(s,a) with the first action forced in both distributions, the product starts at the next action.

Weighted importance sampling uses ∑iρiGi/∑iρi\sum_i\rho_iG_i/\sum_i\rho_i. When the denominator is positive it is a weighted average of returns; it usually has finite-sample bias because it is a ratio and, under suitable conditions, is consistent. If all weights are zero it is undefined: substituting zero is an additional convention that changes its properties.

InteractiveThe rarity of a compatible trajectory

Preparing estimates.

Compare estimates and denominators for explicit finite behavior and target policies.

A finite example shows why horizon matters. If the target always chooses one action, behavior chooses it with probability p>0p>0 in each of HH rounds, and terminal reward is one only if all match, the ordinary weighted return is p−Hp^{-H} with probability pHp^H and zero otherwise. Its expectation is one and the variance of the average of nn independent episodes is (p−H−1)/n(p^{-H}-1)/n. For p<1p<1 it grows exponentially with HH. The correction is unbiased, but informative data can be very rare.

Infinite variance without denying the strong law

In Sutton and Barto’s example 5.5, the target always chooses to return; behavior chooses return or terminate with probability 1/21/2 each. On returning, it terminates with reward one with probability 0,10,1, or returns to the state with probability 0,90,9 and zero reward. Terminating by the other action gives zero. For a successful trajectory of n≥1n\geq1 returns, probability under behavior is 0,05⋅0,45n−10,05\cdot0,45^{n-1} and weight is 2n2^n. Thus,

Eb[ρG]=0,1∑n≥10,9n−1=1,Eb[(ρG)2]=0,2∑n≥11,8n−1=∞.\mathbb E_b[\rho G]=0,1\sum_{n\geq1}0,9^{n-1}=1,\qquad \mathbb E_b[(\rho G)^2]=0,2\sum_{n\geq1}1,8^{n-1}=\infty.

The ordinary estimator has infinite variance. Even so, E∣ρG∣=1\mathbb E|\rho G|=1: for i.i.d. episodes, the strong law guarantees that the mean converges almost surely to one. A finite sequence may look unstable for a long time without contradicting that result. In this particular example, the weighted estimator is exactly one when at least one weight is positive and undefined otherwise; do not extrapolate that coincidence to other problems.

Correcting each reward only as far as needed

For a finite horizon, linearity of expectation allows writing per-decision importance sampling of a state return as

G^t=∑k=tT−1γk−tρt:kRk+1.\widehat G_t=\sum_{k=t}^{T-1}\gamma^{k-t}\rho_{t:k}R_{k+1}.

Reward Rk+1R_{k+1} depends on actions up to kk, not later actions. Under coverage and integrability conditions, integrating future ratios gives one and each term retains its target expectation. This can reduce variance compared with multiplying the whole return by the full ratio, but does not guarantee strict reduction in every problem. With a deterministic target policy, an action mismatch makes the product zero from that point: in backward control only compatible tails contribute to corresponding updates.

In partially observable problems, averaging returns conditional on a history can still estimate an expectation, but value conditioned only on an observation can mix different histories. Monte Carlo does not itself remove this information loss or turn the observation into a Markov state. Later we compare this complete-episode extreme with bootstrapping and multi-step returns.

We use an infinite deck with replacement: ace and cards 2 to 9 have probability 1/13, and value 10 has probability 4/13. The dealer hits below 17 and also stands on soft 17; the player receives −1, 0 or 1 at termination. An initial player natural ends immediately and wins unless the dealer also has a natural. If the player has no natural, the dealer’s hidden card remains unconditioned and the later result is decided by sums. Exploring starts represent later decision states and are not reinterpreted as initial naturals. See Sutton and Barto, examples 5.1 and 5.3.

[ ]Blackjack and first-visit predictionBrowser
import random

def card(rng):
    return min(rng.randint(1,13),10)

def hand(cards):
    total=sum(cards)
    usable=1 in cards and total+10<=21
    return total+10*usable, bool(usable)

def add_card(total,usable,c):
    if c==1 and total+11<=21:
        total+=11; usable=True
    else:
        total+=c
    if total>21 and usable:
        total-=10; usable=False
    return total,usable

def natural(cards):
    return len(cards)==2 and sorted(cards)==[1,10]

def episode(rng,decision,forced_start=None):
    if forced_start is None:
        player=[card(rng),card(rng)]; dealer=[card(rng),card(rng)]
        if natural(player):
            return [],0 if natural(dealer) else 1
        total,usable=hand(player)
        while total<12:
            total,usable=add_card(total,usable,card(rng))
        showing=dealer[0]; forced_action=None
    else:
        # Se fuerza un estado de decisión; la carta oculta sigue siendo incondicional.
        total,showing,usable,forced_action=forced_start
        dealer=[showing,card(rng)]
    trajectory=[]
    while True:
        state=(total,showing,usable)
        action=forced_action if forced_action is not None else decision(state,rng)
        forced_action=None
        trajectory.append((state,action))
        if action==0: break  # 0: plantarse; 1: pedir.
        total,usable=add_card(total,usable,card(rng))
        if total>21: return trajectory,-1
    dealer_total,dealer_usable=hand(dealer)
    while dealer_total<17:
        dealer_total,dealer_usable=add_card(dealer_total,dealer_usable,card(rng))
    if dealer_total>21: return trajectory,1
    return trajectory,(1 if total>dealer_total else (-1 if total<dealer_total else 0))

assert hand([1,1,9])==(21,True)
assert add_card(20,True,1)==(21,True)
assert add_card(21,True,10)==(21,False)
assert natural([1,10]) and not natural([1,1,9])

def fixed_policy(state,rng):
    return int(state[0]<20)

def prediction(seed,n):
    rng=random.Random(seed); sums={}; counts={}
    for _ in range(n):
        trajectory,ret=episode(rng,fixed_policy)
        seen=set()
        for state,_ in trajectory:
            if state not in seen:
                seen.add(state)
                sums[state]=sums.get(state,0)+ret
                counts[state]=counts.get(state,0)+1
    return {s:sums[s]/counts[s] for s in counts},counts

values,visits=prediction(1901,3000)
print('Predicción: episodios',3000,'estados visitados',len(visits),'de 200')
for state in ((20,10,False),(13,1,True)):
    print('estado',state,'visitas',visits.get(state,0),'valor',values.get(state,'sin visitas'))

The evaluated policy hits below 20. In this representation decision states do not repeat within a hand, so first and every visit coincide here. Cell figures come from 3000 episodes; they are not the 10 000- and 500 000-episode surfaces published in figure 5.2 of the book. To reduce noise increase the number of episodes and retain visit counts.

[ ]Monte Carlo control: exploring starts and ε-softBrowser
import random
import math

def control(seed,n,exploring_starts,epsilon=.1):
    rng=random.Random(seed)
    states=[(total,showing,usable) for total in range(12,22)
            for showing in range(1,11) for usable in (False,True)]
    Q={(s,a):0.0 for s in states for a in (0,1)}
    counts={(s,a):0 for s in states for a in (0,1)}
    policy={s:int(s[0]<20) for s in states}
    def decide(state,rng):
        if not exploring_starts and rng.random()<epsilon:
            return rng.randrange(2)
        return policy[state]
    for _ in range(n):
        start=None
        if exploring_starts:
            state=states[rng.randrange(len(states))]
            start=(*state,rng.randrange(2))
        trajectory,ret=episode(rng,decide,start)
        seen=set()
        for state,action in trajectory:
            key=(state,action)
            if key not in seen:
                seen.add(key); counts[key]+=1
                Q[key]+=(ret-Q[key])/counts[key]
        # La política no cambia durante la trayectoria recién generada.
        for state,_ in trajectory:
            current=policy[state]
            if Q[(state,1-current)]>Q[(state,current)]:
                policy[state]=1-current
    return Q,counts,policy

for name,es in [('arranques exploratorios',True),('ε-soft',False)]:
    Q,counts,policy=control(2901,3000,es,epsilon=.1)
    print(name,'episodios',3000,'pares visitados',sum(n>0 for n in counts.values()),'de',len(counts))
    for usable in (False,True):
        print('as usable',usable,'acciones para sumas 12..21 contra 10:',
              ''.join('P' if policy[(total,10,usable)] else 'S' for total in range(12,22)))

P means hit and S stand. The ε-soft policy uses constant exploration ε=0,1: it explores, but is not GLIE because ε does not tend to zero. Exploring starts cover possible pairs without promising that a short run reaches the optimal policy. The figures are from this run; a reliable comparison with the reference policy needs many more games and identical conditions.

The first process is the infinite-variance example of Sutton and Barto, example 5.5. Behavior chooses volver or terminar with probability 1/2. With volver, the process returns to the same state with probability 0,9 and terminates with reward 1 otherwise; terminar ends with reward 0. The target policy always chooses volver. We do not artificially truncate episodes.

[ ]IS in an infinite-variance processBrowser
import random

def infinite_variance_episode(rng):
    weight=1.0
    while True:
        if rng.random()>=.5:
            return 0.0,0.0
        weight*=2
        if rng.random()<.1:
            return weight,1.0

def one_state_run(seed,n):
    rng=random.Random(seed); numerator=0.0; total_weight=0.0; positive=0
    for _ in range(n):
        weight,ret=infinite_variance_episode(rng)
        numerator+=weight*ret; total_weight+=weight
        positive+=int(weight>0)
    ordinary=numerator/n
    weighted=numerator/total_weight if total_weight else None
    return ordinary,weighted,positive

for seed in range(4):
    ordinary,weighted,positive=one_state_run(900+seed,5000)
    print('semilla',900+seed,'ordinario',round(ordinary,4),
          'ponderado',weighted,'episodios compatibles',positive)
for max_steps in (1,2,5,10):
    # Segundo momento parcial exacto, NO varianza estimada con muestra finita.
    partial=.2*sum(1.8**j for j in range(max_steps))
    print('Longitudes hasta',max_steps,'segundo momento parcial',round(partial,4))

The nonzero contribution of a trajectory of length n≥1 has probability 0,1·0,5ⁿ·0,9ⁿ⁻¹ and weight 2ⁿ. Its mean sums to 1, but its second moment is 0,2 Σₖ≥₀ 1,8ᵏ, which diverges. Its first absolute moment is finite: with independent episodes the ordinary mean still converges almost surely, although variance is infinite and observed convergence can be very irregular. Here the weighted estimator is 1 after the first compatible trajectory and undefined before it; this is special to this example.

The second process has a linear grid of three cells and finite horizon H. From 0, each left or right action moves one cell with reflection at endpoints. Each arrival at cell 2 gives reward 1; the process continues until H. Behavior chooses right with probability 0,5 and the target with 0,8. Ground truth is calculated by backward induction for that same horizon. The per-decision method corrects each reward using the product of ratios up to its own action, not the future trajectory.

[ ]Ordinary, weighted and per-decision ISBrowser
import random

def grid_truth(horizon,gamma,target=.8):
    value=[0.0]*3
    for _ in range(horizon):
        nxt=[]
        for s in range(3):
            right=min(2,s+1); left=max(0,s-1)
            nxt.append(target*((right==2)+gamma*value[right])+
                       (1-target)*((left==2)+gamma*value[left]))
        value=nxt
    return value[0]

def grid_episode(rng,horizon,gamma,target=.8,behavior=.5):
    state=0; weight=1.0; ret=0.0; pdis=0.0; discount=1.0
    for _ in range(horizon):
        right=rng.random()<behavior
        ratio=target/behavior if right else (1-target)/(1-behavior)
        state=min(2,state+1) if right else max(0,state-1)
        reward=float(state==2)
        weight*=ratio
        ret+=discount*reward
        pdis+=discount*weight*reward
        discount*=gamma
    return weight,ret,pdis

for horizon in (3,6):
    truth=grid_truth(horizon,.95)
    for n in (100,400):
        errors=[[],[],[]]; undefined=0
        for seed in range(16):
            rng=random.Random(12000+100*horizon+seed)
            sample=[grid_episode(rng,horizon,.95) for _ in range(n)]
            ordinary=sum(w*g for w,g,_ in sample)/n
            weights=sum(w for w,_,_ in sample)
            weighted=sum(w*g for w,g,_ in sample)/weights if weights else None
            per_decision=sum(pd for _,_,pd in sample)/n
            errors[0].append((ordinary-truth)**2)
            if weighted is None: undefined+=1
            else: errors[1].append((weighted-truth)**2)
            errors[2].append((per_decision-truth)**2)
        mse=[sum(e)/len(e) if e else None for e in errors]
        print('H',horizon,'episodios',n,'verdad',round(truth,5),
              'MSE empírico ordinario/ponderado/por decisión',
              [round(v,5) if v is not None else None for v in mse],
              'ponderado indefinido',undefined)

The 16 replications are small and reproducible; they do not prove that one estimator dominates another generally. For a deterministic target policy, some trajectories get zero weight and the weighted denominator may vanish. In this example both policies assign positive probability to both actions, so all finite trajectories have positive weight.

Exercises

ProofUnbiasedness without finite variance
Prove: Prove unbiasedness of ordinary importance sampling and construct an infinite-variance example.
0
Trajectories are generated independently under b; target policy π is fixed, has coverage under b and E_b[|ρG|]<∞. In the example the target always chooses return; b chooses return or terminate with probability 1/2. Return goes back to the state with probability 0,9 or terminates with reward 1 with probability 0,1; terminate ends with reward 0. γ=1. Decimal commas are used.

Step 1 of 3. Why is E_b[ρG]=E_π[G]?

ProofThe random denominator
Prove: Compare first and every visit in a process with revisits.
0
Each episode starts in A, receives reward 1 on each transition and returns to A with probability 1/2; otherwise it moves to terminal state B. γ=1. Duration L is geometric with P(L=k)=2⁻ᵏ for k≥1.

Step 1 of 3. What is the first-visit return and its expectation?

NumericAveraging returns with revisits
In the unit-reward process from the proof you observe episodes of lengths 3 and 1. What is the every-visit estimate of V(A), pooling all visits?
QuizA deterministic target policy
In off-policy MC control you traverse an episode backward with a deterministic greedy target policy. What happens on finding an action the target would not have chosen in that state?
CodeAn incremental weighted mean
Implement weighted_is_update(value,C,weight,ret). value is the previous estimate and C the sum of previous weights; weight is the new observation’s nonnegative weight and ret its return. All are finite real scalars, excluding booleans, with |value| and |ret|≤10¹⁰⁰ and 0≤C,weight≤10¹⁰⁰. Return (new_value,new_C) using new_C=C+weight and new_value=value+(weight/new_C)·(ret−value). If C=weight=0, return (value,0) unchanged: the estimate still has no positive-weight data. Reject invalid inputs with ValueError and do not mutate arguments.
def weighted_is_update(value,C,weight,ret):
  pass
Shift+Enter to run
[ ]Check the exercise returnsBrowser
returns=[3,2,1,1]
print('Primera visita:',(3+1)/2,'toda visita:',sum(returns)/len(returns))