Search

Search papers and lessons

Q-Learning

Level 3 · 12 min read

Q-learning learns the value of each state-action pair by bootstrapping from the best next action, so it finds the optimal policy even while the agent explores with a different policy.

On this page

  • Colour = topic mix
  • Probability
  • Reinforcement learning
  • Linear algebra
  • Stochastic processes
  • Discrete math
  • Sign in to see your progress

TL;DR

Q-learning is a reinforcement learning method that keeps a table of values, one for every pair of a state and an action. The value says how much total reward the agent can expect if it takes that action in that state and plays well afterwards. After each step, the agent nudges the entry for the action it just took toward the reward it got plus the best value available in the next state. Repeated over enough experience, the table converges to the best possible values, and reading off the best action in each state gives an optimal policy.

Where you'll see it: in the first generation of game-playing and robot-control agents, in teaching material on Reinforcement Learning, and as the starting point for deep Q-networks, which replace the table with a neural network.

Intuition

A table of answers to "what if?"

Imagine a restaurant guide that lists, for every table you could sit at and every dish you could order, how happy you are likely to be. You do not know those numbers at first. You learn them by eating: you sit somewhere, order something, enjoy it or not, and update your opinion of that pairing. Over many visits the scores become useful, and the best choice in any situation is simply the highest score in that row.

That is Q-learning. The score for a pair of state and action is called Q(s,a)Q(s, a), and the agent keeps one number for each such pair. It needs no model of how the world works. It does not need to know the rules of a maze or the physics of a robot arm. It only needs to see what happened after each action.

Why the best next action matters

The update does not wait for the end of an episode, and it does not use the action the agent actually took next. It uses the best action available in the next state. That is the key choice. If you stand at a junction and are deciding whether the left turn is worth it, the value of the left turn depends on how good you can do after you get there, and the best you can do there is what counts, not whatever you happen to do by accident.

Because of this, Q-learning learns about the best way to behave even while it behaves in a more cautious or random way to explore. The table tracks the optimal play, not the play the agent used to collect the data.

0.511.522.533.544.500.20.40.60.81state (cell number, goal at 5)Q(s, right)
  • optimal Q for moving right
  • learned Q for moving right
In a five-cell corridor with discount 0.9, the value of moving right is 0.9 raised to the number of steps left before the goal. The dots are the values a Q-learning run found on its own.

The math

Setting

Q-learning sits inside the Markov decision process framework. There is a set of states S\mathcal{S}, a set of actions A\mathcal{A}, a transition rule P(s′∣s,a)P(s' \mid s, a) that gives the probability of landing in state s′s' after taking action aa in state ss, and a reward Rt+1R_{t+1} received on each step. The discount factor γ∈[0,1)\gamma \in [0, 1) says how much a reward kk steps away counts today. The agent's goal is to maximise the expected discounted return Gt=∑k=0∞γkRt+k+1G_t = \sum_{k=0}^{\infty} \gamma^k R_{t+k+1}.

The action-value function of a policy π\pi is qπ(s,a)q_\pi(s, a), the expected return after taking aa in ss and following π\pi afterwards. The best achievable action-value function is

q∗(s,a)=max⁡πqπ(s,a).q^*(s, a) = \max_{\pi} q_\pi(s, a).

Q-learning estimates q∗q^* directly. Write Q(s,a)Q(s, a) for the agent's current estimate, which starts at some arbitrary value, often zero.

The update rule

Definition: Q-learning update

After the agent takes action AtA_t in state StS_t, receives reward Rt+1R_{t+1}, and arrives in state St+1S_{t+1}, it sets

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].

Here α∈(0,1]\alpha \in (0, 1] is the learning rate, which sets how far each correction moves the estimate. The bracketed term is a temporal-difference error, in the sense of Temporal-Difference Learning. Its target is

Yt=Rt+1+γmax⁡aQ(St+1,a).Y_t = R_{t+1} + \gamma \max_{a} Q(S_{t+1}, a).

The target is the reward just seen plus the discounted value of the best action in the next state. It is a sample of the Bellman optimality equation, with the current estimate standing in for q∗q^* on the right-hand side. The update moves Q(St,At)Q(S_t, A_t) a fraction α\alpha of the way toward YtY_t.

If the next state is terminal, the future term is zero, so the target is just Rt+1R_{t+1}.

Why it converges

Watkins and Dayan showed in 1992 that the table converges to q∗q^* with probability 1 (for a finite problem with bounded rewards) under two conditions. First, every state-action pair must be visited infinitely often. Second, the learning rates must satisfy ∑tαt=∞\sum_t \alpha_t = \infty and ∑tαt2<∞\sum_t \alpha_t^2 \lt \infty. These are the same stochastic approximation conditions that apply to Temporal-Difference Learning. In practice a small constant learning rate is used, which keeps tracking changes but never settles exactly.

The conditions are sufficient, not a recipe. They tell you why the method is sound, not how many episodes you need.

