Run tabular Q-learning updates

Q-learning learns the value of each (state, action) by bootstrapping from the best next action:

Q[s, a] += alpha * (r + gamma * max_a' Q[s', a'] - Q[s, a])

and the target is just r when the transition ends the episode.

Write q_learning(Q, transitions, alpha, gamma) where Q is a (states, actions) array and transitions is a list of (s, a, r, s_next, done). Apply the updates in order on a copy of Q and return it.

Signaturedef q_learning(Q, transitions, alpha, gamma)

Understand the idea

Q-learning learns how good each action is in each state. After seeing a transition, it moves Q[s, a] a little toward a target: the reward plus the discounted value of the best action in the next state. It uses the best next action even if the agent did something else, which makes it off-policy. If the transition ends the episode, there is no future, so the target is just the reward. Worked example: 2 states, 2 actions, Q all zeros, alpha 0.5, gamma 0.9. Transition (0, 1, r = 1, s' = 1, not done): target = 1 + 0.9 x max(Q[1]) = 1, so Q[0, 1] = 0 + 0.5 x (1 - 0) = 0.5. Next (1, 0, r = 2, s' = 0, not done): target = 2 + 0.9 x 0.5 = 2.45, so Q[1, 0] = 0.5 x 2.45 = 1.225. Rule: Q[s, a] += alpha (target - Q[s, a]), target = r if done else r + gamma max Q[s']. Apply in order on a copy. Q-learning is the base of DQN game-playing agents.

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

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

  • Sample 1: four updatesq_learning(_Q, _tr, 0.5, 0.9)
  • Sample 2: terminal ignores next stateq_learning([[0.0], [100.0]], [(0, 0, 1.0, 1, True)], 1.0, 0.9)