DQN:用神经网络学习动作价值
Deep Q-networks
推导所选动作的损失,在可手算环境中检查非线性NumPy网络,并保留探索失败的种子。
dqn为什么用网络学习价值?
设想一个有四个房间的教学环境。在任意房间,你都可以立即离开,拿到0.2奖励;也可以向右走。只有从最后一个房间向右离开,才拿到1奖励并结束回合,前面的右移没有奖励。从第一个房间出发,哪个动作更好?折扣因子为0.9时,连续右移四次的回报是0.729。不过,如果智能体只见过立即离开的奖励,它仍可能一直提前退出。
四个房间用表格就能解决。当观测多到难以逐一枚举时,DQN才有用武之地:网络把观测映射成各个动作的价值估计。共享参数使一次更新能够影响其他观测,也可能破坏原本不错的估计。对这个小环境,表格仍是更清楚的基线;我们故意把网络做小,便于检查。
DQN把神经网络的动作价值预测与Q-learning目标结合起来。2013年论文使用经验回放训练;2015年工作明确加入单独维护的目标网络。应把它们当作两个版本比较,不能把后来的每项细节都塞回早期论文。2013年的推导已经在一次优化中固定目标参数,这与2015年延迟复制的机制是两回事。2013年算法 2015年Methods
先读Q-learning与反向传播。经验回放和目标网络分别解释两项配套机制;本篇要回答的是,一条抽到的转移怎样变成梯度。
一条转移,一个所选动作的目标
一条转移包含状态输入x、整数动作a、奖励r、实际下一输入x′,以及表示任务是否终止的布尔值d。本例有两个离散动作。原创网络包含两层tanh隐藏层,每层8个单元,一次前向输出两个动作价值:
批大小为B时,x是B行1列,Q是B行2列;偏置沿行广播。包含偏置在内共有106个参数。这是非线性函数近似器,并非给表格单元换个名字。论文里的Atari网络对图像使用卷积;这里的tanh网络是教学替代,并不是原架构。2013年架构
另存一组参数θ⁻计算自举值。对θ求导时,把下面的目标视作固定数值:
任务终止时,未来贡献为零。采集器因为外部步数预算而停止,并不自动让任务终止:保留实际下一观测,任务继续就应自举。如果任务本身具有固定时域,到时结束属于终止,状态中应包含剩余时间。不能拿重置后的观测替换x′。程序完全跳过终止行的下一输入计算,因此即使终止占位输入含NaN,也不会出现“零乘NaN”污染目标。终止与截断
只取实际执行动作对应的预测值。批次的半平方损失为:
这条转移没有告诉我们另一个动作会发生什么,因此不能顺带给另一个动作编一个监督目标。平方求导得到残差,再通过链式法则得到网络梯度:
这就是半梯度约定:自举估计当作数值使用,不把它当成在线参数的另一个函数继续求导。例如,所选预测为0.2、目标为0.6,残差就是−0.4;若预测值本身可以直接调整,梯度下降会把它提高。另一个输出的直接导数为零,但共享隐藏权重的更新仍可能改变它的预测。
这里u计数已经完成的在线梯度更新。复制发生在指定更新之后:这一次仍使用旧目标,下一次才使用新目标。如果每个环境步做多次梯度更新,就必须分清计数单位。本例使用普通SGD和半平方损失;2015年Methods还描述了误差裁剪,演示没有实现那套完整训练方案。回放和延迟目标都不能给这个非线性控制问题提供普遍收敛证明。目标构造与训练
最优解可以手算的小实验
下列程序可在Python3.12、NumPy1.26.4下独立运行。状态s取0、1、2或3,编码为(s−1.5)/1.5。动作0立即退出,得0.2;动作1右移,只在最后一步得1。按状态排列各行、按动作排列各列,精确的最优动作价值为:
从最后一个房间向前倒推,就能核对右列。最终奖励之前只有三次折扣,不是四次;提前退出立即终止,因此左列始终为0.2。
每次运行采集3000个决策,epsilon为0.25,保存最近64条转移。攒够16条后,每个决策触发16次有放回抽样,并以0.03学习率做一次SGD。总计2985次梯度更新、74次目标复制,每40次更新复制一次。随机探索包含全部动作,也包括当前贪心动作。评估在同一个已知环境中使用无探索的贪心策略,测的是这个任务的回报,不是对未见环境的泛化。
"""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))
固定种子0—7并非全部成功。种子0、5、6、7学到全右策略,回报0.729;种子1—4最后仍全部提前退出,回报0.2。八次平均回报为0.4645,八张最终Q表中的最大绝对误差约1.0638。这些是实际记录的运行,不是总体成功率的估计。种子0的最终Q误差约0.0383,只报告这一轮会隐藏其他结果。
一个可计算的预测说明了可能的障碍。假设每个房间的贪心动作始终是提前退出,那么右移必须由探索分支选中。在独立的epsilon-greedy动作抽样下,从状态0出发,一次尝试抵达奖励终点的概率为:
这个计算以固定动作偏好为条件,不是不断变化的学习器的精确失败概率;当前日志也没有证明每个失败种子都从未见过最终奖励。它指出了值得调查的数据瓶颈。单纯加大网络,并不能保证需要的转移会出现。
检查包括全部106个参数的中心有限差分、手算损失、所选输出屏蔽、终止NaN处理、独立逆推MDP和目标复制时机。设网络参数数目为P,一次批训练约需O(BP)算术运算;参数及梯度占O(P),隐藏激活占O(BH),容量N的标量回放占O(N)。demo还保存运行摘要与检查点;若改成图像回放,需要另算帧字节,不能沿用标量记录的常数。
小实验能说明什么?
小批量损失下降,可能只说明网络更贴近当前目标,而目标或采样状态分布本身并不好。同步后目标还会变化。应结合策略回报和相对已知最优值的误差,不能把一次训练损失当作控制能力的证明。
本例只有确定性转移、完全可观测的标量状态和两个动作,省略了图像预处理、RMSProp、误差裁剪及Atari评估协议。不能据此推断原论文的游戏成绩。函数近似、自举和离策略数据可能产生不良相互作用;这里的部分成功应引导诊断,而非得出算法总能奏效的结论。早期研究范围 后续Methods
可以用表格Q-learning作基线。调查失败种子时,记录到达最终奖励的次数,在相同环境步数预算下比较不同探索安排。若已用这八个种子调参,后续评估应增加其他种子并标明变化。Double DQN、dueling架构与优先回放处理的是不同问题,列出这些名字并不能解释本例究竟哪里出了问题。
先核对更新,再扩大规模
- 一条记录的所选Q为0.2,固定目标为0.6。半平方损失和对该Q的导数是多少?若Q本身就是参数,学习率0.1会怎样更新?
答案:损失为0.08,导数为−0.4,新值为0.24。神经参数更新未必让输出恰好增加0.04,因为链式法则还包含网络的雅可比。
- 一条转移得到奖励1,gamma=0.9,最大下一Q为3。比较真实终止与任务仍继续的采集截断。
答案:终止目标为1,继续目标为3.7。截断情形需要实际下一观测;若换成重置观测,就接上了另一个状态的价值。
- 未选动作在本条记录中的直接输出导数为零,它的价值为什么仍可能改变?
答案:动作共享隐藏参数。经所选输出传回的更新可能改变两个输出共同使用的隐藏表示。没有直接监督,不等于另一个预测必定不动。
- 同事用种子0的0.729回报,声称本设置能可靠解决任务。还应补充什么?
答案:报告全部八个种子:四次0.729、四次0.2,均值0.4645。检查到达奖励的次数,并在同预算下比较表格基线或探索变化。固定动作偏好下的1/4096指出了待检验的机制,不能单独诊断每条失败轨迹。
按正确版本读算法
2013年v1论文给出早期基于回放的神经Q-learning设置;讨论目标网络时,应直接与2015年Methods比较。本项目核读了所注明的方法和架构段落,没有审计游戏成绩表,也没有复现Atari。本篇从明确定义的半平方损失自行推导梯度,不照搬论文印刷的梯度符号约定。Farama的解释补充了把算法接到现代环境循环时所需的API区别。
先判断,再看解释
采集器达到步数限制,但任务未终止;目标是否自动只剩本步奖励?
学习目标
- 推导固定自举目标的半梯度,区分终止与截断。
- 解释学习对种子的依赖,区分教学MDP与Atari基准。
先修与延伸
查看知识关联图 →参考文献
- 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
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(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.
- 核双隐藏层非线性网络、106参数有限差分、所选动作半平方损失、终止屏蔽与实际下一观测、四状态逆推及梯度步复制。八固定种子保留四次提前退出失败,路径概率以固定动作偏好为条件,不当精确诊断或Atari复现。
- 每题四张计算SVG,11数值/几何与18响应式组合通过;六张选定当前截图均直接实看;浏览器输入由插图前SHA绑定,完整页面验收另记。
核对的来源位置:
- 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.
相关主题