Sign in

Q learning

Tabular Q-learning

A table of action values, updated after every step toward the reward plus the best value available in the next state.

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

  1. Start with every table entry at initial_q.
  2. In state ss, choose an action: a random one with probability ε\varepsilon, otherwise the one with the highest entry, breaking ties at random.
  3. Take the action and observe the reward rr and next state s′s'.
  4. Form the target: rr plus γ\gamma times the largest entry in the row of s′s', or just rr if the episode terminated.
  5. Move Q(s,a)Q(s, a) a fraction α\alpha of the way toward the target.
  6. Continue from s′s', 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

IfUse instead
States are images or continuous measurementsDQN
The risk taken while exploring matters, for example near a cliffSARSA
Real steps are expensive and you can remember what happenedDyna

Math foundations

  1. The Bellman optimality equation

    Q∗(s,a)=E[r+γmax⁡a′Q∗(s′,a′)  ∣  s,a]Q^{*}(s, a) = \mathbb{E}\Bigl[ r + \gamma \max_{a'} Q^{*}(s', a') \;\Big|\; s, a \Bigr]

    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.

  2. The TD target

    y=r+γmax⁡a′Q(s′,a′)y = r + \gamma \max_{a'} Q(s', a')

    One sampled version of the right-hand side, using the current table in place of Q∗Q^{*}. When s′s' is terminal the target is just rr.

  3. The TD error

    δ=y−Q(s,a)\delta = y - Q(s, a)

    The gap between the fresh estimate and the stored one. Positive means the step went better than the table expected. The template's update returns this number.

  4. The update

    Q(s,a)←Q(s,a)+α δQ(s, a) \leftarrow Q(s, a) + \alpha\, \delta

    Move the stored value a fraction α\alpha of the way toward the target. A full move would let one noisy sample overwrite everything learned before.

  5. The epsilon-greedy behaviour policy

    π(a∣s)={1−ε+ε∣A∣if a=arg⁡max⁡bQ(s,b)ε∣A∣otherwise\pi(a \mid s) = \begin{cases} 1 - \varepsilon + \dfrac{\varepsilon}{|\mathcal{A}|} & \text{if } a = \arg\max_{b} Q(s, b) \\[1ex] \dfrac{\varepsilon}{|\mathcal{A}|} & \text{otherwise} \end{cases}

    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

s,as, a
current state and the action taken in it
rr
reward received for that step
s′,a′s', a'
next state and a candidate action in it
Q(s,a)Q(s, a)
the table entry: estimated return after taking a in s and acting greedily afterwards
Q∗Q^{*}
the true action values of the best policy
γ\gamma
discount factor (1.0 by default in the template)
α\alpha
step size (learning_rate)
ε\varepsilon
probability of a random action while training (epsilon)
∣A∣|\mathcal{A}|
number of actions
y,δy, \delta
the TD target and the TD error

Worked by hand

Use the template's defaults α=0.5\alpha = 0.5 and γ=1\gamma = 1. First an ordinary step: Q(s,a)=−4Q(s, a) = -4, r=−1r = -1, and the best entry in the next row is −2-2. Then a step off the cliff: Q(s,a)=−10Q(s, a) = -10, r=−100r = -100, and the agent is sent to the start, whose best entry is −13-13.

y=−1+1×(−2)=−3,δ=−3−(−4)=1y = -1 + 1 \times (-2) = -3, \qquad \delta = -3 - (-4) = 1
Q(s,a)←−4+0.5×1=−3.5Q(s, a) \leftarrow -4 + 0.5 \times 1 = -3.5
y=−100+1×(−13)=−113,δ=−113−(−10)=−103y = -100 + 1 \times (-13) = -113, \qquad \delta = -113 - (-10) = -103
Q(s,a)←−10+0.5×(−103)=−61.5Q(s, a) \leftarrow -10 + 0.5 \times (-103) = -61.5

The ordinary step nudges its entry up by half the error. The single fall drops the entry for stepping into the cliff from −10-10 to −61.5-61.5, 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 edge
Read 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

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

  2. After training, the greedy path runs along the cliff edge, but the returns during training are often far worse than −13-13. Is the algorithm failing?
    A way to think about it

    Separate the policy being learned from the policy being followed. With ε=0.1\varepsilon = 0.1, estimate how often a random action is drawn on a 13-step walk beside the cliff and what one bad draw costs.

  3. What would happen to learning with α=1\alpha = 1 in an environment with random rewards, and why does it work acceptably on the cliff grid?
    A way to think about it

    With α=1\alpha = 1 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.

  4. If every entry started at +10+10 instead of 0, with all real rewards negative, how would the agent's exploration change even with ε=0\varepsilon = 0?
    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.