DQN: learning action values with a neural network
深度 Q 网络
Derive the selected-action loss and test a nonlinear NumPy learner against a hand-solvable environment.
dqnWhy learn a value function with a network?
Imagine a four-room teaching environment. In any room you can leave immediately for a reward of 0.2, or move right. Moving right from the last room earns 1 and ends the episode; earlier right moves earn nothing. From the first room, which action is better? With a discount of 0.9, four right moves return 0.729. An agent that has only seen the exit reward may nevertheless keep leaving.
A table can solve these four rooms perfectly well. DQN becomes useful when enumerating every observation is impractical: a network maps an observation to an estimated value for each available action. Shared parameters let an update affect other observations, but can also disturb estimates that were previously good. The table remains the clearer baseline for this tiny environment. Our network is deliberately small enough to inspect.
DQN combines neural action-value prediction with Q-learning targets. The 2013 paper trains from a replay memory; the 2015 work explicitly includes a separately maintained target network. Read their algorithms as two versions, rather than inserting every later detail into the earlier paper. The 2013 derivation already holds target parameters fixed during an optimization step; that is distinct from the 2015 delayed-copy mechanism. 2013 algorithm 2015 Methods
First read Q-learning and backpropagation. The companion articles explain experience replay and target networks; here the question is how a sampled transition becomes a gradient.
One transition, one selected-action target
Let a transition contain state input x, integer action a, reward r, the actual next input x′, and a boolean d indicating task termination. There are two discrete actions. Our original network uses two tanh hidden layers with eight units each; it outputs both action values in one pass:
For a batch of B rows, x is a B-by-1 array and Q is B-by-2. The biases broadcast across rows. The model has 106 parameters including biases. It is a nonlinear function approximator, not a table with renamed entries. The Atari networks in the papers use convolutions over images; this tanh network is a teaching substitute, not that architecture. 2013 architecture
Keep a separate parameter set θ⁻ for computing the bootstrap value. Treat the following target as fixed while differentiating with respect to θ:
Termination sets the future contribution to zero. A collector stopping because of an external step budget does not itself make the task terminal: retain the actual next observation and bootstrap if the task continues. If the task really has a fixed horizon, its end is termination and remaining time belongs in the state. Do not substitute the observation after a reset for x′. Our implementation skips terminal next-input evaluation entirely, so a terminal placeholder containing NaN cannot contaminate the target through “zero times NaN.” Termination and truncation
Gather only the value of the action actually taken. The half-squared batch loss is:
We did not observe what the other action would have produced in that transition. It gets no separate supervised target from this row. Differentiating the square gives the residual, and the chain rule gives the network gradient:
This is the semi-gradient convention: the bootstrap estimate is used as a number, not differentiated through as another function of the online parameters. For example, a selected prediction 0.2 and target 0.6 give residual−0.4; gradient descent moves a directly adjustable prediction upward. The other output’s direct derivative is zero, although updating shared hidden weights may change its prediction too.
Here u counts completed online gradient updates. The copy happens after the designated update. That update used the previous target; the next update uses the new one. Counting gradient updates matters when several are taken per environment step. We use plain SGD and half-squared loss. The 2015 Methods additionally describes clipped errors; our demo does not implement that training recipe. Neither a replay buffer nor a delayed target supplies a general convergence proof for this nonlinear control problem. Target construction and training
A small experiment whose optimum is known
The program below is standalone Python 3.12 with NumPy 1.26.4. State s is one of 0, 1, 2, 3 and is encoded as(s−1.5)/1.5. Action 0 exits for 0.2; action 1 moves right, earning 1 only on the final move. The exact optimal action values, with rows in state order and columns in action order, are:
Work backward from the last room to verify the right-hand column. There are three discounts before the final reward, not four. The exit value is always 0.2 because it terminates immediately.
Each run collects 3000 decisions, uses epsilon 0.25, and stores the latest 64 transitions. Once 16 are available, each decision triggers one batch of 16 draws with replacement and an SGD step of 0.03. There are 2985 gradient updates and 74 target copies, one per 40 updates. Random exploration samples both actions, including the greedy one. Evaluation uses the greedy policy without exploration in the same known environment. It measures this task’s return, not generalization to unseen environments.
"""Original NumPy teaching network, not an Atari reproduction."""
import math
import random
import numpy as np
def integer(value, minimum=0):
if isinstance(value, bool) or not isinstance(value, (int, np.integer)) or value < minimum:
raise ValueError('Expected an integer within the documented range')
return int(value)
def network(seed=0):
rng = np.random.default_rng(integer(seed))
return {name: value for name, value in [
('w1', rng.normal(0, .5, (1, 8))), ('b1', np.zeros(8)),
('w2', rng.normal(0, .3, (8, 8))), ('b2', np.zeros(8)),
('w3', rng.normal(0, .3, (8, 2))), ('b3', np.zeros(2))]}
def forward(p, x):
x = np.asarray(x, dtype=float)
if x.ndim != 2 or x.shape[1] != 1 or not np.isfinite(x).all():
raise ValueError('Expected finite input with shape (batch, 1)')
h1 = np.tanh(x @ p['w1'] + p['b1'])
h2 = np.tanh(h1 @ p['w2'] + p['b2'])
return h2 @ p['w3'] + p['b3'], (x, h1, h2)
def loss_gradient(p, x, actions, targets):
q, (x, h1, h2) = forward(p, x)
a = np.asarray(actions)
y = np.asarray(targets, dtype=float)
n = len(x)
if not n or a.shape != (n,) or a.dtype.kind not in 'iu' or np.any((a < 0) | (a >= 2)):
raise ValueError('One integer action 0 or 1 is required per row')
if y.shape != (n,) or not np.isfinite(y).all():
raise ValueError('One finite fixed target is required per row')
error = q[np.arange(n), a] - y
dq = np.zeros_like(q)
dq[np.arange(n), a] = error / n
d2 = (dq @ p['w3'].T) * (1 - h2 * h2)
d1 = (d2 @ p['w2'].T) * (1 - h1 * h1)
g = {'w1': x.T @ d1, 'b1': d1.sum(0), 'w2': h1.T @ d2,
'b2': d2.sum(0), 'w3': h2.T @ dq, 'b3': dq.sum(0)}
return float(.5 * np.mean(error * error)), g
def copy_network(p):
return {k: v.copy() for k, v in p.items()}
def update_target(target, online, tau=1.):
# tau weights the NEW online parameters; Spinning Up's rho = 1 - tau.
if not math.isfinite(tau) or not 0 <= tau <= 1 or target.keys() != online.keys():
raise ValueError('Invalid target update')
for k in target:
if target[k].shape != online[k].shape or np.shares_memory(target[k], online[k]):
raise ValueError('Target must be a separate, shape-compatible network')
for k in target:
target[k][...] = (1 - tau) * target[k] + tau * online[k]
def targets(target, rewards, next_x, terminated, gamma=.9):
r = np.asarray(rewards, dtype=float)
x = np.asarray(next_x, dtype=float)
done = np.asarray(terminated)
if not math.isfinite(gamma) or not 0 <= gamma <= 1:
raise ValueError('Discount must be in [0, 1]')
if r.ndim != 1 or x.shape != (len(r), 1) or done.shape != r.shape or done.dtype.kind != 'b':
raise ValueError('Mismatched batch or non-boolean terminal flags')
if not np.isfinite(r).all():
raise ValueError('Finite rewards required')
y = r.copy()
live = ~done
# Do not evaluate a terminal placeholder (which may be NaN).
if live.any():
y[live] += gamma * forward(target, x[live])[0].max(axis=1)
return y
def transition(state, action):
s, a = integer(state), integer(action)
if s > 3 or a > 1:
raise ValueError('Four states and two actions only')
if a == 0:
return .2, 0, True
return (1., 0, True) if s == 3 else (0., s + 1, False)
def encode(states):
return (np.asarray(states, dtype=float).reshape(-1, 1) - 1.5) / 1.5
def evaluate(p, gamma=.9):
policy = forward(p, encode(range(4)))[0].argmax(axis=1).tolist()
state, discount, total = 0, 1., 0.
for _ in range(4):
reward, state, done = transition(state, policy[state])
total += discount * reward
if done:
return policy, total
discount *= gamma
raise AssertionError('This acyclic environment ends within four steps')
def train(seed=0, steps=3000, period=40):
steps, period = integer(steps, 1), integer(period, 1)
online = network(seed)
target = copy_network(online)
rng = random.Random(seed + 1009)
initial_policy, initial_return = evaluate(online)
memory, cursor, updates, state = [], 0, 0, 0
snapshots = []
for step in range(steps):
action = rng.randrange(2) if rng.random() < .25 else int(forward(online, encode([state]))[0].argmax())
reward, next_state, done = transition(state, action)
row = (state, action, reward, next_state, done)
if len(memory) < 64:
memory.append(row)
else:
memory[cursor] = row
cursor = (cursor + 1) % 64
state = 0 if done else next_state
if len(memory) < 16:
continue
batch = [memory[rng.randrange(len(memory))] for _ in range(16)]
s, a, r, ns, d = zip(*batch)
y = targets(target, r, encode(ns), d)
loss, gradients = loss_gradient(online, encode(s), a, y)
for k in online:
online[k] -= .03 * gradients[k]
updates += 1
if updates % period == 0:
update_target(target, online)
if (step + 1) % 500 == 0:
policy, ret = evaluate(online)
snapshots.append(dict(step=step + 1, updates=updates, minibatch_loss=loss, policy=policy, greedy_return=ret))
policy, ret = evaluate(online)
expected = np.array([[.2, .9 ** 3], [.2, .9 ** 2], [.2, .9], [.2, 1.]])
q = forward(online, encode(range(4)))[0]
return dict(seed=seed, steps=steps, updates=updates, target_copies=updates // period,
initial_policy=initial_policy, initial_return=initial_return,
policy=policy, greedy_return=ret, optimal_return=.9 ** 3,
max_q_error=float(np.abs(q - expected).max()), q=q.tolist(), checkpoints=snapshots)
def demo():
runs = [train(seed) for seed in range(8)]
return dict(model='Original four-state teaching MDP; 1-8-8-2 tanh Q-network',
exploration=.25, capacity=64, batch_size=16, learning_rate=.03,
gamma=.9, hard_copy_every_gradient_updates=40, runs=runs,
mean_return=float(np.mean([x['greedy_return'] for x in runs])),
maximum_q_error=max(x['max_q_error'] for x in runs))
if __name__ == '__main__':
import json
print(json.dumps(demo(), indent=2, allow_nan=False))
The fixed seeds 0–7 do not all succeed. Seeds 0,5,6,7 learn the all-right policy and return 0.729. Seeds 1–4 finish with the all-exit policy and return 0.2. The eight-run mean is 0.4645; the largest absolute error over the eight final Q-tables is about 1.0638. These are the recorded runs, not a population success-rate estimate. Seed 0’s final Q error is about 0.0383, but reporting only that run would hide the other outcomes.
A useful prediction explains one possible obstacle. If exiting remains greedy in every room, a right move requires the exploratory branch to select right. Under independent epsilon-greedy action draws, the chance of reaching the rewarding exit on one attempt from state 0 is:
This calculation holds for that fixed action preference. It is not an exact failure probability for the changing learner, and the log does not prove that each unsuccessful seed never saw the final reward. It identifies a data bottleneck to investigate. A larger network alone does not ensure that the needed transitions arrive.
Verification includes central finite differences for all 106 parameters, a hand-computed loss, selected-output masking, terminal NaN handling, independent backward evaluation of the MDP, and target-copy timing. A full batch costs roughly O(BP) arithmetic for P network parameters, with O(P) parameter/gradient storage and O(BH) hidden activations. Scalar replay records cost O(N) storage for capacity N. The demo also stores run summaries and checkpoints; image replay would require accounting for frame bytes separately.
What the small result can and cannot tell us
A falling minibatch loss can mean that the network fits its current targets, even when the targets or sampled state distribution are poor. Targets change after synchronization. Compare policy return and value error against the known optimum instead of reading one training loss as a certificate of control quality.
This experiment has deterministic transitions, fully observed scalar states and two actions. It omits image preprocessing, RMSProp, error clipping and the Atari evaluation protocol. The publications’ game results cannot be inferred from it. Function approximation, bootstrapping and off-policy data can interact badly; the partial success here should encourage diagnosis, not a claim that the algorithm always works. Original scope Later Methods
Try tabular Q-learning as a baseline. To investigate the failed seeds, log visits to the final reward and compare more than one exploration schedule under equal environment-step budgets. If you tune on these eight seeds, use additional seeds for a subsequent evaluation and label that change. Double DQN, dueling architectures and prioritized replay address different issues; adding their names does not explain which failure occurred here.
Check the update before scaling it
- One row has selected Q=0.2 and fixed target 0.6. What are its half-squared loss and derivative with respect to that Q? With step size 0.1, what happens if Q itself is the parameter?
Answer: The loss is 0.08 and derivative−0.4. The new value is 0.24. A neural parameter update need not change the output by exactly 0.04 because the chain rule includes the network’s Jacobian.
- A transition earns 1, gamma=0.9 and the largest next Q is 3. Compare a true terminal transition with a collector truncation while the task continues.
Answer: The terminal target is 1; the continuing target is 3.7. The truncation case requires the actual next observation. Using a reset observation would attach the value of a different state.
- Why can the unselected action’s value change even though its direct output derivative for this row is zero?
Answer: The actions share hidden parameters. An update through the selected output can alter the hidden representation used by both outputs. Zero direct supervision is not a promise that the other prediction stays fixed.
- A colleague reports seed 0’s return 0.729 as evidence that this setup solves the task reliably. What should be added?
Answer: Report all eight seeds: four return 0.729, four 0.2, with mean 0.4645. Inspect reward-reaching visits and compare a tabular baseline or changed exploration under equal budgets. The fixed-preference probability 1/4096 suggests a mechanism to test; it does not diagnose every failed trajectory by itself.
Read the algorithm at the right version
The 2013 v1 paper establishes the early replay-based neural Q-learning setup; its algorithm and the 2015 Methods should be compared directly when discussing target networks. We checked the indicated method and architecture passages, not the game score tables, and did not reproduce Atari results. This article derives the gradient from its explicitly defined half-squared loss rather than copying the papers’ printed gradient sign convention. The Farama explanation supplies the later API distinction needed when translating the algorithm into a modern environment loop.
Make a prediction, then check
The sampler stops an otherwise continuing transition at its collection limit. Should its target automatically become just the reward?
Learning objectives
- Derive the semi-gradient with a fixed bootstrap target and distinguish termination from truncation.
- Interpret seed-dependent learning and distinguish the teaching MDP from Atari benchmarks.
Prerequisites & connections
Explore related knowledge →References
- Playing Atari with Deep Reinforcement Learning — arXiv v1
Volodymyr Mnih; Koray Kavukcuoglu; David Silver; Alex Graves; Ioannis Antonoglou; Daan Wierstra; Martin Riedmiller · 2013 - Human-level control through deep reinforcement learning — scoped Methods reading
Volodymyr Mnih; Koray Kavukcuoglu; David Silver; Andrei A. Rusu; Joel Veness; Marc G. Bellemare; Alex Graves; Martin Riedmiller; Andreas K. Fidjeland; Georg Ostrovski; Stig Petersen; Charles Beattie; Amir Sadik; Ioannis Antonoglou; Helen King; Dharshan Kumaran; Daan Wierstra; Shane Legg; Demis Hassabis · 2015 - Deep Dive: Gymnasium Step API
The Farama Foundation · 2023
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-23 · Single AI author. Scoped reading: Read PDF1 identity/abstract,3–5,6 opening architecture/training paragraphs; viewed3/5. Explicit2013-12-19v1, not2015 Nature algorithm. No score-table audit or Atari reproduction. Derive loss gradient independently: printed target-minus-Q expression is an update direction, not the stated square-loss gradient. Read PDF1 identity/abstract,6 left-column Methods and right-column evaluation,7; viewed7. Separate target network, uniform replay and stated training conditions only; score/extended tables not audited. Printed variance decomposition and gradient sign require independent correction; no general convergence claim or benchmark replication. Read full2023-10-27 article on API motivation, alternatives and theory. Terminal versus collection truncation and time-remaining state for finite-horizon tasks. No current installation or third-party tutorial audit performed. 7 paired equations and four explained exercises. Checked nonlinear two-hidden-layer network, all106 parameter finite differences, selected-action half-squared loss, terminal masking and actual next observation, four-state backward oracle and gradient-clock target copies. Eight fixed seeds include four early-exit failures; path probability is conditional on fixed action preferences, not an exact diagnosis or Atari reproduction.
- Checked nonlinear two-hidden-layer network, all106 parameter finite differences, selected-action half-squared loss, terminal masking and actual next observation, four-state backward oracle and gradient-clock target copies. Eight fixed seeds include four early-exit failures; path probability is conditional on fixed action preferences, not an exact diagnosis or Atari reproduction.
- Four computed SVG variants per topic;11 numeric/geometry tests and18 responsive cases passed. All six selected current captures directly viewed. Browser inputs bound by SHA before integration. Full article acceptance recorded separately.
Source locations checked:
- Playing Atari with Deep Reinforcement Learning — arXiv v1 · Read PDF1 identity/abstract,3–5,6 opening architecture/training paragraphs; viewed3/5. Explicit2013-12-19v1, not2015 Nature algorithm. No score-table audit or Atari reproduction. Derive loss gradient independently: printed target-minus-Q expression is an update direction, not the stated square-loss gradient.
- Human-level control through deep reinforcement learning — scoped Methods reading · Read PDF1 identity/abstract,6 left-column Methods and right-column evaluation,7; viewed7. Separate target network, uniform replay and stated training conditions only; score/extended tables not audited. Printed variance decomposition and gradient sign require independent correction; no general convergence claim or benchmark replication.
- Deep Dive: Gymnasium Step API · Read full2023-10-27 article on API motivation, alternatives and theory. Terminal versus collection truncation and time-remaining state for finite-horizon tasks. No current installation or third-party tutorial audit performed.
Related topics