Lesson 6 of 12 · Classic Methods
Q-Learning
Learn Q-learning step by step: temporal-difference updates, the off-policy update rule, α and ε-greedy, and a NumPy grid world with learning curves.
- 16 min read
- Advanced
- Reviewed
- Explain the temporal-difference idea: improving a guess with one real step and a better guess
- Write the Q-learning update rule, and explain why Q-learning is off-policy
- Train a tabular Q-learning agent with an ε-greedy behaviour policy in NumPy
- Read a learning curve printed as numbers
- Predict the effects of the learning rate α and the exploration rate ε
The idea in plain words
In Value Functions, value iteration solved a grid world in 7 sweeps. But it needed the model: every transition probability P and every reward R. Most agents don't have one. A robot doesn't come with the physics of its own motors written out as tables, and a game-playing agent can play a game without being able to read its rules.
Q-learning, introduced by Chris Watkins in 1989, learns from experience alone. The agent takes a step, sees the reward and the next state, and updates one entry in a table of Q-values. After enough steps, the table approaches Q*, and acting greedily on it is optimal. It's the most famous RL algorithm, and with a neural network in place of the table it becomes the Deep Q-Network that learned to play Atari games.
The temporal-difference idea
You leave work expecting a 30-minute drive home. Ten minutes in, you hit a traffic jam, and the sat-nav now says 25 more minutes. You don't need to arrive to know your first guess was too optimistic: 10 minutes driven plus 25 to go makes 35, a better guess for the whole trip, built from one real stretch of road and a newer estimate. Temporal-difference (TD) learning works the same way. After every step, it moves the old estimate towards the reward just received plus the discounted estimate from the next state:
target = r + γ × V(s′) one real step, plus the current guess from where it led
TD error = target − V(s) the surprise: how far off the old guess was
V(s) ← V(s) + α × TD error move a fraction α of the way towards the targetThe simulations in Markov Decision Processes waited until the end of each run to see the whole return. TD learning updates after every step, using its own estimates of later states, which is called bootstrapping, so it can learn in the middle of an episode, and in tasks that never end. The update has the same shape as the incremental average in Multi-Armed Bandits; only the target is new. Here is TD learning on the corridor from Agents, Environments and Rewards, estimating the value of every cell under the random policy:
import numpy as np
def step(state, action): # the corridor from Agents, Environments and Rewards
next_state = state + 1 if action == 1 else state - 1
if next_state == 0:
return next_state, 1, True # coin
if next_state == 6:
return next_state, 10, True # treasure
return next_state, 0, False
rng = np.random.RandomState(0)
V = np.zeros(7) # V[0] and V[6] stay 0: nothing more comes after the end
alpha, gamma = 0.01, 1.0
for episode in range(1, 2001):
state, done = 2, False
while not done:
next_state, reward, done = step(state, rng.randint(2)) # the random policy
target = reward + gamma * V[next_state] # one real step + the current guess
V[state] += alpha * (target - V[state]) # move a little towards the target
state = next_state
if episode in (10, 100, 1000, 2000):
print(f"after {episode:>4} episodes: V(1..5) = " + " ".join(f"{v:4.2f}" for v in V[1:6]))
print("true values: V(1..5) = " + " ".join(f"{1 + 1.5 * s:4.2f}" for s in range(1, 6)))after 10 episodes: V(1..5) = 0.05 0.00 0.00 0.03 0.47 after 100 episodes: V(1..5) = 0.39 0.19 0.19 0.68 2.82 after 1000 episodes: V(1..5) = 1.94 3.06 4.59 6.10 7.97 after 2000 episodes: V(1..5) = 2.45 3.91 5.48 7.11 8.56 true values: V(1..5) = 2.50 4.00 5.50 7.00 8.50
After 10 episodes, only cell 5, next to the treasure, has learned anything much. The news then flows backwards, one step at a time, until every estimate is close to the true value. Cell 2's true value, 4, is the expected return of the random policy that the first lesson worked out with probabilities. TD found it without any probabilities, just by walking around.
The Q-learning update rule
To choose actions without a model, an agent needs Q rather than V: as Value Functions showed, the greedy policy is then simply the action with the largest Q(s, a). Q-learning applies the TD idea to Q, with a target that assumes the best action is taken next:
target = r + γ × (the largest Q(s′, a′) over all actions a′) just r if s′ ends the episode
TD error = target − Q(s, a)
Q(s, a) ← Q(s, a) + α × TD error
an example: Q(s, a) = 2.0, r = −1, γ = 0.9, α = 0.1, and the Q-values in s′ are 1.0, 5.0, 3.0, 0.0
target = −1 + 0.9 × 5.0 = 3.5
TD error = 3.5 − 2.0 = 1.5
Q(s, a) ← 2.0 + 0.1 × 1.5 = 2.15This is the Bellman optimality equation for Q* from Value Functions, with the average over next states replaced by the one next state that actually happened. One sample is noisy, but because each update moves only a fraction α of the way, many updates average the samples out. The learning rate α sets that fraction: with α = 0 nothing is ever learned, and with α = 1 each update throws away the old estimate and keeps only the latest target.
Off-policy learning and the ε-greedy behaviour policy
Two policies are at work. The behaviour policy is the one the agent follows to collect experience, and it must explore: usually ε-greedy, from Exploration vs Exploitation. The target policy is the one whose values are being learned. The max in Q-learning's target means it always learns the values of the greedy policy, which become Q*, whatever the behaviour policy did next.
As long as every action keeps being tried in every state, Q-learning's estimates converge to Q*. Being off-policy has a practical benefit: Q-learning can learn from any experience, such as old episodes kept in memory, recordings of a human, or another agent's actions. Deep Q-Networks rely on this when they learn from a store of past experience. SARSA, in the next lesson, is the on-policy alternative.
Tabular Q-learning on a grid world
Here is the grid from Value Functions, with one change: a move now costs a random amount between 0 and 2, 1 on average, as if traffic varied. Value iteration's answer doesn't change, because it works with the average cost, so we know the target: the start S is worth V*(S) = 1.81. The agent knows none of this. It only sees what step returns, and keeps a table Q with 16 rows, one per cell, and 4 columns, one per action:
import numpy as np
GRID = ["...G", # the grid from Value Functions: G +10, T -10, # wall, start in S
".#.T", # a move now costs a random amount between 0 and 2 (1 on average)
"....",
"S..."]
MOVES = [(-1, 0), (0, 1), (1, 0), (0, -1)] # up, right, down, left
def step(state, action, rng):
"""The environment. The agent never looks inside: it only sees what comes back."""
row, col = divmod(state, 4)
r2, c2 = row + MOVES[action][0], col + MOVES[action][1]
if not (0 <= r2 < 4 and 0 <= c2 < 4) or GRID[r2][c2] == "#":
r2, c2 = row, col # bumped into the edge or the wall
if GRID[r2][c2] == "G":
return r2 * 4 + c2, 10.0, True
if GRID[r2][c2] == "T":
return r2 * 4 + c2, -10.0, True
return r2 * 4 + c2, -rng.uniform(0, 2), False
rng = np.random.RandomState(0)
Q = np.zeros((16, 4))
alpha, gamma, epsilon = 0.1, 0.9, 0.1
rewards, lengths = [], []
print("episodes average reward average steps V(S) = max Q(S)")
for episode in range(1, 201):
s, total = 12, 0.0 # start in S, cell 12
for t in range(100): # at most 100 moves per episode
a = rng.randint(4) if rng.rand() < epsilon else Q[s].argmax() # ε-greedy behaviour
s2, r, done = step(s, a, rng)
target = r if done else r + gamma * Q[s2].max() # the Q-learning target
Q[s, a] += alpha * (target - Q[s, a]) # move towards it
s, total = s2, total + r
if done:
break
rewards.append(total)
lengths.append(t + 1)
if episode % 25 == 0:
print(f"{episode - 24:>3}-{episode:<3} {np.mean(rewards[-25:]):13.2f} {np.mean(lengths[-25:]):14.1f} {Q[12].max():14.2f}")
print("\nlearned values, max Q in every cell:")
for row in range(4):
print(" ".join(f"{GRID[row][col]:>5}" if GRID[row][col] in "GT#" else f"{Q[row * 4 + col].max():5.1f}"
for col in range(4)))
print("greedy policy:")
for row in range(4):
print(" ".join(GRID[row][col] if GRID[row][col] in "GT#" else "↑→↓←"[Q[row * 4 + col].argmax()] for col in range(4)))episodes average reward average steps V(S) = max Q(S) 1-25 -10.06 19.0 -1.46 26-50 2.48 8.7 -1.81 51-75 3.59 6.4 -0.35 76-100 4.51 6.4 1.27 101-125 4.44 6.8 1.87 126-150 3.75 6.5 1.86 151-175 4.54 6.6 1.87 176-200 3.31 7.1 1.61 learned values, max Q in every cell: 1.7 6.3 10.0 G -0.6 # 8.0 T 0.5 4.2 6.1 1.1 1.6 2.9 3.0 -0.8 greedy policy: → → → G ↑ # ↑ T → → ↑ ← → ↑ ↑ ↑
This table is a learning curve in numbers. In the first 25 episodes, the agent wanders for 19 moves on average and often ends in the trap, so the average reward is −10.06. By episodes 51 to 75, it needs about 6.4 moves, close to the shortest route of 6, and the reward settles around 4: the perfect 5 (ten for the goal, minus five moves) less the cost of the occasional exploring move. V(S) climbs to the true 1.81 and then wobbles around it, because the costs are random and α stays at 0.1.
The learned values tell a second story. Along the route the agent uses, through the middle of the grid, they're close to value iteration's (10.0, 8.0, 6.1, 4.2). In the left column, which the agent stopped visiting once it had found its route, they're far off: −0.6 where value iteration found 4.6. Q-learning only learns accurately where it goes. Yet every arrow is an optimal move, because the values only need to rank the actions correctly.
Hyperparameter effects
How much do α and ε matter? The program trains with each setting for 300 episodes, with 10 different seeds, and reports the averages: after how many episodes the greedy policy from S first took the shortest route, the average reward over the last 100 training episodes, and how far the final V(S) is from the true 1.81:
import numpy as np
GRID = ["...G", ".#.T", "....", "S..."]
MOVES = [(-1, 0), (0, 1), (1, 0), (0, -1)] # up, right, down, left
def move(state, action):
row, col = divmod(state, 4)
r2, c2 = row + MOVES[action][0], col + MOVES[action][1]
if not (0 <= r2 < 4 and 0 <= c2 < 4) or GRID[r2][c2] == "#":
r2, c2 = row, col
return r2 * 4 + c2, GRID[r2][c2]
def step(state, action, rng):
s2, cell = move(state, action)
if cell in "GT":
return s2, (10.0 if cell == "G" else -10.0), True
return s2, -rng.uniform(0, 2), False
def greedy_moves_to_goal(Q):
"""Follow the greedy policy from S without exploring: how many moves to reach G?"""
s = 12
for n in range(1, 20):
s, cell = move(s, Q[s].argmax())
if cell in "GT":
return n if cell == "G" else None
return None
def q_learning(alpha, epsilon, seed, episodes=300, gamma=0.9):
rng = np.random.RandomState(seed)
Q, rewards, solved_at = np.zeros((16, 4)), [], None
for episode in range(1, episodes + 1):
s, total = 12, 0.0
for t in range(100):
a = rng.randint(4) if rng.rand() < epsilon else Q[s].argmax()
s2, r, done = step(s, a, rng)
Q[s, a] += alpha * ((r if done else r + gamma * Q[s2].max()) - Q[s, a])
s, total = s2, total + r
if done:
break
rewards.append(total)
if solved_at is None and greedy_moves_to_goal(Q) == 6: # 6 moves is the shortest route
solved_at = episode
return solved_at, np.mean(rewards[-100:]), abs(Q[12].max() - 1.81) # V*(S) = 1.81
print("alpha epsilon optimal after reward, last 100 episodes error in V(S)")
for alpha, epsilon in [(0.01, 0.1), (0.1, 0.1), (0.5, 0.1), (1.0, 0.1), (0.1, 0.0), (0.1, 0.3), (0.1, 1.0)]:
results = np.array([q_learning(alpha, epsilon, seed) for seed in range(10)], dtype=float)
print(f"{alpha:5.2f} {epsilon:8.1f} {np.mean(results[:, 0]):10.0f} episodes {np.mean(results[:, 1]):17.2f} "
f"{np.mean(results[:, 2]):19.2f}")alpha epsilon optimal after reward, last 100 episodes error in V(S) 0.01 0.1 52 episodes 2.22 3.45 0.10 0.1 13 episodes 4.02 0.17 0.50 0.1 7 episodes 3.84 0.39 1.00 0.1 6 episodes 3.72 0.73 0.10 0.0 18 episodes 4.97 0.13 0.10 0.3 19 episodes 0.57 0.20 0.10 1.0 22 episodes -41.87 0.18
The learning rate α trades speed against noise. With α = 0.01, learning is so slow that V(S) is still 3.45 off after 300 episodes. With α = 1, the route is found fastest, but every update replaces the estimate with a single noisy target, so V(S) ends up 0.73 off. α = 0.1 balances the two here. In a world without randomness α = 1 would be fine; noise is what makes small steps necessary, which is why many agents start with a larger α and lower it over time.
The exploration rate ε decides what training costs. More exploration means more random moves and lower rewards while learning, from 4.97 with ε = 0 down to −41.87 with ε = 1. Yet with ε = 1, a behaviour policy that is completely random, the greedy policy still became optimal: that's off-policy learning at work. ε = 0 also did well here, but only because Q starts at 0 and every move costs something, so actions the agent hasn't tried yet look better than the ones it has: the optimistic start from Exploration vs Exploitation. Where rewards are positive along the way, a purely greedy agent can lock onto the first route it finds. The discount factor γ belongs more to the problem than to the learner: it sets how far ahead the agent looks, as in Agents, Environments and Rewards.
Common mistakes
Practice
An agent has stored one episode of experience in the corridor from Agents, Environments and Rewards. Replace pass with the Q-learning update, so that the agent learns from the stored episode three times over. Watch how far back from the treasure the value has spread after each replay.
import numpy as np
# One episode in the corridor, stored as (state, action, reward, next_state, done)
# Actions: 0 = left, 1 = right. The treasure (+10) is in cell 6.
episode = [(2, 1, 0, 3, False), (3, 1, 0, 4, False), (4, 0, 0, 3, False),
(3, 1, 0, 4, False), (4, 1, 0, 5, False), (5, 1, 10, 6, True)]
Q = np.zeros((7, 2))
alpha, gamma = 0.5, 0.9
for replay in range(1, 4): # learn from the same stored episode three times
for s, a, r, s2, done in episode:
# target = r if the episode ended, else r + gamma * (the largest Q in s2)
# then move Q[s, a] a fraction alpha of the way towards the target
pass
print(f"after replay {replay}: Q(cell, right) for cells 2-5 = " + " ".join(f"{q:.2f}" for q in Q[2:6, 1]))
Why is Q-learning called an off-policy method?
Summary
- Temporal-difference learning updates an estimate after every step, towards the reward plus the discounted estimate of the next state: V(s) ← V(s) + α × (r + γ × V(s′) − V(s)).
- Q-learning uses the target r + γ × max Q(s′, a′), or just r at the end of an episode. It is model-free, and its greedy policy approaches the optimal one.
- It is off-policy: it learns the greedy policy's values while an ε-greedy behaviour policy explores, and it can learn even from random or stored experience.
- A learning curve in numbers, such as the average reward and steps per block of episodes, shows when learning has levelled off. Values are accurate only where the agent goes.
- A small α learns slowly, and a large α learns fast but noisily; a larger ε costs reward during training without changing what the greedy policy learns.
Next: SARSA.
Finished reading? Tick it off to track your progress.