◆ AI All-in-One

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
↗ Plan a path here

Read first

Value Functions and Bellman Equations

This leads to

Deep Q-Networks
The full path from zero — 7 concepts before this one
  1. What Is AI?
  2. Probability Basics
  3. How Machines Learn
  4. Supervised, Unsupervised and Reinforcement Learning
  5. Reinforcement Learning: The Basics
  6. Markov Decision Processes
  7. Value Functions and Bellman Equations
  8. 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 p(s′,r∣s,a)p(s', r \mid s, a). 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.

Q-table: one number per (state, action) ↑ ↓ ← → … … … … … s 0.31 0.12 0.20 0.50 … … … … … s′ 0.40 0.25 0.33 0.80 … … … … … orange: the entry being updated green: the best entry in the next state ss′a = →, r = 0 One step of experience: (s, →, r = 0, s′) α = 0.1 (step size), γ = 0.9 1. Target: what the step suggests r + γ · maxₐ′ Q(s′, a′) = 0 + 0.9 × 0.80 = 0.72 2. TD error: how surprised we are target − Q(s, →) = 0.72 − 0.50 = +0.22 3. Nudge the entry towards the target Q(s, →) ← 0.50 + 0.1 × 0.22 = 0.522 Repeat for every step of every episode. Good news propagates backwards from the goal, one state per visit.
Fig. 1 One Q-learning update. The agent took "right" in state s, got reward 0 and landed in s′. The best entry for s′ is 0.80, so the target is 0 + 0.9 × 0.80 = 0.72. The current estimate 0.50 is nudged 10% of the way towards it.

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 Q(s,a)Q(s, a) towards r+γmax⁡a′Q(s′,a′)r + \gamma \max_{a'} Q(s', a') 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 GtG_t, and move the estimate towards it:

V(St)←V(St)+α[Gt−V(St)]V(S_t) \leftarrow V(S_t) + \alpha \big[ G_t - V(S_t) \big]

The Greek letter α\alpha ("alpha") is the step size, a small number like 0.1. It plays the role that the learning rate η\eta plays in Gradient Descent. RL texts follow Sutton and Barto and call it α\alpha. This rule is the incremental average from Multi-Armed Bandits and Exploration again. It is unbiased, because GtG_t 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:

V(St)←V(St)+α[Rt+1+γV(St+1)⏟TD target−V(St)]V(S_t) \leftarrow V(S_t) + \alpha \big[ \underbrace{R_{t+1} + \gamma V(S_{t+1})}_{\text{TD target}} - V(S_t) \big]

The bracket is the TD error, written δt\delta_t ("delta"):

δt=Rt+1+γV(St+1)−V(St)\delta_t = R_{t+1} + \gamma V(S_{t+1}) - V(S_t)

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 AtA_t in state StS_t and observing Rt+1R_{t+1} and St+1S_{t+1}:

Q(St,At)←Q(St,At)+α[Rt+1+γmax⁡aQ(St+1,a)−Q(St,At)]Q(S_t, A_t) \leftarrow Q(S_t, A_t) + \alpha \Big[ R_{t+1} + \gamma \max_{a} Q(S_{t+1}, a) - Q(S_t, A_t) \Big]

Every symbol:

  • Q(St,At)Q(S_t, A_t): the table entry for the state you were in and the action you took.
  • Rt+1R_{t+1}: the reward you just received.
  • max⁡aQ(St+1,a)\max_a Q(S_{t+1}, a): 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.
  • γ\gamma: the discount factor.
  • α\alpha: the step size, i.e. how far to move towards the target.

If St+1S_{t+1} is terminal there is no future, so the target is just Rt+1R_{t+1}.

Worked example (the figure above). Q(s,→)=0.50Q(s, \rightarrow) = 0.50, the agent moves right, gets r=0r = 0, and lands in s′s', whose best entry is 0.80. With γ=0.9\gamma = 0.9 and α=0.1\alpha = 0.1:

  • TD target: 0+0.9×0.80=0.720 + 0.9 \times 0.80 = 0.72
  • TD error: 0.72−0.50=+0.220.72 - 0.50 = +0.22, a pleasant surprise
  • New value: 0.50+0.1×0.22=0.5220.50 + 0.1 \times 0.22 = 0.522

The full algorithm

  1. Initialise Q(s,a)=0Q(s, a) = 0 for all states and actions.
  2. For each episode, start in S0S_0. Then repeat until the episode ends:
    • Choose AtA_t with an ε-greedy policy (Multi-Armed Bandits and Exploration): a random action with probability ε\varepsilon, otherwise arg⁡max⁡aQ(St,a)\arg\max_a Q(S_t, a).
    • Take it. Observe Rt+1R_{t+1} and St+1S_{t+1}.
    • Apply the Q-learning update.
  3. When done, act greedily with respect to QQ.

Convergence. Watkins and Dayan proved in 1992 that tabular Q-learning converges to the optimal q∗q_* 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. αn=1/n\alpha_n = 1/n). In practice a small constant α\alpha works well and gets close.

Off-policy and on-policy: Q-learning versus SARSA

Notice the max⁡\max in the target. The agent behaves ε-greedily, but its update assumes that from St+1S_{t+1} 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: St,At,Rt+1,St+1,At+1S_t, A_t, R_{t+1}, S_{t+1}, A_{t+1}. It uses the action the agent actually takes next, instead of the max:

Q(St,At)←Q(St,At)+α[Rt+1+γ Q(St+1,At+1)−Q(St,At)]Q(S_t, A_t) \leftarrow Q(S_t, A_t) + \alpha \Big[ R_{t+1} + \gamma\, Q(S_{t+1}, A_{t+1}) - Q(S_t, A_t) \Big]

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.

S G the cliff step here: reward −100 and back to S every move costs −1 · ε-greedy exploration with ε = 0.1 SARSA: the safe path, 17 steps learns the value of what it actually does, exploring moves included: about −24 per episode Q-learning: the optimal path, 13 steps learns the value of the best action; its random moves sometimes fall off: about −42 per episode
Fig. 2 Cliff walking (Sutton & Barto, Example 6.6), reproduced by the second code example below. Q-learning learns the shortest path right along the cliff edge, but while it is still exploring, its random moves sometimes fall off. SARSA accounts for its own exploration and learns a safer path further from the edge.

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.

0.0 0.2 0.4 0.6 0 2,000 4,000 6,000 8,000 10,000 0.473 best possible, v*(start) 0.429 best possible while still exploring (ε = 0.1) episode average return per episode blue: Q-learning on the icy gridworld, mean of each block of 200 episodes
Fig. 3 The learning curve from the code above, averaged over blocks of 200 episodes. Around episode 3,500 the return jumps up and then hovers near the ceiling set by the agent's own exploration.

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 max⁡aQ(start,a)=0.496\max_a Q(\text{start}, a) = 0.496 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 rr. Adding γmax⁡Q\gamma \max Q 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 ε=0\varepsilon = 0 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 α\alpha 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 nn 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

  1. In the gridworld code, set eps = 0.3. Does the learning curve rise faster or slower? Where does it level off, and why?
  2. Decay exploration: eps = max(0.01, 1.0 * 0.999 ** episode). Compare the final average return and the learned policy with the run above.
  3. 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.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. Q(s, →) = 0.50. The agent moves right, gets reward 0, and the best entry in the new state is 0.80. With γ = 0.9 and α = 0.1, what is the updated Q(s, →)?

  2. Why can Q-learning learn from old data or another agent's experience, while SARSA cannot?

  3. On the cliff-walking task, a robot with noisy motors will always keep some random movement. Which algorithm's learned path is the better choice for it?

  4. After training, Q-learning estimates the start square at 0.496, above the true optimal value 0.473. What is the most likely cause?

  5. How does a Monte Carlo update differ from a TD update?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Course

Hugging Face Deep RL Course

Hugging Face · Intermediate · Free

A hands-on deep reinforcement learning course from Q-learning to PPO. You train agents in games.

Course

UCL Course on Reinforcement Learning

David Silver · 2015 · Intermediate · Free

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.

Paper

Q-learning

Christopher Watkins & Peter Dayan · 1992 · Advanced · Paid

The convergence proof for Q-learning, which Watkins introduced in his 1989 PhD thesis.

Article

A (Long) Peek into Reinforcement Learning

Lilian Weng · 2018 · Intermediate · Free

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