Overview
Keep a table with one number for each state and action: an estimate of the total reward that follows if you take that action there and act well afterwards. After every step, compare the old estimate with a fresh one made from the reward just received plus the best entry in the next state's row, and move the old estimate part of the way toward it. The fresh estimate always assumes the best next action, even when the agent in fact explores and does something else. Because of that the table learns the values of the best policy while the agent follows a different, exploratory one. This is what off-policy means. The template includes the 4 by 12 cliff-walking grid to train on.
A short history
Chris Watkins introduced Q-learning in his 1989 PhD thesis at Cambridge, Learning from Delayed Rewards, and Watkins and Peter Dayan published a convergence proof in 1992. It was the first widely used method that learns the best action values directly from experience without a model of the environment, and it learns about the best policy even while the agent explores. The Q stands for the quality of an action. DQN is this same update with a neural network in place of the table.
How it works
- Start with every table entry at
initial_q. - In state , choose an action: a random one with probability , otherwise the one with the highest entry, breaking ties at random.
- Take the action and observe the reward and next state .
- Form the target: plus times the largest entry in the row of , or just if the episode terminated.
- Move a fraction of the way toward the target.
- Continue from , and repeat over many episodes.
Watch out for
- The table learns the values of the greedy policy, not of the exploring policy the agent follows. On the cliff it learns the edge path, and then falls off during training whenever a random action is drawn there.
- The maximum over noisy estimates is biased upward, so early values are too optimistic. Double Q-learning is the standard fix.
- Every state and action must be visited many times. With too little exploration some entries never leave their starting value and the greedy policy can be wrong.
- A table has one entry per state and action, so it cannot handle large or continuous state spaces, and nothing learned in one state carries over to a similar one.
Use cases
When to use it
Small problems whose states and actions fit in a table: gridworlds, simple games, a first baseline. Use SARSA when the reward collected while still exploring matters, and DQN when the states do not fit in a table.
In industry
- Research and teaching
- The first control algorithm in most reinforcement learning courses, on grid worlds and small games where the whole table can be printed.
- Embedded control
- Small controllers with a few sensor states and a few actions, where a lookup table fits in memory and is easy to inspect.
- Operations
- Simple inventory or queue decisions with a handful of discrete states, learned in a simulator and deployed as a table.
Choosing it: what must hold
- A small number of discrete states and discrete actions, so that every pair can be visited many times.
- Enough exploration that each state and action keeps being tried.
- A step size that is small or decays, for the estimates to settle.
When to choose something else
| If | Use instead |
|---|---|
| States are images or continuous measurements | DQN |
| The risk taken while exploring matters, for example near a cliff | SARSA |
| Real steps are expensive and you can remember what happened | Dyna |
Math foundations
The Bellman optimality equation
The value of the best policy satisfies a consistency rule: the value of an action equals the expected reward plus the discounted best value of where it leads. Q-learning searches for the table that obeys it.
The TD target
One sampled version of the right-hand side, using the current table in place of . When is terminal the target is just .
The TD error
The gap between the fresh estimate and the stored one. Positive means the step went better than the table expected. The template's
updatereturns this number.The update
Move the stored value a fraction of the way toward the target. A full move would let one noisy sample overwrite everything learned before.
The epsilon-greedy behaviour policy
Mostly the best known action, sometimes a random one. This is the policy that gathers data. It does not appear in the target, which is why the method is off-policy.
Symbols
- current state and the action taken in it
- reward received for that step
- next state and a candidate action in it
- the table entry: estimated return after taking a in s and acting greedily afterwards
- the true action values of the best policy
- discount factor (1.0 by default in the template)
- step size (learning_rate)
- probability of a random action while training (epsilon)
- number of actions
- the TD target and the TD error
Worked by hand
Use the template's defaults and . First an ordinary step: , , and the best entry in the next row is . Then a step off the cliff: , , and the agent is sent to the start, whose best entry is .
The ordinary step nudges its entry up by half the error. The single fall drops the entry for stepping into the cliff from to , so that action is avoided from then on.
Visual example
Loading the example.
Try this
- Press Step a few times and read the update line: the target always uses the best entry of the next row.
- Run 100 episodes, then compare the greedy path return with the mean training return.
- Raise ε to 0.4 and train again: the learned path stays on the cliff edge while training returns get worse.
Code sample
from impl import CliffWalk, QLearning
from config import QLearningConfig
env = CliffWalk()
agent = QLearning(env.n_states, env.n_actions, QLearningConfig(episodes=500))
returns = agent.train(env) # return of every training episode
print(agent.evaluate(env)) # -13.0: the shortest path, along the cliff edgeRead the implementation (122 lines)
"""Tabular Q-learning, with a cliff-walking environment to learn on.
Q-learning keeps a table Q[state, action] and moves each entry toward
reward + gamma * max_a' Q[next_state, a']. The target uses the best next action whatever the agent
does next, so the table converges to the optimal action values while the agent explores (off-policy).
"""
from __future__ import annotations
import numpy as np
try:
from .config import QLearningConfig
except ImportError: # run from the template's own folder
from config import QLearningConfig
class CliffWalk:
"""Cliff walking (Sutton and Barto, example 6.6): a rows x cols grid, start bottom-left, goal bottom-right.
The bottom-row cells between start and goal are the cliff: stepping there gives -100 and sends the
agent back to the start. Every other step gives -1. States are integers row * cols + col.
Actions: 0 up, 1 right, 2 down, 3 left. A move into a wall leaves the agent where it is.
`step` returns (state, reward, terminated, truncated). The shortest safe path runs along the cliff
edge and has return -(cols + 1), which is -13 for the default 4 x 12 grid.
"""
n_actions = 4
_MOVES = ((-1, 0), (0, 1), (1, 0), (0, -1))
def __init__(self, rows: int = 4, cols: int = 12, max_steps: int = 500) -> None:
if rows < 2 or cols < 3:
raise ValueError("the grid needs at least 2 rows and 3 columns")
self.rows, self.cols, self.max_steps = rows, cols, max_steps
self.n_states = rows * cols
self.start = (rows - 1) * cols
self.goal = rows * cols - 1
self.state = self.start
self.t = 0
@property
def optimal_return(self) -> float:
return -float(self.cols + 1)
def is_cliff(self, state: int) -> bool:
"""True for the bottom-row cells strictly between start and goal."""
return self.start < state < self.goal
def reset(self) -> int:
self.state = self.start
self.t = 0
return self.state
def step(self, action: int):
"""Apply one action (0..3). Returns (state, reward, terminated, truncated)."""
row, col = divmod(self.state, self.cols)
d_row, d_col = self._MOVES[int(action)]
row = min(max(row + d_row, 0), self.rows - 1)
col = min(max(col + d_col, 0), self.cols - 1)
self.state = row * self.cols + col
self.t += 1
reward = -1.0
if self.is_cliff(self.state):
reward = -100.0
self.state = self.start
terminated = self.state == self.goal
truncated = not terminated and self.t >= self.max_steps
return self.state, reward, terminated, truncated
class QLearning:
"""Tabular Q-learning agent with an epsilon-greedy behaviour policy.
n_states, n_actions: size of the table. States and actions are integers starting at 0.
"""
def __init__(self, n_states: int, n_actions: int, config: QLearningConfig | None = None) -> None:
self.config = config or QLearningConfig()
self.n_states, self.n_actions = n_states, n_actions
self.q = np.full((n_states, n_actions), self.config.initial_q, dtype=float)
self.rng = np.random.default_rng(self.config.seed)
def act(self, state: int, greedy: bool = False) -> int:
"""Epsilon-greedy action for `state`. greedy=True always takes the first best action."""
if greedy:
return int(np.argmax(self.q[state]))
if self.rng.random() < self.config.epsilon:
return int(self.rng.integers(self.n_actions))
row = self.q[state]
return int(self.rng.choice(np.flatnonzero(row == row.max()))) # break ties at random
def update(self, state: int, action: int, reward: float, next_state: int, terminated: bool) -> float:
"""One Q-learning step. Returns the TD error before the update."""
cfg = self.config
target = reward if terminated else reward + cfg.gamma * self.q[next_state].max()
td_error = target - self.q[state, action]
self.q[state, action] += cfg.learning_rate * td_error
return float(td_error)
def train(self, env, episodes: int | None = None) -> list[float]:
"""Run `episodes` episodes of epsilon-greedy control. Returns the return of each episode."""
returns = []
for _ in range(self.config.episodes if episodes is None else episodes):
state, done, total = env.reset(), False, 0.0
while not done:
action = self.act(state)
next_state, reward, terminated, truncated = env.step(action)
self.update(state, action, reward, next_state, terminated)
state, total, done = next_state, total + reward, terminated or truncated
returns.append(total)
return returns
def evaluate(self, env) -> float:
"""Return of one episode of the greedy policy (no exploration, no learning)."""
state, done, total = env.reset(), False, 0.0
while not done:
state, reward, terminated, truncated = env.step(self.act(state, greedy=True))
total, done = total + reward, terminated or truncated
return total
def greedy_policy(self) -> np.ndarray:
"""Best action in every state, shape (n_states,)."""
return np.argmax(self.q, axis=1)- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 7, run with
python3 -m unittest -v
Practice
Using the template, create CliffWalk() and a QLearning agent, train for 500 episodes, and check that evaluate returns -13.0. Reshape greedy_policy to 4 by 12 and trace the path. Then plot the list that train returned and explain why the average training return stays well below -13 although the greedy path is the shortest one.
Check on learning
- The agent explores with random actions, yet the table converges to the values of a policy that never explores. Which part of the update makes that possible?
A way to think about it
Look at which next action the target uses, and whether that depends on what the agent actually did next. Compare with a target that used the action really taken.
- After training, the greedy path runs along the cliff edge, but the returns during training are often far worse than . Is the algorithm failing?
A way to think about it
Separate the policy being learned from the policy being followed. With , estimate how often a random action is drawn on a 13-step walk beside the cliff and what one bad draw costs.
- What would happen to learning with in an environment with random rewards, and why does it work acceptably on the cliff grid?
A way to think about it
With each update replaces the entry with the latest sample. Ask whether the samples for one state and action differ from visit to visit on this grid, where moves and rewards are deterministic.
- If every entry started at instead of 0, with all real rewards negative, how would the agent's exploration change even with ?
A way to think about it
Untried actions keep their optimistic starting value, while tried ones are pulled down toward the truth. Consider which action the greedy rule then prefers in a state.