Off-policy learning

The target uses max⁡aQ(St+1,a)\max_a Q(S_{t+1}, a), not the action At+1A_{t+1} that the agent will actually take. The behaviour policy, the one that picks actions, can be anything that keeps exploring, such as an ε\varepsilon-greedy rule that picks a random action with probability ε\varepsilon and the greedy one otherwise. The target policy, the one the table describes, is the greedy policy that always picks the highest-valued action. Learning about one policy while following another is called off-policy learning.

The on-policy cousin is SARSA, which replaces the max with Q(St+1,At+1)Q(S_{t+1}, A_{t+1}) for the action that was really taken. The two differ only in that one line, and that line changes what gets learned in risky settings.

Worked examples

Example 1: two states by hand

Two states, ss and s′s'. From ss there is one action, which moves to s′s' with reward 0. From s′s' there is one action, which pays reward 1 and ends the episode. Use γ=0.9\gamma = 0.9 and α=0.5\alpha = 0.5, and start with every QQ equal to 0.

Example
Three episodes

Episode 1, step 1 (at ss). The reward is 0 and the next state is s′s'. The target is 0+0.9×max⁡aQ(s′,a)=0.9×0=00 + 0.9 \times \max_a Q(s', a) = 0.9 \times 0 = 0. The update is Q(s,go)=0+0.5×(0−0)=0Q(s, \text{go}) = 0 + 0.5 \times (0 - 0) = 0.

Episode 1, step 2 (at s′s'). The reward is 1 and the episode ends, so the target is 1. The update is Q(s′,go)=0+0.5×(1−0)=0.5Q(s', \text{go}) = 0 + 0.5 \times (1 - 0) = 0.5.

Episode 2, step 1 (at ss). The target is 0+0.9×0.5=0.450 + 0.9 \times 0.5 = 0.45. The update is Q(s,go)=0+0.5×(0.45−0)=0.225Q(s, \text{go}) = 0 + 0.5 \times (0.45 - 0) = 0.225.

Episode 2, step 2 (at s′s'). The target is 1. The update is Q(s′,go)=0.5+0.5×(1−0.5)=0.75Q(s', \text{go}) = 0.5 + 0.5 \times (1 - 0.5) = 0.75.

Episode 3, step 1 (at ss). The target is 0.9×0.75=0.6750.9 \times 0.75 = 0.675. The update is Q(s,go)=0.225+0.5×(0.675−0.225)=0.45Q(s, \text{go}) = 0.225 + 0.5 \times (0.675 - 0.225) = 0.45.

Episode 3, step 2 (at s′s'). The update is Q(s′,go)=0.75+0.5×(1−0.75)=0.875Q(s', \text{go}) = 0.75 + 0.5 \times (1 - 0.75) = 0.875.

Interpretation: the value of s′s' climbs toward its true value of 1. The value of ss lags behind, because it is only updated from s′s', and it reaches the correct answer 0.90.9 once s′s' is accurate. Information about the reward spreads backwards one state per visit.

Example 2: a five-cell corridor

Example
Learning the corridor from experience

A robot sits in a corridor of five cells, numbered 1 to 5. Cell 5 is the goal, and entering it pays reward 1 and ends the episode. Every other step pays 0. The robot can move left or right. At the wall in cell 1 it stays put. The true optimal values, from solving the Bellman equation exactly, are q∗(s,right)=0.94−sq^*(s, \text{right}) = 0.9^{4-s} for s=1,…,4s = 1, \dots, 4, which gives 0.729, 0.81, 0.9 and 1.0, and q∗(s,left)q^*(s, \text{left}) equal to 0.656, 0.656, 0.729 and 0.81 for s=1,…,4s = 1, \dots, 4.

Here is a Q-learning run that starts with an all-zero table, uses γ=0.9\gamma = 0.9, α=0.1\alpha = 0.1, and an ε\varepsilon-greedy behaviour policy with ε=0.1\varepsilon = 0.1:

import random
 
GOAL, GAMMA, ALPHA, EPS = 5, 0.9, 0.1, 0.1
ACTIONS = [-1, +1]  # left, right
random.seed(0)
Q = {(s, a): 0.0 for s in range(1, GOAL) for a in ACTIONS}
 
def step(s, a):
    s2 = min(max(s + a, 1), GOAL)  # walls at 1 and at the goal
    r = 1.0 if s2 == GOAL else 0.0
    return s2, r
 
def choose(s):
    if random.random() < EPS:
        return random.choice(ACTIONS)
    best = max(Q[(s, a)] for a in ACTIONS)
    return random.choice([a for a in ACTIONS if Q[(s, a)] == best])
 
for episode in range(3000):
    s = 1
    while s != GOAL:
        a = choose(s)
        s2, r = step(s, a)
        future = 0.0 if s2 == GOAL else max(Q[(s2, b)] for b in ACTIONS)
        Q[(s, a)] += ALPHA * (r + GAMMA * future - Q[(s, a)])
        s = s2
 
