Module contents
Lesson 11 of 37Core 105 min

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 Q(s,a)Q(s,a) for the estimated value of taking aa in ss and continuing under the relevant policy. An ε\varepsilon-greedy policy chooses a uniformly random action with probability ε\varepsilon 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 QQ 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 At+1A_{t+1} is chosen using the behavior policy and appears in the target:

δtSarsa=Rt+1+γQ(St+1,At+1)−Q(St,At),Q(St,At)←Q(St,At)+αδtSarsa.\delta_t^{\mathrm{Sarsa}}=R_{t+1} +\gamma Q(S_{t+1},A_{t+1})-Q(S_t,A_t),\qquad Q(S_t,A_t)\leftarrow Q(S_t,A_t)+\alpha\delta_t^{\mathrm{Sarsa}}.

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 ε\varepsilon, 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 nn-step extension sums the next observed rewards and, if termination has not yet occurred, adds γnQ(St+n,At+n)\gamma^nQ(S_{t+n},A_{t+n}). SARSA(λ) can distribute TD error across visited pairs using traces that decay with γλ\gamma\lambda. 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.

InteractiveEvery transition changes one Q entry

Preparing the windy-gridworld transitions.

Follow the agent through the windy grid and inspect the target and error of each update.

Q-learning: explore while targeting the maximum

Q-learning replaces the sampled next action with the best current estimate:

δtQ=Rt+1+γmax⁡a′Q(St+1,a′)−Q(St,At).\delta_t^{Q}=R_{t+1}+\gamma\max_{a'}Q(S_{t+1},a')-Q(S_t,A_t).

Behavior can remain ε\varepsilon-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.

InteractiveLearning beside the cliff

Preparing the cliff-walking simulation.

Compare paths and returns during exploration and during evaluation without exploration.

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 π\pi:

δtExp=Rt+1+γ∑a′π(a′∣St+1)Q(St+1,a′)−Q(St,At).\delta_t^{\mathrm{Exp}}=R_{t+1} +\gamma\sum_{a'}\pi(a'\mid S_{t+1})Q(S_{t+1},a') -Q(S_t,A_t).

If π\pi matches behavior, it is on-policy. A different target policy can also be used. When π\pi is greedy and assigns probability only to maxima of QQ, the sum equals the Q-learning maximum. With π\pi 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 mm actions and gg tied maxima, a common convention divides the greedy portion uniformly: every action receives ε/m\varepsilon/m, and every maximum also receives (1−ε)/g(1-\varepsilon)/g. 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 X1,…,XmX_1,\ldots,X_m are integrable estimators with means μi\mu_i. For each jj, max⁡iXi≥Xj\max_iX_i\geq X_j almost surely, so

E[max⁡iXi]≥max⁡iE[Xi]=max⁡iμi.\mathbb E[\max_iX_i]\geq\max_i\mathbb E[X_i]=\max_i\mu_i.

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.

InteractiveSelection and evaluation with noise

Preparing the maximization experiment.

Change the number of actions and noise level, then compare selecting and evaluating with separate samples.

With two sets of estimators XX and YY, select I=arg⁡max⁡iXiI=\arg\max_i X_i and evaluate YIY_I. If vector YY is independent of XX and E[Yi]=μi\mathbb E[Y_i]=\mu_i, then

E[YI]=∑iP(I=i)μi≤max⁡iμi.\mathbb E[Y_I]=\sum_i\Pr(I=i)\mu_i\leq\max_i\mu_i.

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 γ=1\gamma=1, 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 a∗=arg⁡max⁡aQA(s′,a)a^*=\arg\max_aQ^A(s',a), the nonterminal target is r+γQB(s′,a∗)r+\gamma Q^B(s',a^*); updating B reverses their roles. Behavior can choose using the sum QA+QBQ^A+Q^B. 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 0≤γ<10\leq\gamma<1, 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, ∑kαk(s,a)=∞\sum_k\alpha_k(s,a)=\infty and ∑kαk(s,a)2<∞\sum_k\alpha_k(s,a)^2<\infty. Under standard sampling assumptions and with a finite table, QQ converges almost surely to Q∗Q^*. 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 γ=1\gamma=1, 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 α\alpha or changing dynamics its effect depends on the problem. An ε\varepsilon that falls too quickly can prevent reaching sparse rewards. Keeping it fixed maintains exploration but changes behavior performance. Choose and document schedules for α\alpha and ε\varepsilon, 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.

[ ]SARSA, Expected SARSA, Q-learning and double QBrowser
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.

[ ]Maximization bias in two statesBrowser
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.

[ ]FrozenLake and Taxi versus value iterationLocal GPU
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)
This cell needs the local lab (PyTorch with your GPU). Start it with 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

ProofThe maximum and the double estimator
Prove: Compare the maximum of estimates with an estimator that separates selection and evaluation.
0
There are m actions with finite means μᵢ. A=(A₁,…,Aₘ) and B=(B₁,…,Bₘ) are independent vectors, and each component is integrable and unbiased: E[Aᵢ]=E[Bᵢ]=μᵢ. The index I=argmaxᵢ Aᵢ uses a fixed tie-breaking rule based on A.

Step 1 of 3. Which inequality does the maximum estimate from one sample satisfy?

NumericThe same trajectory, two targets
Initially Q(A)=(1,2), Q(B)=(2,3), Q(C)=(4,1), with actions 0 and 1; α=0.5 and γ=0.9. Observe in this order: (A,0, reward 1, B, next action 0), (B,0, reward −1, C, next action 1), and (C,1, reward 2, terminal). Update each transition immediately. What is Q(A,0)+Q(B,0)+Q(C,1) under Q-learning minus the same sum under SARSA?
QuizA robot that cannot fall
A physical robot cannot suffer any fall during learning. You only have tabular SARSA and Q-learning with ε-greedy exploration. Which decision is justified?
QuizThe next action in the target
An implementation claims to be Q-learning, but on a nonterminal transition uses r+γQ(next, next_action), where next_action is drawn from the ε-greedy behavior policy. What does it update?
CodeOne table selects, the other evaluates
Implement double_q_learning(env, episodes, alpha, gamma, eps, seed=0). env.n_states and env.n_actions are positive; reset() returns an integer state, and step(a) returns (next_state, reward, terminated, truncated). Indices are valid, rewards are finite, and every episode finishes in finite time. Initialize Q1 and Q2 to zero. For exact control of random draws, use random.Random(seed) and follow this order on each step: call rng.random() even when eps is 0 or 1; if it is less than eps choose an action using rng.randrange(env.n_actions), otherwise use rng.choice on the ascending indices maximizing Q1(s,a)+Q2(s,a), even with a single maximum. After env.step call rng.random(): update Q1 if it is less than 0.5, otherwise Q2. For a nonterminal transition use rng.choice on the sorted maximizing indices of the table being updated in the next state, even for one maximum, and evaluate that action using the other table. The target is reward + γ times that evaluation, except when terminated is true, when it is the reward alone. Stop the episode on termination or truncation, but retain the bootstrap on truncation. Return (Q1,Q2) as lists of lists. Do not draw a bootstrap action when terminated is true. episodes is a nonnegative integer and alpha, gamma, eps lie in [0,1].
def double_q_learning(env, episodes, alpha, gamma, eps, seed=0):
  pass
Shift+Enter to run
[ ]Check the three updatesBrowser
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']))