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 , 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.
- optimal Q for moving right
- learned Q for moving right
The math
Setting
Q-learning sits inside the Markov decision process framework. There is a set of states , a set of actions , a transition rule that gives the probability of landing in state after taking action in state , and a reward received on each step. The discount factor says how much a reward steps away counts today. The agent's goal is to maximise the expected discounted return .
The action-value function of a policy is , the expected return after taking in and following afterwards. The best achievable action-value function is
Q-learning estimates directly. Write for the agent's current estimate, which starts at some arbitrary value, often zero.
The update rule
After the agent takes action in state , receives reward , and arrives in state , it sets
Here 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
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 on the right-hand side. The update moves a fraction of the way toward .
If the next state is terminal, the future term is zero, so the target is just .
Why it converges
Watkins and Dayan showed in 1992 that the table converges to 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 and . 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 , not the action that the agent will actually take. The behaviour policy, the one that picks actions, can be anything that keeps exploring, such as an -greedy rule that picks a random action with probability 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 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, and . From there is one action, which moves to with reward 0. From there is one action, which pays reward 1 and ends the episode. Use and , and start with every equal to 0.
Episode 1, step 1 (at ). The reward is 0 and the next state is . The target is . The update is .
Episode 1, step 2 (at ). The reward is 1 and the episode ends, so the target is 1. The update is .
Episode 2, step 1 (at ). The target is . The update is .
Episode 2, step 2 (at ). The target is 1. The update is .
Episode 3, step 1 (at ). The target is . The update is .
Episode 3, step 2 (at ). The update is .
Interpretation: the value of climbs toward its true value of 1. The value of lags behind, because it is only updated from , and it reaches the correct answer once is accurate. Information about the reward spreads backwards one state per visit.
Example 2: a five-cell corridor
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 for , which gives 0.729, 0.81, 0.9 and 1.0, and equal to 0.656, 0.656, 0.729 and 0.81 for .
Here is a Q-learning run that starts with an all-zero table, uses , , and an -greedy behaviour policy with :
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.
| Situation | What goes wrong | Better choice |
|---|---|---|
| Millions or billions of states, such as raw pixels | The table does not fit in memory, and most entries are never visited | A function approximator, such as a [[deep-q-network |
| Continuous actions, such as joint torques | The max over actions is hard to compute | Actor-critic or Policy Gradient methods |
| Risky environments, such as a cliff edge | The greedy target ignores the dangers of the exploring policy during learning | SARSA, which learns the values of the policy being followed |
| Noisy rewards with many actions | The max of noisy estimates is biased upward, so values look better than they are | Double Q-learning, which keeps two tables and uses one to pick and the other to evaluate |
| Learning from a fixed log of past data | Actions the log never tried have no estimates | Offline 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, , 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 . It takes action , receives reward , and lands in , where the largest value is 4. Use and . What is the new value of ?Show answer
The target is . The update is . 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 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 -greedy rule with 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 , 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
- Sutton and Barto, Reinforcement Learning: An Introduction, 2nd ed., Section 6.5 (Q-learning) and Example 6.6 (cliff walking). incompleteideas.net
- Q-learning, Wikipedia. en.wikipedia.org/wiki/Q-learning
- Mnih et al., Playing Atari with Deep Reinforcement Learning, 2013. arxiv.org/abs/1312.5602