for s in range(1, GOAL):
    print(s, "left", round(Q[(s, -1)], 3), "right", round(Q[(s, +1)], 3))

Output:

1 left 0.656 right 0.729
2 left 0.656 right 0.81
3 left 0.729 right 0.9
4 left 0.81 right 1.0

The learned table matches the optimal values to three decimals. Read the best action in each cell and the robot walks right all the way to the goal. Note that 500 episodes were not enough: after that many, the left-moving entries were still around 0.70 for cell 4, instead of 0.81. The table needs more visits to the cells far from the goal before its left-hand entries settle. This is typical: values far from the reward take longest to converge.

Tradeoffs and failure modes

Q-learning is simple, model-free and provably convergent in the tabular case. Those are good reasons to reach for it, but it has limits.

SituationWhat goes wrongBetter choice
Millions or billions of states, such as raw pixelsThe table does not fit in memory, and most entries are never visitedA function approximator, such as a [[deep-q-network
Continuous actions, such as joint torquesThe max over actions is hard to computeActor-critic or Policy Gradient methods
Risky environments, such as a cliff edgeThe greedy target ignores the dangers of the exploring policy during learningSARSA, which learns the values of the policy being followed
Noisy rewards with many actionsThe max of noisy estimates is biased upward, so values look better than they areDouble Q-learning, which keeps two tables and uses one to pick and the other to evaluate
Learning from a fixed log of past dataActions the log never tried have no estimatesOffline methods that constrain the policy to stay near the data

The max overestimation is the subtle one. Each entry is a noisy estimate, and taking the max of noisy numbers tends to pick the lucky ones. The error does not go away with more data alone. In practice, most deep RL systems use replay buffers such as Experience Replay and target networks to keep training stable, but those are extensions to the basic idea, not part of it.

In Sutton and Barto's cliff-walking gridworld, Q-learning learns the shortest path, which runs along the cliff edge. Its exploring behaviour sometimes falls off, so its average reward during training is poor. SARSA learns a longer path that keeps away from the edge, and does better while learning. Neither is wrong. They are answering different questions.

History

Chris Watkins introduced Q-learning in his 1989 PhD thesis, Learning from Delayed Rewards, at Cambridge. He was looking for a way to learn optimal behaviour without a model of the environment, which was the gap in the dynamic programming methods of the time. Peter Dayan and Watkins gave the convergence proof in a 1992 paper.

For about two decades Q-learning was known mainly as a clean theoretical method that worked on small problems. It caught on widely after Mnih and colleagues used a deep Q-network to play Atari games from raw screen pixels in 2013, and then reached human-level play across dozens of games in 2015. Those systems kept Q-learning's update rule and replaced the table with a neural network, which made it practical for large state spaces.

Check yourself

QuestionIn the update, why does the target use the max over next actions, rather than the action the agent actually takes next?Show answer

Because the goal is to estimate the best achievable value, q∗q^*, not the value of the agent's current behaviour. Using the max makes the target describe greedy play in the next state, which is what the Bellman optimality equation requires. The agent can then explore with any policy and still learn the optimal values. SARSA uses the action actually taken, so it learns the values of the behaviour it follows.

QuestionA Q-learning agent has Q(s,a)=2Q(s, a) = 2. It takes action aa, receives reward R=1R = 1, and lands in s′s', where the largest QQ value is 4. Use α=0.2\alpha = 0.2 and γ=0.5\gamma = 0.5. What is the new value of Q(s,a)Q(s, a)?Show answer

The target is R+γmax⁡bQ(s′,b)=1+0.5×4=3R + \gamma \max_b Q(s', b) = 1 + 0.5 \times 4 = 3. The update is Q(s,a)←2+0.2×(3−2)=2.2Q(s, a) \leftarrow 2 + 0.2 \times (3 - 2) = 2.2. The estimate moves a fifth of the way toward the target.

QuestionWhy can Q-learning still find the optimal policy when the agent explores randomly 10 percent of the time?Show answer

Because the update does not depend on which action was taken in the next state. The target always uses the best value there, so the table is pushed toward q∗q^* no matter what the exploring policy did. The exploration only matters for coverage: every state-action pair must keep being visited for the convergence conditions to hold, and an ε\varepsilon-greedy rule with ε>0\varepsilon \gt 0 guarantees that.

QuestionA robot arm has six joints, and each joint can take 100 discrete positions. Why is a plain Q-learning table impractical for it, and what would you use instead?Show answer

The number of joint configurations is 1006=1012100^6 = 10^{12}, and the table needs one entry per configuration and action. That is far too many to store, and most entries would never be visited. A function approximator, such as a neural network that takes the joint state as input and outputs one value per action, generalises across similar configurations. Alternatively, a policy-gradient method can learn a policy directly, without a value for every entry.

Sources