Week 07 · SARSA and Q-learning

See how a risky next action changes an on-policy update.

← Week 6 · Subject contents · Week 8 →

See how a risky next action changes an on-policy update.

Work through the problem

SARSA uses the next action actually taken: target r+γQ(s′,a′). Q-learning uses r+γ maxₐ Q(s′,a), which estimates the greedy continuation while the behaviour policy explores. The difference matters near a cliff because an exploratory move can be costly.

For next-state action values [−1,−12], immediate reward −1 and γ=0.9, an exploratory choice of action 1 produces target −11.8. Q-learning’s greedy target is −1.9. Train both on a small cliff grid and score each under the same epsilon-greedy evaluation.

Run the Python lab

import numpy as np
start, goal = (3,0),(3,7)
moves = [(-1,0),(0,1),(1,0),(0,-1)]
def episode(Q,rng,training,sarsa):
    def action(s):
        return rng.integers(4) if rng.random()<.1 else Q[s].argmax()
    s,a,total = start,action(start),0
    for _ in range(200):
        d = moves[a]
        t = (min(3,max(0,s[0]+d[0])),min(7,max(0,s[1]+d[1])))
        r = -1
        if t[0]==3 and 0<t[1]<7:
            t,r = start,-100
        b = action(t)
        if training:
            target = r if t==goal else r+(Q[t][b] if sarsa else Q[t].max())
            Q[s][a] += .25*(target-Q[s][a])
        total += r
        if t==goal:
            break
        s,a=t,b
    return total
for sarsa in [True,False]:
    table = np.zeros((4,8,4))
    rng = np.random.default_rng(10)
    for _ in range(900):
        episode(table,rng,True,sarsa)
    scores = [episode(table,rng,False,sarsa) for _ in range(200)]
    print("SARSA" if sarsa else "Q-learning",round(np.mean(scores),2))

Output from the lab

SARSA -17.73
Q-learning -34.91

Practice

  1. Would greedy-only evaluation answer the same question?

Check your reasoning

  1. It measures the learned greedy route. Epsilon-greedy evaluation includes the risk introduced by continued exploration.

← Week 6 · Subject contents · Week 8 →

Further reading · Sutton and Barto · Reinforcement Learning