AI Wiki中文/EN

Q-learning

Q-learning

Update action values from experience and understand bootstrapping, off-policy learning, and convergence conditions.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Intuition: is an action worth taking?

An action in a maze is valuable not only for its immediate reward but also for the state it leads to. Q-learning estimates discounted return with Q(s,a)Q(s,a): take action aa in state ss, then follow an optimal policy. By trying actions and observing rewards and next states, the learner revises this value table.

The environment is commonly modeled as a Markov decision process: conditioned on the current state and action, the next-state and reward distribution does not depend on earlier history. Omitting important information from the state can invalidate that assumption. Classic analysis and the standard textbook distinguish the algorithm from the conditions required for convergence. Watkins and Dayan, Sutton and Barto, second-edition working draft, Section 6.5

The update and the meaning of off-policy

For a nonterminal transition (s,a,r,s′)(s,a,r,s'):

Q(s,a)←Q(s,a)+α[r+γmax⁡a′Q(s′,a′)−Q(s,a)].Q(s,a)\leftarrow Q(s,a)+\alpha\left[r+\gamma\max_{a'}Q(s',a')-Q(s,a)\right].

The bracketed quantity is the temporal-difference error. α\alpha is the learning rate and γ\gamma the discount factor. Part of the target uses a current value estimate instead of waiting for the complete return at the end of an episode. This is bootstrapping.

An ε-greedy behavior policy chooses a random action with probability ε and otherwise uses the highest current estimate. The update nevertheless targets the next state’s maximum value rather than the exploratory action actually taken next. This makes Q-learning off-policy. SARSA uses the value of the actual subsequent action instead.

At a true terminal state there is no future return, so the target is just rr. A time-limit truncation need not mean environmental termination; handle it according to the task definition. Confusing the two biases value estimates.

Here we restrict attention to a finite, stationary Markov decision process, bounded rewards, a table, and 0≤γ<10\leq\gamma<1. Every state–action pair must be visited infinitely often. Counting the kkth update of that particular pair, step sizes must also satisfy:

0<αk(s,a)≤1,∑k=1∞αk(s,a)=∞,∑k=1∞αk(s,a)2<∞.0<\alpha_k(s,a)\leq1,\qquad \sum_{k=1}^{\infty}\alpha_k(s,a)=\infty,\qquad \sum_{k=1}^{\infty}\alpha_k(s,a)^2<\infty.

The original theorem uses α<1\alpha<1; here finitely many α=1\alpha=1 steps are allowed, such as the first step of 1/k1/k. A finite prefix does not change the later asymptotic conditions. For example, αk=1/k\alpha_k=1/k satisfies both sum conditions, but does not ensure sufficient visitation. A fixed ε does not make unreachable states appear. These conditions concern asymptotic convergence; finite-run success still requires measurement. The lab’s constant learning rate fails the square-sum condition. A nonterminal update scans successor actions in O(∣A(s′)∣)O(|A(s')|) time; a terminal update takes constant time, and the full table requires O(∑s∣A(s)∣)O(\sum_s|A(s)|) storage. Original paper, Section 2

The optimal Bellman equation provides another reading: Q∗(s,a)Q^*(s,a) is the expectation of immediate reward plus discounted optimal successor value. An observed transition provides a random target, and the step size mixes it with the old estimate. No complete transition matrix must first be estimated, but learning still depends on information from the environment. The paper also discusses absorbing tasks with γ=1\gamma=1 under extra termination conditions; this code excludes that case. Read the proof together with the authors’ corrections to the policy-value equation on page 280 and the condition in Appendix Lemma B.4. Author errata

Check one update

This complete example tests a single update. Full training additionally needs an environment, an exploration policy, and episode handling.

import math

def update(q, state, action, reward, next_state, terminal,
           alpha=0.5, gamma=0.9):
    # q is a mapping from state IDs to nonempty lists of action values.
    if not (math.isfinite(alpha) and 0 < alpha <= 1
            and math.isfinite(gamma) and 0 <= gamma < 1
            and math.isfinite(reward)):
        raise ValueError("finite reward, 0 < alpha <= 1, 0 <= gamma < 1 required")
    if type(terminal) is not bool:
        raise ValueError("terminal must be Boolean")
    row = q[state]
    if type(action) is not int or not 0 <= action < len(row):
        raise ValueError("invalid action index")
    current = row[action]
    if not math.isfinite(current):
        raise ValueError("current value must be finite")
    future = 0.0
    if not terminal:
        successors = q[next_state]
        if not successors or not all(math.isfinite(v) for v in successors):
            raise ValueError("nonempty finite successor values required")
        future = max(successors)
    target = reward + gamma*future
    result = (1-alpha)*current + alpha*target
    if not math.isfinite(target) or not math.isfinite(result):
        raise ValueError("update overflow")
    row[action] = result
    return result

q = {0: [0.0, 0.0], 1: [2.0, 1.0]}
assert abs(update(q, 0, 1, 1.0, 1, False) - 1.4) < 1e-12
# A terminal transition never looks up its nonexistent successor.
assert update(q, 0, 0, 1.0, "end", True) == 0.5
assert update(q, 0, 0, -2.0, "end", True, alpha=1.0) == -2.0
assert update(q, 0, 0, 3.0, 1, False, alpha=1.0, gamma=0) == 3.0
for settings in ({"alpha": 0}, {"alpha": 1.1}, {"gamma": 1},
                 {"gamma": float("nan")}):
    try:
        update(q, 0, 1, 1.0, 1, False, **settings)
    except ValueError:
        pass
    else:
        raise AssertionError("invalid learning parameters accepted")

Exploration, approximation, and rewards

Unvisited actions cannot reveal their true value through table updates alone. A purely greedy policy can prematurely commit to an action that looked good by chance. Sparse rewards, huge state spaces, and partial observability constrain direct tabular learning.

Replacing a table with a neural network does not preserve tabular convergence results automatically. Function approximation, off-policy data, and bootstrapping can interact unstably. Maximizing a reward also does not establish that the reward captures a human’s intended objective.

Experiments and exercises

  1. What is the nonterminal target in the example? Answer: 1+0.9×2=2.81+0.9\times2=2.8; a learning rate of 0.5 produces 1.4.
  2. Should a true terminal update add γmax⁡Q\gamma\max Q? Answer: no.
  3. Does increasing ε necessarily improve the current episode’s reward? Answer: no; exploration can trade short-term performance for information.
  4. With one state, one action, reward 1 on every step, a self-loop, and γ=0.9\gamma=0.9, what is the optimal value? Answer: Q∗=1+0.9Q∗Q^*=1+0.9Q^* gives Q∗=10Q^*=10. Starting at zero with step size 0.5 produces 0.5 on the first update; one update does not immediately yield 10.
  5. Compare episode counts in the grid lab and distinguish accidental success from a stable policy. Serious evaluation also needs multiple random seeds and separate evaluation episodes.

Research connections

SARSA changes the policy targeted by the update. DQN approximates action values with a neural network, using replay and target networks in training. Offline reinforcement learning studies settings where new interaction cannot be collected. Specify the policy that generated the data, the reward definition, and whether exploration noise remains active during evaluation.

Make a prediction, then check

What is the target for a truly terminal transition?

Choose one answer

Learning objectives

  • Calculate a temporal-difference update and handle terminal states.
  • Explain exploration, sampling, and tabular convergence conditions.

Prerequisites & connections

Explore related knowledge →

References

  1. Q-learning
    Christopher J. C. H. Watkins; Peter Dayan · 1992
  2. Reinforcement Learning: An Introduction — second-edition working draft (2014–2015)
    Richard S. Sutton; Andrew G. Barto · 2015
  3. Errata to Q-learning
    Chris Watkins; Peter Dayan

Version2 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-05 · Codex technical check: cited-source comparison, re-derivation and recalculation, bilingual argument comparison, and executed Python assertions; no independent human peer review.

  • Checked pairwise visitation and step-size conditions, finite α=1 prefixes, and exclusion of γ=1; terminal transitions never read successor entries.
  • Independently checked the one-state self-loop value 10, terminal targets, negative rewards, and parameter boundaries; deterministic iteration is not presented as stochastic convergence evidence.
  • Compared the main claims, assumptions, examples, exercises, and citations across languages; structural checks additionally compare display equations, code, and source IDs. This is an AI technical check, not independent human peer review.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.