Lesson 7 of 12 · Classic Methods
SARSA
Learn SARSA, the on-policy cousin of Q-learning: its update rule, a NumPy cliff-walking comparison, Expected SARSA and when to choose each method.
- 15 min read
- Advanced
- Reviewed
- Explain the difference between on-policy and off-policy learning
- Write the SARSA update and work it out by hand next to the Q-learning update
- Train SARSA and Q-learning on cliff walking in NumPy and explain why they learn different paths
- Describe Expected SARSA and choose between the three methods for a problem
The idea in plain words
In Q-Learning, the agent acted ε-greedily: usually the best action it knew, sometimes a random one. But its update always assumed that from the next state on it would act perfectly, because the target used the largest Q-value of the next state. It learned about one policy (the greedy one) while following another (the exploring one).
SARSA changes one thing. Its target uses the Q-value of the action the agent will really take next, random or not. So it learns how good its actual behaviour is, exploration included.
Why would that matter? Picture two hikers learning a route along the top of a cliff. Both stumble in a random direction about one step in ten. The first plans as if she will never stumble, so she walks right along the edge, the shortest route. The second plans with her stumbles in mind, so she keeps a few metres away from the edge. As long as the stumbles continue, the second hiker gets home safely more often. The first hiker is Q-learning and the second is SARSA, and this lesson shows the difference with real numbers.
The SARSA update
SARSA is a temporal-difference (TD) method, like Q-learning: after every step it nudges Q(s, a) a little towards a target built from the reward and its current estimate for the next state. The two methods differ only in the target:
TD error = target − Q(s, a)
new Q(s, a) = Q(s, a) + α × TD error
Q-learning target: r + γ × (the largest Q(s', a') over all actions a')
SARSA target: r + γ × Q(s', a'), where a' is the action the agent will really take nextThe name lists the five things each update needs: the State, the Action, the Reward, the next State and the next Action, written (s, a, r, s', a'). Because SARSA needs a' before it can update, the loop picks the next action first, uses it in the update, and then really takes it in the next step.
Here is one update worked out both ways. The current estimate Q(s, a) is 3.0, the step earns a reward of −1, and in the next state ε-greedy happens to explore and pick action 2, which is worth only 1.0:
import numpy as np
alpha, gamma = 0.5, 0.9
q_sa = 3.0 # current estimate Q(s, a)
r = -1 # reward for this step
q_next = np.array([2.0, 6.0, 1.0, 0.0]) # Q(s', a') for the 4 actions in the next state
a_next = 2 # epsilon-greedy explored and picked action 2
sarsa_target = r + gamma * q_next[a_next] # the action it will really take
q_target = r + gamma * q_next.max() # the best action
print(f"SARSA target {sarsa_target:5.2f} -> new Q(s, a) = {q_sa + alpha * (sarsa_target - q_sa):.2f}")
print(f"Q-learning target {q_target:5.2f} -> new Q(s, a) = {q_sa + alpha * (q_target - q_sa):.2f}")SARSA target -0.10 -> new Q(s, a) = 1.45 Q-learning target 4.40 -> new Q(s, a) = 3.70
The Q-learning target (4.40) assumes the agent will take the best next action, worth 6.0, so its estimate rises to 3.70. The SARSA target (−0.10) uses the action the agent really picked, worth 1.0, so its estimate drops to 1.45. Most of the time the next action is the greedy one and the two targets are identical. They differ only after an exploratory step, and the next example shows that this is exactly where the danger lies.
Cliff walking: Q-learning against SARSA
Cliff walking is a classic test problem from Sutton and Barto's textbook, Reinforcement Learning: An Introduction. The world is a grid of 4 rows and 12 columns. The agent starts at the bottom left and must reach the goal (G) at the bottom right. The 10 cells between them are a cliff (C). Every step costs −1, and a step into the cliff costs −100 and sends the agent back to the start. Both agents train for 500 episodes with α = 0.5, γ = 1 (no discount, because every step already costs) and ε = 0.1 the whole time.
The two training loops are identical except for one line: future = Q[s2][a2] for SARSA and future = Q[s2].max() for Q-learning.
import numpy as np
# ---- The cliff: 4 rows x 12 columns. Start bottom left, goal bottom right ----
ROWS, COLS = 4, 12
START, GOAL = (3, 0), (3, 11)
MOVES = [(-1, 0), (0, 1), (1, 0), (0, -1)] # up, right, down, left
ARROWS = "↑→↓←"
def step(state, action):
row = min(max(state[0] + MOVES[action][0], 0), ROWS - 1)
col = min(max(state[1] + MOVES[action][1], 0), COLS - 1)
if row == 3 and 0 < col < 11: # fell off the cliff: back to the start
return START, -100, False
return (row, col), -1, (row, col) == GOAL # every other step costs 1
def choose(Q, state, eps, rng): # epsilon-greedy
if rng.rand() < eps:
return rng.randint(4)
return int(np.argmax(Q[state]))
def train(method, episodes=500, alpha=0.5, gamma=1.0, eps=0.1, seed=0):
rng = np.random.RandomState(seed)
Q = np.zeros((ROWS, COLS, 4))
rewards, falls = [], []
for _ in range(episodes):
s, done, total, fell = START, False, 0, 0
a = choose(Q, s, eps, rng)
while not done:
s2, r, done = step(s, a)
a2 = choose(Q, s2, eps, rng) # the action it will really take next
if method == "SARSA":
future = Q[s2][a2] # SARSA: the value of that action
else:
future = Q[s2].max() # Q-learning: the value of the best action
target = r if done else r + gamma * future
Q[s][a] += alpha * (target - Q[s][a])
s, a = s2, a2 # the chosen action is carried over
total, fell = total + r, fell + (r == -100)
rewards.append(total)
falls.append(fell)
return Q, rewards, falls
def greedy_path(Q): # follow the best action from the start
grid = [["."] * COLS for _ in range(ROWS)]
grid[3][1:11] = ["C"] * 10
grid[3][11] = "G"
s, steps = START, 0
while s != GOAL and steps < 50:
a = int(np.argmax(Q[s]))
grid[s[0]][s[1]] = ARROWS[a]
s, _, _ = step(s, a)
steps += 1
return steps, "\n".join(" ".join(row) for row in grid)
for method in ["Q-learning", "SARSA"]:
Q, rewards, falls = train(method)
steps, picture = greedy_path(Q)
print(f"{method}, episodes 401-500: average reward {np.mean(rewards[400:]):.1f}, "
f"fell off {sum(falls[400:])} times")
print(f"greedy path: {steps} steps")
print(picture)
print()Q-learning, episodes 401-500: average reward -56.2, fell off 39 times greedy path: 13 steps . . . . . . . . . . . . . . . . . . . . . . . . → → → → → → → → → → → ↓ ↑ C C C C C C C C C C G SARSA, episodes 401-500: average reward -23.6, fell off 4 times greedy path: 17 steps → → → → → → → → → → ↓ . ↑ . . . . . . . . . → ↓ ↑ . . . . . . . . . . ↓ ↑ C C C C C C C C C C G
The arrows show the greedy action in each cell of the route, starting from the bottom-left corner.
- Q-learning learned the shortest route: 13 steps, right along the edge of the cliff. But it keeps exploring while it trains, and on the edge a single random step down costs −100. It fell off 39 times in the last 100 episodes and averaged −56.2 per episode.
- SARSA learned a 17-step route that climbs to the top row, as far from the cliff as possible. Its values include its own random steps, so cells next to the cliff look bad to it. It fell off only 4 times and averaged −23.6, more than twice as well while learning.
Which one is right? Both, for different questions. Switch exploration off after training and Q-learning's route scores −13 against SARSA's −17: Q-learning found the better greedy policy. Keep exploring, or act in a world where moves sometimes go wrong, and SARSA's policy does better. If ε is lowered slowly towards 0 during training, SARSA's own policy becomes greedy and it ends up with the shortest route too.
Expected SARSA
SARSA's target depends on which next action happened to be drawn, and that random draw adds noise to every update. Expected SARSA removes the noise by averaging: instead of the value of the one action it picked, it uses the average value of the next action, weighted by how likely the policy is to pick each one.
Expected SARSA target = r + γ × Σ over a' of π(a' | s') × Q(s', a')
π(a' | s') is the probability that the policy picks action a' in state s'.
For ε-greedy with 4 actions: ε/4 for every action, plus an extra 1 − ε for the greedy one.It is still on-policy, because it averages over the policy it follows. When the policy is fully greedy (ε = 0), the average is just the largest value, and Expected SARSA becomes Q-learning. The price is a little more work per step: a sum over all actions instead of one lookup.
The program below trains all three methods on the same cliff with three learning rates and reports the average reward per episode over all 500 training episodes, averaged over 3 runs:
import numpy as np
ROWS, COLS, START, GOAL = 4, 12, (3, 0), (3, 11) # the same cliff as before
MOVES = [(-1, 0), (0, 1), (1, 0), (0, -1)]
def step(state, action):
row = min(max(state[0] + MOVES[action][0], 0), ROWS - 1)
col = min(max(state[1] + MOVES[action][1], 0), COLS - 1)
if row == 3 and 0 < col < 11:
return START, -100, False
return (row, col), -1, (row, col) == GOAL
def train(method, alpha, episodes=500, gamma=1.0, eps=0.1, seed=0):
rng = np.random.RandomState(seed)
Q = np.zeros((ROWS, COLS, 4))
choose = lambda s: rng.randint(4) if rng.rand() < eps else int(np.argmax(Q[s]))
total = 0
for _ in range(episodes):
s, done = START, False
a = choose(s)
while not done:
s2, r, done = step(s, a)
a2 = choose(s2)
if method == "SARSA":
future = Q[s2][a2]
elif method == "Expected SARSA": # average over what the policy might do
probs = np.full(4, eps / 4)
probs[np.argmax(Q[s2])] += 1 - eps
future = probs @ Q[s2]
else:
future = Q[s2].max()
target = r if done else r + gamma * future
Q[s][a] += alpha * (target - Q[s][a])
s, a, total = s2, a2, total + r
return total / episodes
print("average reward per episode over 500 episodes (3 runs each)")
print(f"{'alpha':>6}{'Q-learning':>12}{'SARSA':>9}{'Expected SARSA':>16}")
for alpha in [0.1, 0.5, 1.0]:
scores = [np.mean([train(m, alpha, seed=seed) for seed in range(3)])
for m in ["Q-learning", "SARSA", "Expected SARSA"]]
print(f"{alpha:>6}{scores[0]:12.1f}{scores[1]:9.1f}{scores[2]:16.1f}")average reward per episode over 500 episodes (3 runs each) alpha Q-learning SARSA Expected SARSA 0.1 -73.1 -52.3 -50.2 0.5 -57.0 -37.0 -28.8 1.0 -52.5 -70.9 -26.3
With a small learning rate (α = 0.1) all three learn slowly, and SARSA and Expected SARSA are close. As α grows, Expected SARSA keeps improving (−26.3 at α = 1.0), while SARSA gets worse (−70.9). With α = 1 every update replaces the old estimate with the new target, so a noisy target hurts. SARSA's target swings with every random next action. Expected SARSA's target has no such randomness here, because the cliff itself is deterministic, so it can take big steps safely. Q-learning's training reward is poor at every α, because its route runs along the edge.
When to prefer which
| Situation | Good choice | Why |
|---|---|---|
| Training in a simulator, with exploration switched off afterwards | Q-learning | It learns the best greedy policy directly, and mistakes during training are free |
| Learning while acting for real, where exploratory mistakes cost something | SARSA or Expected SARSA | Their values include their own exploration, so they keep away from danger |
| The agent keeps exploring after deployment | SARSA or Expected SARSA | They learn how good the policy is as it will really be used |
| Learning from logged data or another agent's actions | Q-learning | SARSA needs the next action chosen by its own current policy |
| A sensible default for small tabular problems | Expected SARSA | Less noisy targets, larger α works, and it becomes Q-learning when ε = 0 |
Common mistakes
Practice
Work out the three targets for one step. The next state's Q-values are 4, 10, 0 and 2, and epsilon-greedy (with epsilon 0.2) explored and picked the first action. Print each target with two decimals.
import numpy as np
gamma, eps = 0.9, 0.2
r = -1 # reward for this step
q_next = np.array([4.0, 10.0, 0.0, 2.0]) # Q(s', a') for up, right, down, left
a_next = 0 # epsilon-greedy explored and picked up
# 1. SARSA: r + gamma x Q(s', a_next)
# 2. Q-learning: r + gamma x the largest Q(s', a')
# 3. Expected SARSA: r + gamma x the average of Q(s', a'), weighted by the epsilon-greedy
# probabilities: eps / 4 for every action, plus an extra 1 - eps for the best action
sarsa = 0.0
q_learning = 0.0
expected = 0.0
print(f"SARSA {sarsa:.2f}, Q-learning {q_learning:.2f}, Expected SARSA {expected:.2f}")
On cliff walking with ε = 0.1 during training, why does SARSA learn a route far from the edge while Q-learning learns the route along it?
Summary
- SARSA updates Q(s, a) towards r + γ × Q(s', a'), using the action the agent will really take next; Q-learning uses the best next action instead.
- SARSA is on-policy: it learns the value of the policy it follows, exploration included. Q-learning is off-policy: it learns the greedy policy while exploring.
- On cliff walking with ε = 0.1, Q-learning learns the shortest route along the edge but falls off often while training; SARSA learns a safer route and earns more reward while learning.
- Expected SARSA averages over the probabilities of the next action, which removes noise and lets it use larger learning rates.
- Prefer Q-learning in a simulator when exploration ends at deployment, and SARSA or Expected SARSA when mistakes during learning cost something.
Next: Solving a Grid World.
Finished reading? Tick it off to track your progress.