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 from episodes generated following . 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 contributes the return from its first occurrence. Conditional on having reached , the Markov property and fixed policy give the same expected value . 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 . 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.
Preparing visits.
For example, consider two states, and terminal. From reward one is received and the process returns to with probability ; otherwise it terminates. With , duration is geometric and . First visit contributes and has expectation two. With one episode, every visit averages , namely , whose expectation is . For independent episodes, pooling all visits gives
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 , use ; 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 , and value ten with probability . 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 , or . 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.
Preparing the blackjack simulator.
Without a model, knowing only does not let us evaluate to compare actions. Monte Carlo control estimates 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 -soft policy assigns at least to each available action. An -greedy policy is a special case: it distributes remaining mass among greedy actions according to the chosen tie rule. Fixed 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. 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 generates data and target policy is the one we wish to evaluate. For a finite episode and a visit to at , define
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 has expectation . If evaluating with the first action forced in both distributions, the product starts at the next action.
Weighted importance sampling uses . 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.
Preparing estimates.
A finite example shows why horizon matters. If the target always chooses one action, behavior chooses it with probability in each of rounds, and terminal reward is one only if all match, the ordinary weighted return is with probability and zero otherwise. Its expectation is one and the variance of the average of independent episodes is . For it grows exponentially with . 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 each. On returning, it terminates with reward one with probability , or returns to the state with probability and zero reward. Terminating by the other action gives zero. For a successful trajectory of returns, probability under behavior is and weight is . Thus,
The ordinary estimator has infinite variance. Even so, : 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
Reward depends on actions up to , 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.
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.
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.
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.
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
Step 1 of 3. Why is E_b[ρG]=E_π[G]?
Step 1 of 3. What is the first-visit return and its expectation?
def weighted_is_update(value,C,weight,ret):
pass
returns=[3,2,1,1]
print('Primera visita:',(3+1)/2,'toda visita:',sum(returns)/len(returns))