Temporal-difference control: SARSA, Q-learning and maximization bias
Apply temporal-difference control with SARSA, Q-learning, Expected SARSA, and double Q-learning, and compare their behavior and convergence assumptions.
After this lesson you can
- Implement tabular SARSA, Expected SARSA, Q-learning, and double Q-learning.
- Explain on-policy and off-policy behavior using cliff walking.
- State Q-learning convergence assumptions and their connection to Robbins–Monro.
- Derive maximization bias with Jensen’s inequality and analyze double estimation.
- Evaluate tabular agents in Gymnasium against value iteration.
Before you start
Learning to choose without knowing the map
An agent must cross a grid to reach a goal. Every step has a cost, and some cells are dangerous. It does not know the transitions, but after acting it observes the reward and its new position. The previous lesson updated state values for a fixed policy. Now we estimate action values and use those estimates to decide.
Write for the estimated value of taking in and continuing under the relevant policy. An -greedy policy chooses a uniformly random action with probability and otherwise chooses a greedy action. A policy must also specify how it breaks ties among maxima. Alternating approximate evaluation and improvement is a form of generalized policy iteration. While and behavior change, do not assume each update already evaluates a stationary policy exactly.
SARSA: learning from the action actually taken
In SARSA, the next action is chosen using the behavior policy and appears in the target:
The letters name the sequence state, action, reward, state, action. It is on-policy when that behavior policy is also the policy being evaluated and improved. With fixed , the target includes future exploratory actions. It is generally different from the value of greedy behavior without exploration. If the transition truly terminates, the target is the immediate reward. If an external time limit truncates an episode of a continuing task, use the continuation estimate for the final state before resetting.
The -step extension sums the next observed rewards and, if termination has not yet occurred, adds . SARSA(λ) can distribute TD error across visited pairs using traces that decay with . The traces reset each episode. As in TD(λ) prediction, the conventional online algorithm and a forward view with frozen values are not identical step by step.
Preparing the windy-gridworld transitions.
Q-learning: explore while targeting the maximum
Q-learning replaces the sampled next action with the best current estimate:
Behavior can remain -greedy. The target uses a greedy policy distinct from the behavior policy, making it off-policy. The tabular update approximates the Bellman optimality operator on the pairs supplied as data. Changing behavior does not remove the need to visit every relevant pair sufficiently often. An action never tried cannot be learned by magic. At a terminal transition, do not take the maximum of an arbitrary table: the bootstrap is zero.
Preparing the cliff-walking simulation.
In the classic example from Sutton and Barto, section 6.6, falling returns the agent to the start with a large penalty, while reaching the goal terminates the episode. With persistent exploration, a path near the edge can be good for a greedy policy and poor when random actions are occasionally taken. SARSA accounts for those actions in its targets; Q-learning targets greedy continuation. The actual result depends on seeds, training, and parameters. The figure shows its own data and does not guarantee that SARSA avoids falls or that an observed route is optimal.
For a robot that cannot suffer accidents during learning, neither algorithm alone certifies safety. Depending on the setting, constraints, supervision, simulation, or a safe behavior policy are needed. SARSA incorporating exploration in its value does not prohibit a dangerous action.
Expected SARSA: integrating over the next action
Expected SARSA averages under a known target policy :
If matches behavior, it is on-policy. A different target policy can also be used. When is greedy and assigns probability only to maxima of , the sum equals the Q-learning maximum. With equal to SARSA’s behavior policy, the sum is the conditional expectation of the target that samples the next action, holding the transition and table fixed. It removes variation from that action draw, although other sources of variation remain. Van Seijen and colleagues analyze this relationship and compare algorithms across environments.
For actions and tied maxima, a common convention divides the greedy portion uniformly: every action receives , and every maximum also receives . The probabilities must sum to one even under ties. A different tie-breaking convention is valid when the same distribution is actually used for choosing actions and forming the expectation.
Maximization bias and double estimation
Suppose are integrable estimators with means . For each , almost surely, so
This applies Jensen’s inequality to the convex maximum function. The inequality can be strict, but need not be: noiseless or perfectly correlated estimates can yield equality. If each mean is a true action value, maximizing noisy estimates has nonnegative maximization bias relative to the true maximum. This result concerns specific unbiased estimators. It does not prove that every trained Q-table has positive bias in every state.
Preparing the maximization experiment.
With two sets of estimators and , select and evaluate . If vector is independent of and , then
Under these assumptions, separating selection and evaluation removes the positive bias of selecting and measuring with the same sample, but may underestimate when a suboptimal action is chosen. Double Q-learning maintains two tables. When updating one, it selects the maximum with that table and evaluates the action with the other. The learned tables share dynamics and may be correlated, so the independent-vector proof does not establish unbiasedness or universally eliminate overestimation in the algorithm. Van Hasselt introduces the estimator and algorithm.
In example 6.7 of Sutton and Barto, choosing right from A terminates with reward zero. Left leads with reward zero to B, where any of several actions terminates with a normal reward of mean −0.1 and variance 1. With , left has expected value −0.1 and is worse than right, but maximizing noisy estimates at B can make it look attractive. The lab and interactive run their own experiments with explicit seeds and budgets.
For example, when updating table A with , the nonterminal target is ; updating B reverses their roles. Behavior can choose using the sum . Double DQN separates selection and evaluation with networks, while TD3 uses the minimum of two critics as part of its target. These are distinct extensions addressing overestimation, and they do not automatically inherit the independent-case assumptions (Double DQN, TD3).
What tabular convergence guarantees
For a finite stationary MDP, bounded rewards, and , the Bellman optimality operator is a contraction in the maximum norm. A classic formulation of Q-learning convergence requires each relevant pair to be visited infinitely often and its step sizes to satisfy, over its own visits, and . Under standard sampling assumptions and with a finite table, converges almost surely to . Contraction directs asynchronous updates toward the fixed point, and step-size conditions control noise. See Watkins and Dayan and Tsitsiklis for the arguments and their assumptions.
This guarantee does not automatically cover , constant step sizes, exploration that abandons pairs too early, or neural networks. Additional episodic results have their own assumptions. For SARSA, a policy becoming greedy is insufficient on its own: infinite visits and suitable conditions on step sizes and dynamics are also needed.
Separating training and evaluation
Optimistic initialization can encourage little-tried actions when the reward scale makes it genuinely optimistic, but with constant or changing dynamics its effect depends on the problem. An that falls too quickly can prevent reaching sparse rewards. Keeping it fixed maintains exploration but changes behavior performance. Choose and document schedules for and , and separately measure returns during training and from a frozen greedy policy on new episodes.
The environment may terminate on success or failure, or stop at an external time limit. The termination indicator determines whether the target bootstraps. Truncation requires a reset but does not imply zero future value. If the finite horizon is part of the problem, remaining time must be included in the state to represent that task correctly.
Laboratories
The following explicit models use the same transition interface for SARSA, Expected SARSA, Q-learning, and double Q-learning. In cliff walking, falling costs −100 and returns to the start without terminating. Every other step costs −1 and the goal does terminate. In the windy grid, vertical movement depends on the column before the action. An external step limit stops the simulation but does not remove the target bootstrap. These small runs check the code rather than reproduce the book’s averaged curves.
import random
class Grid:
def __init__(self,kind,limit=200):
if kind not in ('cliff','wind'): raise ValueError('Entorno desconocido')
self.kind=kind; self.limit=limit
self.height,self.width=(4,12) if kind=='cliff' else (7,10)
self.start=(3,0); self.goal=(3,11) if kind=='cliff' else (3,7)
self.wind=(0,0,0,1,1,1,2,2,1,0)
def reset(self):
self.s=self.start; self.t=0; return self.s
def step(self,a):
dr,dc=((-1,0),(0,1),(1,0),(0,-1))[a]
row,col=self.s
nr=row+dr-(self.wind[col] if self.kind=='wind' else 0)
nr=max(0,min(self.height-1,nr)); nc=max(0,min(self.width-1,col+dc))
next_state=(nr,nc); reward=-1.0; fell=False
if self.kind=='cliff' and nr==3 and 1<=nc<=10:
next_state=self.start; reward=-100.0; fell=True
self.s=next_state; self.t+=1
terminated=next_state==self.goal
truncated=self.t>=self.limit and not terminated
return next_state,reward,terminated,truncated,fell
def qrow(table,state):
if state not in table: table[state]=[0.0]*4
return table[state]
def choose(values,epsilon,rng):
if rng.random()<epsilon: return rng.randrange(len(values))
top=max(values); best=[i for i,v in enumerate(values) if v==top]
return rng.choice(best)
def train_grid(kind,method,seed,episodes=400,alpha=.5,epsilon=.1,gamma=1.0):
rng=random.Random(seed); env=Grid(kind); Q={}; Q2={}; returns=[]; falls=0; cut=0
def values(state):
q=qrow(Q,state)
return [x+y for x,y in zip(q,qrow(Q2,state))] if method=='double' else q
for _ in range(episodes):
state=env.reset(); action=choose(values(state),epsilon,rng); total=0.0
while True:
nxt,reward,terminated,truncated,fell=env.step(action)
total+=reward; falls+=int(fell)
next_action=choose(values(nxt),epsilon,rng) if not terminated else None
if method=='double':
first,second=(Q,Q2) if rng.random()<.5 else (Q2,Q)
current=qrow(first,state); fnext=qrow(first,nxt); snext=qrow(second,nxt)
target=reward
if not terminated:
best=choose(fnext,0,rng); target+=gamma*snext[best]
else:
current=qrow(Q,state); future=qrow(Q,nxt); target=reward
if not terminated:
if method=='sarsa': target+=gamma*future[next_action]
elif method=='q': target+=gamma*max(future)
elif method=='expected':
target+=gamma*((1-epsilon)*max(future)+epsilon*sum(future)/len(future))
else: raise ValueError('Método desconocido')
current[action]+=alpha*(target-current[action])
if terminated or truncated:
cut+=int(truncated); break
state,action=nxt,next_action
returns.append(total)
# Evaluación voraz separada y con generador independiente; no modifica tablas.
ev=random.Random(seed+10000); evaluation=[]; eval_cut=0
for _ in range(20):
state=env.reset(); total=0
while True:
if method=='double':
q=[x+y for x,y in zip(Q.get(state,[0.]*4),Q2.get(state,[0.]*4))]
else: q=Q.get(state,[0.]*4)
action=choose(q,0,ev)
state,reward,term,trunc,_=env.step(action); total+=reward
if term or trunc:
eval_cut+=int(trunc); evaluation.append(total); break
return sum(returns)/len(returns),falls,cut,sum(evaluation)/len(evaluation),eval_cut
for kind in ('cliff','wind'):
for method in ('sarsa','expected','q','double'):
train,falls,cuts,evaluation,eval_cuts=train_grid(kind,method,410)
print(kind,method,'retorno train',round(train,2),'caídas',falls,
'cortes train',cuts,'retorno voraz',round(evaluation,2),'cortes eval',eval_cuts)The evaluation policy uses no ε exploration; greedy ties are randomly resolved using an independent seed. Q-learning uses the maximum, Expected SARSA the expectation under the ε-greedy distribution, and SARSA the next action actually chosen. Double Q selects with one table and evaluates with the other. A truncated episode may indicate that the goal was not reached and its return must not be confused with that of a completed episode.
In the next MDP, moving right from A terminates with reward zero. Moving left reaches B with reward zero, and any of ten actions there terminates with a normally distributed reward of mean −0.1 and standard deviation 1. The true left value is therefore −0.1 and the right value is 0. We compare how often left is chosen during training, without assuming that a finite sample exactly reproduces a published curve.
import random
def pick(values,epsilon,rng):
if rng.random()<epsilon: return rng.randrange(len(values))
maximum=max(values)
return rng.choice([a for a,v in enumerate(values) if v==maximum])
def maximization_run(method,seed,episodes=120,alpha=.1,epsilon=.1):
rng=random.Random(seed); qa=[[0.0]*2,[0.0]*10]; qb=[[0.0]*2,[0.0]*10]
left=0
for _ in range(episodes):
values=[a+b for a,b in zip(qa[0],qb[0])] if method=='double' else qa[0]
action=pick(values,epsilon,rng); left+=int(action==0)
if action==0:
if method=='q':
qa[0][0]+=alpha*(max(qa[1])-qa[0][0])
second=pick(qa[1],epsilon,rng)
qa[1][second]+=alpha*(rng.gauss(-.1,1)-qa[1][second])
else:
first,other=(qa,qb) if rng.random()<.5 else (qb,qa)
choice=pick(first[1],0,rng)
first[0][0]+=alpha*(other[1][choice]-first[0][0])
selected=pick([a+b for a,b in zip(qa[1],qb[1])],epsilon,rng)
first,other=(qa,qb) if rng.random()<.5 else (qb,qa)
first[1][selected]+=alpha*(rng.gauss(-.1,1)-first[1][selected])
else:
first=qa if method=='q' or rng.random()<.5 else qb
first[0][1]+=alpha*(0-first[0][1])
return left/episodes
for method in ('q','double'):
fractions=[maximization_run(method,710+i) for i in range(24)]
print(method,'fracción media de izquierda',round(sum(fractions)/len(fractions),4),
'mínimo',round(min(fractions),4),'máximo',round(max(fractions),4))For the classic selection-bias interpretation of double Q, the evaluating estimator must not share the error used to select. The practical update alternates tables trained on shared data. Do not assume perfect independence or the absence of all bias in a particular run.
The following local lab needs numpy and gymnasium. To reproduce Taxi-v3 exactly, install python -m pip install numpy gymnasium==1.2.3 in an isolated environment. If the installation registers Taxi-v4 but not v3, the code uses v4 and reports the identifier. These are different versions and their results must not be labeled as v3. The Gymnasium 1.2.3 registry includes Taxi-v3; the current documentation explains version changes. By default, two learning rates and two exploration levels are compared with 20 seeds per environment. For a short check use ORYON_QUICK=1. This reduced budget checks the complete path, not convergence. ORYON_TD_OUT selects the output JSON. Parameters and seeds are recorded to reproduce the experiment.
import gc
import json
import os
import platform
from pathlib import Path
import gymnasium as gym
import numpy as np
quick=os.environ.get('ORYON_QUICK','0')=='1'
seeds=range(2 if quick else 20)
configurations=[(.3,.1),(.3,.3),(.7,.1),(.7,.3)]
gamma=.99
def unpack_model(env):
# P expone (probabilidad, siguiente, recompensa, terminated).
model=env.unwrapped.P; S=env.observation_space.n; A=env.action_space.n
width=max(len(model[s][a]) for s in range(S) for a in range(A))
prob=np.zeros((S,A,width)); nxt=np.zeros((S,A,width),dtype=int)
reward=np.zeros((S,A,width)); terminal=np.zeros((S,A,width),dtype=bool)
for s in range(S):
for a in range(A):
for j,(p,ns,r,done) in enumerate(model[s][a]):
prob[s,a,j]=p; nxt[s,a,j]=ns; reward[s,a,j]=r; terminal[s,a,j]=done
return prob,nxt,reward,terminal
def optimal_model(env,gamma,tol=1e-9):
prob,nxt,reward,terminal=unpack_model(env)
V=np.zeros(env.observation_space.n)
for iteration in range(1,20001):
Q=np.sum(prob*(reward+gamma*(~terminal)*V[nxt]),axis=2)
new=Q.max(axis=1)
if np.max(abs(new-V))<=tol:
V=new; break
V=new
else: raise ArithmeticError('Value iteration no convergió')
Q=np.sum(prob*(reward+gamma*(~terminal)*V[nxt]),axis=2)
residual=float(np.max(abs(Q.max(axis=1)-V)))
return V,np.argmax(Q,axis=1),iteration,residual
def evaluate(env,policy,seed,episodes):
returns=[]; cuts=0
for i in range(episodes):
state,_=env.reset(seed=seed+i); total=0.0; factor=1.0
while True:
state,reward,terminated,truncated,_=env.step(int(policy[state]))
total+=factor*reward; factor*=gamma
if terminated or truncated:
cuts+=int(truncated and not terminated); break
returns.append(total)
return float(np.mean(returns)),cuts
def train(env,seed,episodes,alpha,epsilon):
rng=np.random.default_rng(seed)
Q=np.zeros((env.observation_space.n,env.action_space.n)); cuts=0
for episode in range(episodes):
state,_=env.reset(seed=seed*100000+episode)
while True:
if rng.random()<epsilon: action=int(rng.integers(Q.shape[1]))
else:
best=np.flatnonzero(Q[state]==Q[state].max())
action=int(rng.choice(best))
nxt,reward,terminated,truncated,_=env.step(action)
target=reward if terminated else reward+gamma*Q[nxt].max()
Q[state,action]+=alpha*(target-Q[state,action])
if terminated or truncated:
cuts+=int(truncated and not terminated); break
state=nxt
return Q,cuts
report={'quick':quick,'gamma':gamma,'seeds':list(seeds),'configurations':configurations,
'python':platform.python_version(),'numpy':np.__version__,'gymnasium':gym.__version__,
'protocol':'Referencia exacta sin TimeLimit; retornos medidos con TimeLimit y descuento.',
'environments':{}}
taxi_id='Taxi-v3' if 'Taxi-v3' in gym.registry else 'Taxi-v4'
for name,full_episodes in [('FrozenLake-v1',4000),(taxi_id,8000)]:
env=gym.make(name); V,optimal,iterations,residual=optimal_model(env,gamma)
initial=np.asarray(env.unwrapped.initial_state_distrib,dtype=float)
eval_n=10 if quick else 40
benchmark,reference_cuts=evaluate(env,optimal,50000,eval_n)
results=[]
for alpha,epsilon in configurations:
for seed in seeds:
episodes=80 if quick else full_episodes
Q,train_cuts=train(env,seed,episodes,alpha,epsilon)
greedy=np.argmax(Q,axis=1)
score,eval_cuts=evaluate(env,greedy,50000,eval_n)
results.append({'seed':seed,'alpha':alpha,'epsilon':epsilon,'episodes':episodes,
'discounted_eval_return':score,'train_truncations':train_cuts,
'eval_truncations':eval_cuts})
report['environments'][name]={'optimal_value_unwrapped':float(initial@V),
'optimal_greedy_return_time_limited':benchmark,'reference_eval_truncations':reference_cuts,
'vi_iterations':iterations,'vi_residual':residual,'eval_episodes':eval_n,'runs':results}
print(name,'referencia exacta sin TimeLimit',round(float(initial@V),5),
'referencia simulada con TimeLimit',round(benchmark,5),'residuo VI',residual)
for alpha,epsilon in configurations:
runs=[r for r in results if r['alpha']==alpha and r['epsilon']==epsilon]
scores=[r['discounted_eval_return'] for r in runs]
print('alpha',alpha,'epsilon',epsilon,'media semillas',round(float(np.mean(scores)),5),
'desviación entre semillas',round(float(np.std(scores)),5),
'cortes eval',sum(r['eval_truncations'] for r in runs))
env.close()
del V,Q,optimal,greedy
gc.collect()
destination=Path(os.environ.get('ORYON_TD_OUT','oryon-l11-results.json'))
destination.parent.mkdir(parents=True,exist_ok=True)
destination.write_text(json.dumps(report,indent=2,ensure_ascii=False),encoding='utf-8')
print('Informe:',destination)npm run lab and open the connection link.The env.unwrapped.P model does not include the external TimeLimit limit, so its exact optimal value and the evaluation return under a limit are distinct quantities. A training episode stops on terminated or truncated, but only true termination removes the bootstrap. Evaluation uses an ε-free greedy policy with separate environment seeds and the same seeds across configurations. A small sweep with constant ε and α does not establish Q-learning’s asymptotic convergence conditions.
Exercises
Step 1 of 3. Which inequality does the maximum estimate from one sample satisfy?
def double_q_learning(env, episodes, alpha, gamma, eps, seed=0):
pass
alpha,gamma=.5,.9
transitions=[('A',0,1,'B',0),('B',0,-1,'C',1),('C',1,2,None,None)]
results={}
for method in ('sarsa','q'):
table={'A':[1.,2.],'B':[2.,3.],'C':[4.,1.]}
for state,action,reward,nxt,next_action in transitions:
continuation=0.0 if nxt is None else (table[nxt][next_action] if method=='sarsa' else max(table[nxt]))
table[state][action]+=alpha*(reward+gamma*continuation-table[state][action])
results[method]=[table['A'][0],table['B'][0],table['C'][1]]
print(method,results[method],'suma',sum(results[method]))
print('Diferencia Q menos SARSA:',sum(results['q'])-sum(results['sarsa']))