n步回报:先等几步奖励,再接上估计
N-step returns
计算延迟目标,在边界补完等待更新,并标明自举使用哪一版价值表。
n-step-returns一次预测应该等多久?
一步学习器看到下一奖励,就用价值估计补完剩余未来;蒙特卡洛学习器则等完整回合。n步目标先等至多n个奖励,再用估计补上剩余部分。这个选择既改变进入目标的信息,也改变何时能更新。
取原创轨迹0 → 1 → 0 → 终止,奖励0、1.6、2,折扣0.9,固定价值表[1,2,0]。第一次访问的一步、两步及完整回报目标分别为1.8、2.25和3.06。它们都不是简单把一步目标乘以n。
Sutton与Barto第7.1节介绍一步到完整回报备份的连续范围,Silver讲义写出相应折扣和。这里还要追踪一个单看目标公式容易漏掉的细节:等待更新时,价值表可能已经改变。
先数已观察奖励,再定位自举状态
设观测序列结束于状态下标H,包含S_0到S_H及奖励R_1到R_H。序列结束可能是真正终止,也可能只是采集截断。对正整数n和起点t,设h=min(t+n,H)。只有当h=H且终点真正终止时,z_h才为1,其余为零。固定表W给出:
第一个奖励的指数为零,自举项的指数等于该目标已观察的转移数。若h在观测边界之前,从那个中间状态自举;若只是停止采集而结束序列,即使没有凑齐n个奖励,也保留边界继续价值。
对于真正终止于T的完整回合,特殊情形为:
足够长的目标都变成同一完整回报,不会借用下一回合奖励。工作稿解释了这个边界规则。实看的工作稿式7.1在gamma平方后漏了奖励因子;这里使用完整下标求和,避免传播排版错误,并与Silver的n步公式一致。
目标与更新是两件事
目标需要的奖励在状态时刻u=min(t+n,H)可得。用实际更新时刻的当前表进行更新:
必须说明两项分别使用哪张表。这里两项都使用实际更新发生前的同一张表;整回合冻结一张表的离线计算则是另一约定。即使回放已有轨迹,也不能使用晚于所声明可用时刻的奖励。
终止时,多个等待起点可能同时准备好。按时间顺序补完,每个起点只更新一次;同一状态反复出现时,顺序可能影响结果。流式版本可以使用环形缓冲区,但下方教学代码保留完整输入轨迹,便于检查调度。
在明确条件下,多看奖励能减小一种近似误差
固定策略、采样前固定的表W、正确终止处理和小于1的折扣下,减去真值对应的n步恒等式,就只剩自举误差:
这里吸收终止扩展的价值为零。这个界约束固定表下目标的期望,不约束每个带噪样本;也不能直接证明使用同一批后续观测更新出来的自适应表满足同样结论。更长窗口可能增加采样方差并延迟学习,未必提升有限运行精度。gamma为1时,式中的因子不再衰减自举误差。
沿重复状态跟踪数字
开头轨迹中固定表为[1,2,0],按访问顺序排列目标向量:
例如第一个两步目标为0 + 0.9×1.6 + 0.9²×1 = 2.25。两次转移后回到状态0,因此自举用状态0的值。
现在允许alpha0.5的一步在线更新。第一次更新将状态0从1改为1.4,下一目标就使用新表:
这个差异不是折扣算错,而是采用在线价值更新约定、没有冻结整张表的结果。
展示可用时刻与补更新顺序
将程序保存为n_step.py,使用Python 3.12标准库运行。target在明确给定的表上计算单个目标;learn_episode按延迟更新回放已保存轨迹,记录各目标何时可得。它模拟更新时间,不是实时环境或环形缓冲区实现。
"""Original n_step teaching example; synthetic episodes, not benchmark reproduction."""
import json
import math
import random
def unit(x, name):
if isinstance(x, bool) or not isinstance(x, (int, float)) or not math.isfinite(x) or not 0 <= x <= 1:
raise ValueError(name+' must be finite in [0,1]')
def sequence(states, rewards, values, terminated):
if type(terminated) is not bool or len(values)<2 or any(not math.isfinite(x) for x in values) or values[-1]!=0:
raise ValueError('finite values with a zero terminal component required')
if not rewards or len(states)!=len(rewards)+1 or any(not math.isfinite(r) for r in rewards):
raise ValueError('nonempty finite rewards and one extra state required')
terminal=len(values)-1
if any(type(s) is not int or not 0<=s<=terminal for s in states):
raise ValueError('state index outside table')
if terminal in states[:-1] or (states[-1]==terminal)!=terminated:
raise ValueError('termination flag must match the final state only')
def target(states,rewards,values,t,n,gamma=.9,terminated=True):
unit(gamma,'gamma');sequence(states,rewards,values,terminated)
if type(n) is not int or n<1 or type(t) is not int or not 0<=t<len(rewards):raise ValueError('valid time and positive integer n required')
return _target(states,rewards,values,t,n,gamma,terminated)
def _target(states,rewards,values,t,n,gamma,terminated):
h=min(t+n,len(rewards));g=math.fsum(gamma**(k-t)*rewards[k] for k in range(t,h))
if h<len(rewards) or not terminated:g+=gamma**(h-t)*values[states[h]]
return g
def learn_episode(states,rewards,initial,n,alpha=.5,gamma=.9,terminated=True):
unit(alpha,'alpha');target(states,rewards,initial,0,n,gamma,terminated)
v=list(initial);trace=[];T=len(rewards)
def update(t,available):
g=_target(states,rewards,v,t,n,gamma,terminated);s=states[t];v[s]+=alpha*(g-v[s])
trace.append(dict(time=t,available=available,target=g,values=v.copy()))
for available in range(1,T+1):
t=available-n
if t>=0:update(t,available)
for t in range(max(0,T-n+1),T):update(t,T)
return dict(values=v,trace=trace)
def demo():
states=[0,1,0,2];rewards=[0,1.6,2];initial=[1,2,0]
fixed={str(n):[target(states,rewards,initial,t,n) for t in range(3)] for n in [1,2,3,10]}
learned={str(n):learn_episode(states,rewards,initial,n) for n in [1,2,3]}
return dict(fixed_value_targets=fixed,online=learned,
cutoff_target=target([0,1],[0],[0,4,0],0,5,terminated=False),
terminal_target=target([0,2],[0],[0,4,0],0,5,terminated=True))
if __name__=='__main__':
print(json.dumps(demo(),indent=2,allow_nan=False))
n=2时,起点0、1、2分别在可用时刻2、3、3更新,最终值为[1.8125,2.7,0]。n=1顺序更新得到[1.7,2.43,0];n=3按时间补完得到[2.015,2.7,0]。后者虽然使用完整回报,却仍在重复状态的两次更新之间改表,不等于冻结表后累加全部修正。
两个边界测试都只观察到奖励0:在价值4的非终止状态截断,即使n=5也得到3.6;真正终止则得到0。程序会拒绝与保留终止状态ID不一致的标记。
公共目标函数先校验长度T的轨迹和S项表,再直接加至多n项奖励,耗时O(T+S+min(n,T))。回合学习器只校验一次,随后使用内部求和函数;加上复制表快照,总时间为O(T min(n,T) + TS)。除输入存储外,trace自身占O(TS)。优化后的流式实现可以省掉完整快照并采用有限缓冲区;这个便于阅读的回放并不冒充那种实现。
不只是在选一个窗口长度
还要指定折扣、终止处理、自举表时机、步长和行为策略。增加n既改变采样奖励数量,也改变更新延迟;冻结目标的小误差界,不能决定其采样版本的方差。
异策略数据中,更长序列可能包含更多来自错误行为分布的动作;不加修正的目标未必评估期望的目标策略。TD(lambda)混合多个窗口,SARSA显式保留下一动作。两种扩展都不能免除边界与更新时间的定义。
标出每个奖励何时可用
-
开头轨迹第一次访问的两步目标,为什么从状态0自举,而不是状态1?
答案:两次转移是
0→1和1→0。目标纳入奖励0和1.6,再接gamma² × W(0);状态1只是一步后继。 -
W(0)=1、alpha0.5,计算两步目标及其第一次更新。答案:目标
0+0.9×1.6+0.81×1=2.25,状态0更新为1+0.5×(2.25−1)=1.625。 -
三次转移、
n=2,终止时更新几个起点?有起点更新两次吗?答案:起点1在时刻3准备好,起点2在时刻3补完;起点0已在时刻2更新。三个起点各一次;若补更新又从起点1开始,就会重复。
-
增大
n一定改善带噪任务的学习曲线吗?答案:不一定。冻结表偏差界随gamma的n次方缩小,但长目标可能噪声更大、到得更晚。应比较完整学习协议,包括边界、步长及评估策略,不能只看这一条界。
终点与表的版本都属于算法说明
工作稿讨论n步备份和在线/离线更新,Silver预测讲义把它放在TD与蒙特卡洛之间。上方期望误差界在明确的固定表条件下推导。重复状态回放和截断测试为原创计算,不是随机游走基准复现。
先判断,再看解释
回合在凑齐n个奖励之前结束,尚在等待的更新怎么办?
学习目标
- 计算窗口在终止前、终止时及越过终止时的目标。
- 让每个位置只更新一次,且不偷用当时尚不可得的奖励。
先修与延伸
查看知识关联图 →参考文献
- Reinforcement Learning: An Introduction — second-edition working draft (2014–2015)
Richard S. Sutton; Andrew G. Barto · 2015 - Lecture 4: Model-Free Prediction
David Silver · 2015
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(AI)
Codex · 2026-09-23 · Single AI author. Scoped reading: PDF183–184 §7.1, viewed183. Eq7.1 visibly omits the reward after gamma²; use the correct indexed sum, cross-checked with Silver PDF32 and direct arithmetic. Read2026-09-23. Author teaching page identifies the 2015 course; 2025 upload path is not the lecture year. Read PDF1,3–7,10–13,16–18,29,32,35,37,40–45. MC visit conventions, incremental means, TD targets, n-step returns, accumulating traces and explicitly offline equivalence. General bias/variance summaries are teaching heuristics, not unconditional variance or efficiency theorems. No slides/images copied. 6 paired equations and four explained exercises. Checked fixed-table target matrices, online bootstrap timing, terminal flush, large horizons, cutoff, integer-domain validation and update availability. Exact exhaustive paths verify a fixed-table bias bound; no adaptive-table theorem is claimed.
- 核固定表目标矩阵、在线自举时机、终止收尾、大步数、截断、整数定义域和更新可用时刻;精确穷举路径核固定表偏差界,不称为自适应表定理。
- 每题四张计算SVG,12数值/几何与36响应式组合通过;12张当前选定图均直接实看,浏览器输入由插图前SHA绑定,完整页面验收另记。
核对的来源位置:
- Reinforcement Learning: An Introduction — second-edition working draft (2014–2015) · PDF183–184 §7.1, viewed183. Eq7.1 visibly omits the reward after gamma²; use the correct indexed sum, cross-checked with Silver PDF32 and direct arithmetic. Read2026-09-23.
- Lecture 4: Model-Free Prediction · Author teaching page identifies the 2015 course; 2025 upload path is not the lecture year. Read PDF1,3–7,10–13,16–18,29,32,35,37,40–45. MC visit conventions, incremental means, TD targets, n-step returns, accumulating traces and explicitly offline equivalence. General bias/variance summaries are teaching heuristics, not unconditional variance or efficiency theorems. No slides/images copied.
相关主题