Run tabular SARSA updates over an episode

Why it matters On-policy TD updates like SARSA underlie actor-critic methods such as PPO's value targets.

SARSA is on-policy TD control: it updates Q(s, a) toward r + gamma Q(s', a') with the action actually taken next.

Write sarsa_updates(Q, episode, alpha, gamma). Q is an (S, A) array (copy it). episode is a list of (s, a, r, s_next, a_next, done). For each tuple in order, target = r if done else r + gamma * Q[s_next, a_next], then Q[s, a] += alpha * (target - Q[s, a]). Return the updated Q.

Signaturedef sarsa_updates(Q, episode, alpha, gamma)

Example

Q zeros (2, 2), episode [(0, 1, 1.0, 1, 0, True)], alpha 0.5 gives Q[0, 1] = 0.5.

Understand the idea

SARSA learns action values from what the agent actually does. Each update uses the tuple (state, action, reward, next state, next action), which gives the name. The target is the reward plus the discounted value of the next action the policy really took, not the best possible action. So SARSA learns the value of its own exploring behaviour. Worked example: Q starts at zeros, alpha 0.5, gamma 0.9. Step 1: (0, 0, r 1.0, next 1, next action 1, not done). Target = 1 + 0.9 * Q[1, 1] = 1 + 0 = 1, so Q[0, 0] = 0 + 0.5 * (1 - 0) = 0.5. Step 2: (1, 1, r 2.0, next 2, next action 0, done). Target = 2, so Q[1, 1] = 0 + 0.5 * 2 = 1.0. Rule: work on a copy of Q; for each tuple, target = r if done else r + gamma * Q[s_next, a_next]; Q[s, a] += alpha * (target - Q[s, a]). Using the max over next actions turns it into Q-learning. Used in: on-policy tabular control and classic RL teaching.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplesarsa_updates(np.zeros((2, 2)), [(0, 1, 1.0, 1, 0, True)], 0.5, 0.9)
  • Sample 2: chainsarsa_updates([[0, 0], [2, 5]], [(0, 0, 0.0, 1, 0, False), (1, 0, 1.0, 0, 1, True)], 0.5, 0.9)