Double DQN:选择动作与评价动作分开做
Double DQN
枚举最大值估计的偏差,手算双估计目标,并保留小网络对比中的失败种子。
double-dqn最好的估计,为什么看起来好过头了?
设想两个动作的真实价值都为零。每个估计独立地以相同概率报出−1或+1。单个估计无偏,但取两者最大值,只有两个误差都为负时才得到−1,其余情况都是+1。因此最大值的平均数为1/2,尽管两个动作都不比零更好。选择改变了我们看到的误差。
Double DQN修改DQN的自举目标:在线网络选择下一动作,目标网络给这个动作打分。普通最大值操作同时做的两件事,现在分开完成。不需要两个对抗智能体,也不需要两个环境。Double Q-learning原论文研究双估计器,神经网络版本则利用DQN已有的延迟目标网络。估计器论证 神经网络版本
建议先读目标网络。延迟和双估计选择处理的是更新中的不同问题:延迟让预测器在若干步内保持不动;双估计规则改变从这个预测器中取哪个动作的值。
选择与评价,各自做一件事
用q_a表示动作真实价值,X_a表示带噪估计。若估计可积且无偏,最大值函数的凸性给出:
这个结论讨论估计器及其噪声,并不是说训练中的网络在每个状态、每个动作上都高估。相关性、函数逼近误差,以及本来就有偏的目标,都可能改变学习系统的表现。
令I为最大化X选出的动作索引,并固定并列时的选择规则。假设另一向量Y与X独立,而且每个Y_a对q_a无偏。按所选索引作条件分解:
第二个估计不再继承被选中的正噪声,却可能低估真正的最佳价值,因为选择阶段可能挑中较差动作。推导用到了独立性和评价无偏;把两个网络分别命名为“在线”“目标”,并不能建立这些前提。双估计前提
对奖励r、下一状态s′、终止指示d的转移,用在线参数theta选择,用延迟参数theta-minus评价:
只对未终止记录计算自举部分。采集步数上限不自动等于任务终止,区别见DQN。本次更新把y视为固定数值。对B条抽样转移,教学实现使用:
这是半梯度更新,不沿argmax或延迟评价反传。在线网络执行梯度下降,另一个时钟负责把在线参数复制到目标网络。Double DQN保留这一复制机制,因此两估计器仍有关联。2010年的表格算法则随机选择更新两个表中的一个,分别承担选择与评价角色;两者有共同思想,但更新时序不相同。Double Q-learning Double DQN
下一状态在线值为[5,4]、目标值为[1,3],奖励2、折扣0.9时:
若任务终止,两种目标都为2。若在线网络与目标网络完全相同,两种公式也一致;即使最大值并列,选出的数值仍相同。
程序枚举两个动作、两个估计器各自独立的±1误差:四个符号构成16种等可能情况。“同一估计器”表示评价时复用选择时的估计。精确平均数为:
第二行中,选择器以3/4的概率选中较好动作,独立评价因此平均为3/8,低于真实最大值1/2。这是一个可穷举的反例:双估计并不总是对最大值无偏。
一个估计实验,一个学习实验
下面是可直接运行的Python/NumPy程序,仓库requirements-examples.txt锁定依赖。noise_example用精确分数枚举;double_targets计算在线argmax与延迟评价,不修改任何参数字典。并列时选最小动作索引,终止记录不计算下一状态。
第二个实验使用原创四状态环境:动作0退出并获奖励0.2;动作1向右,只有离开最后一个状态时获奖励1,之前向右奖励均为零。折扣0.9,因此最优起点回报0.729。1→8→8→2的tanh网络共106参数。两方法使用相同八种子、3000环境步、epsilon=0.25、64条回放、16条有放回批次、学习率0.03,每40次梯度更新复制目标。缓存满16条开始更新,共2985次。
"""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))
两种方法在seed0、5、6、7学到全向右策略,seed1—4都停留在全退出策略。两者八种子平均回报均为0.4645。Q误差略有不同,但这次实验没有显示Double DQN的平均回报提升。精确噪声例展示估计机制,环境实验衡量这套具体训练设置的行为;两者回答不同问题。
一次更新包括当前状态预测与反传、在线下一状态选择、目标下一状态评价。设每状态前向成本为F、反向为G,批成本量级为B(F+G),额外前向次数体现在常数中。动作argmax对动作数为线性;目标存储增加一份参数,回放存储另计。实现对全部106参数做了固定目标的有限差分梯度检查。
目标更小,不自动意味着策略更好
延迟副本与在线网络相关,逼近值也可能已经有偏。Double DQN不提供精确估计器推导中的独立性。它也无法修复探索缺失:换一个目标公式不会凭空产生尚未观察到的成功轨迹。本例的失败种子保留了这个限制。
这是小型、完全可观测的控制任务,没有复现Atari;它省去了图像预处理、卷积特征和基准评估流程。与其他架构或采样法组合时,仍需分别说清各项选择。Rainbow的方法部分把双估计、dueling、优先回放和分布目标并列讨论,但这些名称不能互换。组合语境
先预测目标,再运行程序
- 保留手算例其他条件,把在线值换成[4,5],目标是多少?若任务终止呢?
答案:在线选择动作1,其目标值为3,因此未终止目标为4.7;终止时为2,与下一状态排序无关。
- 等真实价值的噪声例中,把独立评价器换成选择器自身,平均值还为零吗?
答案:不为零。评价复用了选中的正噪声,平均值为1/2。两个变量名指向同一个估计,并不构成独立评价。
- 真实价值[0,1/2]时,为什么独立双估计为3/8,而不是1/2?
答案:选择噪声的四种情况中,三种选到较好动作。给定每次选择,独立评价的期望等于该动作真实值,因此平均为(3/4)(1/2)+(1/4)0=3/8。
- 本环境中两方法平均回报都是0.4645,能据此说明什么?更强的对比应怎样做?
答案:只能说明这些种子和设置下测得平均回报相等,不能说明在全部任务上等价。保留四个失败种子,匹配环境交互预算和评价规则,再测更多种子以及高估会影响选择的任务,不只挑有利于某方法的运行。
先读估计器论证,再看基准主张
2010论文给出双估计思想和表格构造,本篇使用PDF2—4页,未审计后面的完整收敛证明。Double DQN来源明确为2015年12月8日arXiv v3,元数据对应AAAI2016;本篇用PDF2、4页核对选择/评价规则及其与DQN的关系,不转载成绩表。原始估计器 所选神经网络版本
Rainbow使用2017年10月6日v1的方法部分,不冒充已核读最终2018版;PDF2—3帮助区分组合智能体的各个组件。接着读dueling网络,研究Q值如何表示;或读优先回放,研究哪些转移被抽到。Rainbow方法
先判断,再看解释
下一状态在线值[5,4]、目标值[1,3],奖励2、gamma=0.9;未终止的Double DQN目标是多少?
学习目标
- 分离动作选择与评价,说清独立双估计出现低估的条件。
- 实现延迟网络目标,不把相关估计器说成独立,也不保证性能提升。
先修与延伸
查看知识关联图 →参考文献
- 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
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(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.
- 核在线选择/目标评价、106参数固定目标有限差分、终止/并列、16种独立噪声及不等均值低估。区分2010随机选表与相关延迟网络;八匹配种子保留四次失败,平均回报同为0.4645,不作Atari或普遍提升主张。
- 每题四张计算SVG,14数值/几何与24个当前响应式组合通过;八张选定当前截图均实看;两组未变图保留初次捕获,两组改图使用新捕获,实际资产及稿件SHA绑定,完整页面验收另记。
核对的来源位置:
- 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.
相关主题