Double DQN: choose with one estimate, evaluate with another
Double DQN
Enumerate maximum-estimator bias, compute the double target, and compare two learners without hiding failed seeds.
double-dqnWhy does the best-looking estimate look too good?
Imagine two actions that both have true value zero. Each estimate independently reports either −1 or +1 with equal probability. A single estimate is unbiased. Picking the larger estimate gives −1 only when both errors are negative; otherwise it gives +1. Its average is therefore 1/2, although neither action is worth more than zero. Selection has changed which errors we see.
Double DQN changes the bootstrap target in DQN: use the online network to choose the next action, then read that action’s value from the target network. This separates two operations that an ordinary maximum performs together. It does not require two competing agents or two different environments. The original Double Q-learning paper studies double estimators; the neural adaptation uses the delayed target network already present in DQN. Estimator argument Neural adaptation
Read target networks first. Their delay and the Double DQN selection rule solve different parts of the update problem: delay holds a predictor still for several updates; double selection changes which entry in that predictor becomes the target.
Selection and evaluation have different jobs
Write an action’s true value as q_a and a noisy estimate as X_a. For integrable unbiased estimates, convexity of the maximum gives:
This statement concerns the estimator and its noise. It does not say every trained network overestimates every action at every state. Correlations, approximation error and an already biased target can change a learning system’s behavior.
Let I be the index selected by maximizing X, breaking ties consistently. Suppose a second vector Y is independent of X and each Y_a is unbiased for q_a. Conditioning on the selected index then yields:
The second estimate no longer inherits the selected positive noise. It may instead underestimate the best true value because selection can choose an inferior action. Independence and unbiased evaluation are doing work in this derivation; merely calling two networks “online” and “target” does not establish either assumption. Double-estimator conditions
For a transition with reward r, next state s′ and terminal indicator d, use online parameters theta for selection and delayed parameters theta-minus for evaluation:
Compute the bootstrap only for nonterminal rows. A collection time limit is not automatically task termination; see the distinction in DQN. During this update, treat y as a fixed number. For B sampled transitions, the teaching implementation uses:
There is no gradient through the argmax or delayed evaluation in this semi-gradient update. The online network trains by gradient descent; a separate clock copies it to the target network. Double DQN retains the target-copy mechanism, so the estimators remain related. The 2010 tabular algorithm instead randomly chooses which of two tables to update, using separate selection and evaluation roles. These are related constructions, not identical update schedules. Double Q-learning Double DQN
For online next-state values [5,4], target values [1,3], reward 2 and discount 0.9:
At termination both targets are 2. If the online and target networks are identical, the two formulas also agree, including when the maximum is tied and the chosen value is the same.
The program enumerates two actions with independent ±1 errors in each of two estimators: four signs give 16 equally likely cases. “Same estimator” evaluates with the very estimates used for selection. The exact averages are:
In the second row, selection chooses the better action with probability 3/4. Independent evaluation therefore averages 3/8, below its true maximum 1/2. This is a small exact counterexample to the claim that double estimation is always an unbiased maximum.
An estimator experiment and a learning experiment
Run the complete program with Python and NumPy; repository dependencies are pinned in requirements-examples.txt. noise_example uses exact fractions for the enumeration. double_targets computes online argmax and delayed evaluation without modifying either parameter dictionary. Ties select the lowest action index. Terminal rows do not evaluate their next-state inputs.
The second experiment uses an original four-state environment. Action 0 exits with reward 0.2; action 1 moves right, earning reward 1 only when leaving the last state. Earlier right moves earn zero. Discount is 0.9, so the optimal start return is 0.729. A 1→8→8→2 tanh network has 106 parameters. Both learners use the same eight seeds, 3,000 environment steps, epsilon 0.25, replay capacity 64, batches of 16 sampled with replacement, learning rate 0.03 and target copies every 40 gradient updates. The first update occurs after 16 stored transitions, giving 2,985 updates.
"""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')
from fractions import Fraction
import itertools
def double_targets(online, 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
if live.any():
chosen = forward(online, x[live])[0].argmax(axis=1)
evaluated = forward(target, x[live])[0]
y[live] += gamma * evaluated[np.arange(live.sum()), chosen]
return y
def noise_example(means):
means = list(map(Fraction, means))
rows = []
for errors in itertools.product([-1, 1], repeat=4):
a = [means[i] + errors[i] for i in range(2)]
b = [means[i] + errors[i + 2] for i in range(2)]
selected = max(range(2), key=lambda i: a[i])
rows.append((max(a), b[selected], a[selected]))
average = [sum(row[j] for row in rows) / len(rows) for j in range(3)]
return dict(true_means=list(map(float, means)), true_max=float(max(means)),
single_mean=float(average[0]), independent_double_mean=float(average[1]),
identical_estimators_mean=float(average[2]),
exact_averages=list(map(str, average)), cases=len(rows))
def train(seed=0, steps=3000, mode='double'):
steps = integer(steps, 1)
if mode not in ('double', 'dqn'):
raise ValueError('Choose double or dqn')
online = network(seed)
target = copy_network(online)
rng = random.Random(seed + 1009)
memory, cursor, updates, state = [], 0, 0, 0
for _ in range(steps):
action = rng.randrange(2) if rng.random() < .25 else int(forward(online, encode([state]))[0].argmax())
reward, ns, done = transition(state, action)
row = (state, action, reward, ns, done)
if len(memory) < 64:
memory.append(row)
else:
memory[cursor] = row
cursor = (cursor + 1) % 64
state = 0 if done else ns
if len(memory) < 16:
continue
batch = [memory[rng.randrange(len(memory))] for _ in range(16)]
s, a, r, ns, done = zip(*batch)
y = double_targets(online, target, r, encode(ns), done) if mode == 'double' else targets(target, r, encode(ns), done)
_, g = loss_gradient(online, encode(s), a, y)
for k in online:
online[k] -= .03 * g[k]
updates += 1
if updates % 40 == 0:
update_target(target, online)
policy, ret = evaluate(online)
q = forward(online, encode(range(4)))[0]
exact = np.array([[.2, .729], [.2, .81], [.2, .9], [.2, 1.]])
return dict(seed=seed, mode=mode, steps=steps, updates=updates, policy=policy,
greedy_return=ret, max_q_error=float(np.abs(q - exact).max()))
def demo():
a, b = network(0), network(1)
for p in [a, b]:
for value in p.values():
value[...] = 0.
a['b3'][:] = [5., 4.]
b['b3'][:] = [1., 3.]
comparisons = {mode: [train(seed, mode=mode) for seed in range(8)] for mode in ['dqn', 'double']}
return dict(equal_means=noise_example([0, 0]), unequal_means=noise_example([0, Fraction(1, 2)]),
online_values=[5., 4.], target_values=[1., 3.],
hand_double=double_targets(a, b, [2., 2.], [[0.], [np.nan]], [False, True]).tolist(),
hand_dqn=targets(b, [2., 2.], [[0.], [np.nan]], [False, True]).tolist(),
comparisons=comparisons,
mean_returns={mode: float(np.mean([row['greedy_return'] for row in runs])) for mode, runs in comparisons.items()},
scope='Exact estimator enumeration and original four-state NumPy control; not an Atari comparison or general bias theorem.')
if __name__ == '__main__':
import json
print(json.dumps(demo(), indent=2, allow_nan=False))
For both methods, seeds 0, 5, 6 and 7 learn the all-right policy; seeds 1–4 remain at the all-exit policy. The eight-seed mean return is 0.4645 for each method. Their numerical Q errors differ slightly, but this run provides no average-return improvement for Double DQN. The exact noise example demonstrates an estimator mechanism; the environment run measures the behavior of this particular training setup. They answer different questions.
An update requires current-state prediction and backpropagation, online next-state selection, and target next-state evaluation. If F is one network-forward cost per state and G its backward cost, a batch costs on the order of B(F+G), with additional forward passes reflected in the constant. Action argmax is linear in the action count. Target storage adds another parameter copy; replay storage is separate. The implementation checks a fixed-target gradient by finite differences over all 106 parameters.
A smaller target is not automatically a better policy
Delayed copies are correlated with the online network, and approximate values may already be biased. Double DQN does not supply the independence used in the exact estimator derivation. It also cannot repair missing exploration: changing a target formula does not create an unobserved successful trajectory. Our failed seeds make that limitation visible.
The example is a small fully observed control task, not an Atari reproduction. It omits image preprocessing, convolutional features and benchmark evaluation protocols. Combining Double DQN with another architecture or sampling rule requires specifying each choice separately. Rainbow’s methods discussion places double selection alongside dueling, prioritized replay and distributional targets; it does not make those names interchangeable. Combination context
Predict the target before running the code
- Keep the hand example but exchange the online values to [4,5]. What target results, and what if the transition terminates?
Answer: Online selection now chooses action 1. Its target value is 3, so the nonterminal target is 4.7. At termination it is 2, regardless of the next-state ranking.
- In the equal-true-value noise example, replace the independent evaluator with the selector itself. Does the mean remain zero?
Answer: No. Evaluation reuses the selected positive noise, giving mean 1/2. Two variable names referring to one estimate do not provide independent evaluation.
- Why is the independent double estimate 3/8 for true values [0,1/2], rather than 1/2?
Answer: The noisy selector chooses the better action in three of four selecting-noise cases. Conditional on each choice, independent evaluation returns that action’s true value in expectation. Thus the average is (3/4)(1/2)+(1/4)0=3/8.
- Both learners obtain mean return 0.4645 in the supplied environment. What can this establish, and what should a stronger comparison change?
Answer: It establishes equal measured mean returns under these seeds and settings, not equivalence on all tasks. Report the four failed seeds, keep environment interactions and evaluation rules matched, then test additional seeds and tasks where overestimation can affect choices. Do not select only runs that favor one method.
Read the estimator argument before the benchmark claim
The 2010 paper supplies the double-estimator reasoning and tabular construction. Here we used its PDF pages 2–4, without auditing the later full convergence proof. The Double DQN source is explicitly arXiv v3 dated December 8, 2015; its metadata identifies AAAI 2016. We used PDF pages 2 and 4 for the selection/evaluation rule and its relation to DQN. No score table is reproduced. Original estimator Selected neural version
Rainbow is the October 6, 2017 v1 methods reading, not a verified copy of the final 2018 publication. Its pages 2–3 help separate the components of a combined agent. Continue with dueling networks to change how Q values are represented, or prioritized replay to change which transitions are sampled. Rainbow methods
Make a prediction, then check
Online next-state values are[5,4], target values[1,3], reward2 and gamma0.9. What is the nonterminal Double DQN target?
Learning objectives
- Separate action selection from evaluation and state when independent double estimates can underestimate.
- Implement the delayed-network target without claiming estimator independence or guaranteed performance gains.
Prerequisites & connections
Explore related knowledge →References
- Double Q-learning — scoped estimator and algorithm reading
Hado van Hasselt · 2010 - Deep Reinforcement Learning with Double Q-learning — arXiv v3
Hado van Hasselt; Arthur Guez; David Silver · 2015 - Rainbow: Combining Improvements in Deep Reinforcement Learning — arXiv v1 methods
Matteo Hessel; Joseph Modayil; Hado van Hasselt; Tom Schaul; Georg Ostrovski; Will Dabney; Dan Horgan; Bilal Piot; Mohammad Azar; David Silver · 2017
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-23 · Single AI author. Scoped reading: Read PDF2–4: maximum bias, independent double estimators, Lemma1 and tabular update narrative. Independence and unbiased evaluation are assumptions, not properties guaranteed by delayed neural copies. No later full convergence proof or benchmark replication. Read PDF2 and4; viewed4. First preprint2015-09-22, selected v3 dated2015-12-08, metadata AAAI2016. Online selection, target evaluation and periodic copies; explicitly correlated estimators. No appendix proof, score-table audit or Atari reproduction. Selected2017-10-06v1, then under review for AAAI2018; not verified final2018 bytes. Read PDF2–3 methods: Double Q, PER, dueling mean, categorical softmax and integrated targets. Distributional Rainbow uses KL priority. No later full architecture, benchmark or ablation audit. 6 paired equations and four explained exercises. Checked online selection/target evaluation, fixed-target all106-parameter finite differences, terminal and tie handling, exact16-case independent estimator arithmetic and unequal-mean underestimation. Distinguish random table updates in2010 from delayed correlated networks. Eight matched seeds retain four failed policies and equal mean returns0.4645; no Atari or general performance claim.
- Checked online selection/target evaluation, fixed-target all106-parameter finite differences, terminal and tie handling, exact16-case independent estimator arithmetic and unequal-mean underestimation. Distinguish random table updates in2010 from delayed correlated networks. Eight matched seeds retain four failed policies and equal mean returns0.4645; no Atari or general performance claim.
- Four computed SVG variants per topic;14 numeric/geometry tests and24 current responsive cases passed. All eight selected current captures directly viewed. Two unchanged groups retain initial captures, two revised groups use new captures; actual assets and manuscripts are SHA bound. Full article acceptance recorded separately.
Source locations checked:
- Double Q-learning — scoped estimator and algorithm reading · Read PDF2–4: maximum bias, independent double estimators, Lemma1 and tabular update narrative. Independence and unbiased evaluation are assumptions, not properties guaranteed by delayed neural copies. No later full convergence proof or benchmark replication.
- Deep Reinforcement Learning with Double Q-learning — arXiv v3 · Read PDF2 and4; viewed4. First preprint2015-09-22, selected v3 dated2015-12-08, metadata AAAI2016. Online selection, target evaluation and periodic copies; explicitly correlated estimators. No appendix proof, score-table audit or Atari reproduction.
- Rainbow: Combining Improvements in Deep Reinforcement Learning — arXiv v1 methods · Selected2017-10-06v1, then under review for AAAI2018; not verified final2018 bytes. Read PDF2–3 methods: Double Q, PER, dueling mean, categorical softmax and integrated targets. Distributional Rainbow uses KL priority. No later full architecture, benchmark or ablation audit.
Related topics