Level 3 In-Depth AI · Reinforcement Learning
Q-Learning
Learn how good every action is in every state purely from experience, with no model of the world, by nudging a table of estimates towards "reward plus the best value of the next state". The tabular algorithm that deep RL grew from.
- Level
- ●●●●● Intermediate
- Reading
- 14 min
- To learn it well
- 1.5 hours to read, an afternoon to practise
- Builds on
- 7 concepts →
- Quiz
- 5 questions ↓
Read first
Value Functions and Bellman EquationsThis leads to
Deep Q-NetworksThe full path from zero — 7 concepts before this one
- What Is AI?
- Probability Basics
- How Machines Learn
- Supervised, Unsupervised and Reinforcement Learning
- Reinforcement Learning: The Basics
- Markov Decision Processes
- Value Functions and Bellman Equations
- Q-Learning
Read them roughly in this order. See it on the concept map →
Why it matters
Value Functions and Bellman Equations solved the icy gridworld exactly, but it cheated. It read the rulebook: the full table of transition probabilities . A robot, a game-playing program or a trading agent almost never has that table. It can only act and see what happens.
Q-learning learns optimal behaviour from that raw experience alone. It needs no model of the environment (it is model-free), it can learn from data collected by any behaviour, even random or old, and in small problems it is guaranteed to find the optimal policy. It is the direct ancestor of DeepMind's Atari-playing Deep Q-Network, and its central idea, the temporal-difference update, runs through nearly all of modern RL, including the critics in Actor-Critic Methods and Proximal Policy Optimization.
The intuition
Suppose you drive home from work every day and keep a mental estimate of how long the trip takes. Today you leave and hit unexpected traffic on the first street. You don't wait until you get home to update your estimate. You think straight away, "I'm 10 minutes behind where I'd usually be at this corner, so today will take longer." You revise your guess using another guess: your usual estimate of the time from this corner home.
That is temporal-difference (TD) learning. Rather than waiting for the final outcome, update each estimate towards the reward you just got plus your current estimate of what comes next. The mismatch between the two is the TD error, a measure of surprise. Positive surprise means things are better than you thought, so you raise the estimate. Negative surprise means you lower it.
Q-learning applies this to action values. It keeps a table, the Q-table, with one number for every pair (state, action): "how much total discounted reward do I expect if I take this action here and act optimally afterwards?" Every time the agent takes a step, it updates one entry.
At first all entries are 0 and the agent wanders. The first time it stumbles into the goal, the entry for the last action before the goal gets a little credit. Next time it reaches that square, the credit flows one step further back. Over many episodes, value spreads backwards from the goal like water filling a riverbed, until the greedy path through the table leads straight home.
Key idea Q-learning nudges towards after every step. It learns the values of the best actions even while the agent is exploring with random ones. That is what makes it off-policy.
How it works
Two ways to learn from experience
Without a model, there are two ways to estimate the value of a state from experience.
Monte Carlo methods wait until the episode ends, compute the actual return , and move the estimate towards it:
The Greek letter ("alpha") is the step size, a small number like 0.1. It plays the role that the learning rate plays in Gradient Descent. RL texts follow Sutton and Barto and call it . This rule is the incremental average from Multi-Armed Bandits and Exploration again. It is unbiased, because is a true sample of the return, but noisy, and it has to wait for the episode to finish.
Temporal-difference methods update after a single step. They replace the unknown rest of the return with the current estimate of the next state's value:
The bracket is the TD error, written ("delta"):
This is the Bellman equation turned into an update. Instead of averaging over all possible next states with known probabilities, it uses the one next state that actually happened. Averaged over many visits, the samples follow the true probabilities, so the estimates converge to the same answer. TD learning bootstraps (it updates a guess from a guess), which adds some bias but greatly reduces noise. It also learns during the episode, and works for tasks that never end.
The Q-learning update
Q-learning, introduced by Chris Watkins in 1989, applies a TD update to the Bellman optimality equation for action values. After taking action in state and observing and :
Every symbol:
- : the table entry for the state you were in and the action you took.
- : the reward you just received.
- : the best entry in the row for the state you landed in. This is your estimate of how well you could do from there if you act optimally.
- : the discount factor.
- : the step size, i.e. how far to move towards the target.
If is terminal there is no future, so the target is just .
Worked example (the figure above). , the agent moves right, gets , and lands in , whose best entry is 0.80. With and :
- TD target:
- TD error: , a pleasant surprise
- New value:
The full algorithm
- Initialise for all states and actions.
- For each episode, start in . Then repeat until the episode ends:
- Choose with an ε-greedy policy (Multi-Armed Bandits and Exploration): a random action with probability , otherwise .
- Take it. Observe and .
- Apply the Q-learning update.
- When done, act greedily with respect to .
Convergence. Watkins and Dayan proved in 1992 that tabular Q-learning converges to the optimal provided every state–action pair keeps being tried and the step sizes shrink at a suitable rate (they must add up to infinity, while their squares add up to something finite, e.g. ). In practice a small constant works well and gets close.
Off-policy and on-policy: Q-learning versus SARSA
Notice the in the target. The agent behaves ε-greedily, but its update assumes that from it will act greedily. It learns about one policy (the greedy target policy) while following another (the exploratory behaviour policy). That is what off-policy means. It is a superpower: Q-learning can learn from old data, from demonstrations, or from another agent's experience. Deep Q-Networks relies on this to learn from a replay buffer.
The alternative is SARSA, named after the five things each update uses: . It uses the action the agent actually takes next, instead of the max:
SARSA is on-policy. It learns the value of the policy it is actually following, exploration and all.
The difference shows clearly in Sutton and Barto's cliff-walking task. The agent must walk from S to G along the edge of a cliff. Each step costs −1, and falling off costs −100 and sends it back to the start.
Q-learning finds the truly optimal path, 13 steps along the edge. But an ε-greedy agent walking there occasionally takes a random step off the cliff, so its reward while learning is worse (about −42 per episode versus −24). SARSA learns that, given its own random moves, walking along the edge is dangerous, and takes the 17-step route along the top. Which is "right" depends on whether you'll stop exploring later (then prefer Q-learning) or must keep acting with some randomness, as a real robot with noisy motors must (then SARSA's caution is valuable).
In code
Tabular Q-learning on the icy gridworld from Value Functions and Bellman Equations. The agent only calls step(). It never sees the 80/10/10 slip probabilities that value iteration used.
import random
from collections import defaultdict
WALL, GOAL, PIT, START = (1, 1), (0, 3), (1, 3), (3, 0)
MOVES = {"↑": (-1, 0), "↓": (1, 0), "←": (0, -1), "→": (0, 1)}
SIDEWAYS = {"↑": "←→", "↓": "←→", "←": "↑↓", "→": "↑↓"}
def step(s, a):
"""Icy gridworld: the agent can only sample it, not read its rules."""
x = random.random()
a = a if x < 0.8 else SIDEWAYS[a][0] if x < 0.9 else SIDEWAYS[a][1]
r, c = s[0] + MOVES[a][0], s[1] + MOVES[a][1]
if 0 <= r < 4 and 0 <= c < 4 and (r, c) != WALL:
s = (r, c)
if s == GOAL: return s, 1.0, True
if s == PIT: return s, -1.0, True
return s, 0.0, False
random.seed(0)
Q = defaultdict(float) # Q[(state, action)], starts at 0
alpha, gamma, eps = 0.1, 0.9, 0.1
greedy = lambda s: max(MOVES, key=lambda a: (Q[(s, a)], random.random())) # random tie-break
returns = []
for episode in range(1, 10001):
s, G, disc, done = START, 0.0, 1.0, False
while not done:
a = random.choice(list(MOVES)) if random.random() < eps else greedy(s)
s2, r, done = step(s, a)
target = r if done else r + gamma * max(Q[(s2, b)] for b in MOVES)
Q[(s, a)] += alpha * (target - Q[(s, a)]) # the Q-learning update
G += disc * r; disc *= gamma; s = s2
returns.append(G)
if episode % 1000 == 0 or episode in (100, 500):
avg = sum(returns[-100:]) / 100
print(f"episodes {episode-99:5d}-{episode:5d}: average return {avg:+.3f}")
print("learned max_a Q(start, a) =", round(max(Q[(START, a)] for a in MOVES), 3),
" (value iteration: 0.473)")
for r in range(4):
print(" ".join(greedy((r, c)) if (r, c) not in (WALL, GOAL, PIT) else "■" for c in range(4)))
# episodes 1- 100: average return +0.011
# episodes 401- 500: average return +0.142
# episodes 901- 1000: average return +0.203
# episodes 1901- 2000: average return +0.302
# episodes 2901- 3000: average return +0.343
# episodes 3901- 4000: average return +0.394
# episodes 4901- 5000: average return +0.424
# episodes 5901- 6000: average return +0.450
# episodes 6901- 7000: average return +0.382
# episodes 7901- 8000: average return +0.433
# episodes 8901- 9000: average return +0.397
# episodes 9901-10000: average return +0.437
# learned max_a Q(start, a) = 0.496 (value iteration: 0.473)
# → → → ■
# ↑ ■ ↑ ■
# ↑ ← ← ↓
# ↑ ← ↑ ←
Those printed numbers are the learning curve. The average return climbs from about 0 to around 0.43. It can't reach 0.473, the optimal value, while it still takes a random action 10% of the time. Even a perfect table, followed ε-greedily, earns only 0.429 from the start square.
Compare the learned policy with the optimal one in Value Functions and Bellman Equations. Along the route the agent actually travels, it matches exactly: up the left side and along the top. In two squares it rarely visits (the middle of the bottom two rows) it chose differently. Those entries were updated too few times to be accurate. Tabular learning is only as good as its coverage. Note also that the learned is above the true 0.473. That is a hint of the overestimation discussed below.
The SARSA versus Q-learning comparison on the cliff is the same loop with one line changed:
import random
ROWS, COLS = 4, 12
START, GOAL = (3, 0), (3, 11)
MOVES = [(-1, 0), (1, 0), (0, -1), (0, 1)] # up, down, left, right
def step(s, a):
r = min(max(s[0] + MOVES[a][0], 0), ROWS - 1)
c = min(max(s[1] + MOVES[a][1], 0), COLS - 1)
if r == 3 and 0 < c < 11: # stepped off the cliff
return START, -100.0, False
return (r, c), -1.0, (r, c) == GOAL
def train(method, episodes=500, alpha=0.5, gamma=1.0, eps=0.1):
Q = {((r, c), a): 0.0 for r in range(ROWS) for c in range(COLS) for a in range(4)}
def policy(s):
if random.random() < eps: return random.randrange(4)
return max(range(4), key=lambda a: (Q[(s, a)], random.random()))
totals = []
for _ in range(episodes):
s, a, total, done = START, policy(START), 0.0, False
while not done:
s2, r, done = step(s, a)
a2 = policy(s2)
if method == "sarsa": nxt = Q[(s2, a2)] # action it WILL take
else: nxt = max(Q[(s2, b)] for b in range(4)) # best action
Q[(s, a)] += alpha * (r + (0 if done else gamma * nxt) - Q[(s, a)])
s, a, total = s2, a2, total + r
totals.append(total)
return sum(totals[-100:]) / 100, Q
random.seed(0)
for method in ["sarsa", "q-learning"]:
avg, Q = train(method)
s, path = START, 0 # follow the greedy policy
while s != GOAL and path < 50:
s, _, _ = step(s, max(range(4), key=lambda a: Q[(s, a)])); path += 1
print(f"{method:10s} reward per episode while learning: {avg:6.1f} greedy path: {path} steps")
# sarsa reward per episode while learning: -24.4 greedy path: 17 steps
# q-learning reward per episode while learning: -41.5 greedy path: 13 steps
Common pitfalls
- Bootstrapping from terminal states. If the episode has ended, the target is just . Adding of a terminal state, whose entries may be non-zero because of a bug, makes values leak past the end of the episode.
- Too little exploration. With the agent repeats its first lucky route forever. With too much, it never exploits what it learns. Start high (say 1.0) and decay to 0.05–0.1.
- Step size too large or too small. With noisy rewards or transitions, a large makes values jitter. A tiny one learns painfully slowly. 0.1 is a reasonable default for tables.
- Maximization bias. Taking the max of noisy estimates is biased upwards: if all actions are truly worth 0 but the estimates are noisy, the largest estimate is likely above 0. The result is over-optimistic values, like the 0.496 above. Double Q-learning (van Hasselt, 2010) keeps two tables and lets one pick the action while the other scores it.
- State explosion. A table needs one row per state. A 10 × 10 board is fine. Raw 84 × 84 pixel images have more possible states than any table could hold. That is the problem Deep Q-Networks solves.
Watch out Combining function approximation, bootstrapping and off-policy learning, which Sutton and Barto call the "deadly triad", can make value estimates diverge to infinity. Tabular Q-learning is safe. The moment you replace the table with a neural network, you need the stabilising tricks of Deep Q-Networks.
Variations
- Expected SARSA uses the expected value of the next action under the policy instead of a sample or the max. It has lower variance, and it includes Q-learning as the special case of a greedy target policy.
- n-step methods look real rewards ahead before bootstrapping. They sit between one-step TD and Monte Carlo, and they are used in A3C, Rainbow and others.
- TD(λ) and eligibility traces blend all n-step targets with exponentially decaying weights. The same idea becomes GAE in Actor-Critic Methods.
- Deep Q-Networks (Deep Q-Networks) replace the table with a convolutional network and add experience replay and a target network.
- Dyna-Q (Model-Based RL and World Models) also learns a model from the same experience and replays imagined transitions to learn faster.
A bit of history
Arthur Samuel's checkers program (1959) already updated its evaluation of positions towards the evaluation of later positions, a precursor of TD. Richard Sutton formalised temporal-difference learning in his 1988 paper "Learning to predict by the methods of temporal differences". Chris Watkins introduced Q-learning in his 1989 Cambridge PhD thesis, Learning from Delayed Rewards, and the convergence proof with Peter Dayan followed in 1992. SARSA was introduced by Gavin Rummery and Mahesan Niranjan in 1994 under the name "modified connectionist Q-learning". The name SARSA came from Sutton. In 1992, Gerald Tesauro's TD-Gammon used TD learning with a neural network to play backgammon at close to world-champion level, the first big demonstration of what deep RL would later do at scale.
Try it
- In the gridworld code, set
eps = 0.3. Does the learning curve rise faster or slower? Where does it level off, and why?- Decay exploration:
eps = max(0.01, 1.0 * 0.999 ** episode). Compare the final average return and the learned policy with the run above.- Turn the gridworld agent into SARSA (choose the next action before updating, and use it in the target). Does it treat the squares beside the pit differently?
Hint for 1: with more exploration, the ceiling set by random moves is lower.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Reinforcement Learning: An Introduction
The foundational RL textbook by the field's founders. Free PDF.
Hugging Face Deep RL Course
A hands-on deep reinforcement learning course from Q-learning to PPO. You train agents in games.
UCL Course on Reinforcement Learning
Ten recorded lectures with slides by the lead researcher behind AlphaGo. Covers MDPs, dynamic programming, TD learning, function approximation, policy gradients and planning; follows Sutton & Barto closely.
Q-learning
The convergence proof for Q-learning, which Watkins introduced in his 1989 PhD thesis.
A (Long) Peek into Reinforcement Learning
A dense, well-organised tour of the core ideas: MDPs, Bellman equations, dynamic programming, Monte Carlo and TD methods, Q-learning, DQN and policy gradients.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/rl/q-learning.md