AI Wiki中文/EN

时序差分:结局没到,也能更新估计

Temporal-difference learning

推导TD(0),追踪奖励跨两个回合传播,区分真正终止与人为截断的目标。

本页目录直觉理解数学与方法代码实现局限与误解实验与练习研究脉络

反复经历时,奖励逐渐影响较早的状态

设一条两步路线:入口 → 房间 → 终止,奖励分别为0和4。两个非终止状态的价值都从零开始,折扣0.9、步长0.5。第一次转移时,房间看起来仍值零,入口也不变;第二次转移看到奖励4,房间估计升到2。

再走一遍,入口已经可以使用房间估计:目标1.8,新值0.9;房间则从2升到3。第二回合中,最终奖励已经影响较早的预测,而不必先为那个较早访问计算完整回报。

这就是时序差分学习(temporal-difference learning,TD)。Sutton的1988论文研究相邻预测之差带来的学习,教材工作稿给出这里使用的表格TD(0)规则。这条路线是原创例子,不是对两项来源实验的复现。

两个回合展示奖励向较早状态传播;单独的边界例子区分采集截断与真正终止。
两个回合展示奖励向较早状态传播;单独的边界例子区分采集截断与真正终止。

对贝尔曼目标取一个样本

在有限马尔可夫决策过程中固定平稳策略pi。用r_pi(s)表示其期望即时奖励,用P_pi(s,s')表示状态转移概率。奖励有界、折扣小于1时,其价值满足:

vπ(s)=rπ(s)+γ∑s′Pπ(s,s′)vπ(s′).v_\pi(s)=r_\pi(s)+\gamma\sum_{s'}P_\pi(s,s')v_\pi(s').

策略评估可以对已知转移表求平均;无模型学习器则只观察一次奖励和一个后继。TD(0)用当前后继估计代替未知真值:

δt=Rt+1+γVt(St+1)−Vt(St),Vt+1(St)=Vt(St)+αtδt.\delta_t=R_{t+1}+\gamma V_t(S_{t+1})-V_t(S_t),\qquad V_{t+1}(S_t)=V_t(S_t)+\alpha_t\delta_t.

其他状态项不变。右侧两项都使用本次更新前的表,即使下一状态就是当前状态也如此。真正终止状态的后续价值为零,但进入它时收到的奖励仍然计入。Silver讲义将奖励加后继估计称为TD目标,将目标与当前估计之差称为TD误差。

偏差从哪里来

将目标记为Y_t。在给定当前状态和固定当前表的条件下,其期望与目标价值之差为:

E[Yt∣St=s,Vt]−vπ(s)=γ∑s′Pπ(s,s′)(Vt(s′)−vπ(s′)).\mathbb E[Y_t\mid S_t=s,V_t]-v_\pi(s) =\gamma\sum_{s'}P_\pi(s,s')\bigl(V_t(s')-v_\pi(s')\bigr).

用目标的条件期望减去贝尔曼方程,即得此式。若后继估计正确,目标在这个条件意义下无偏;否则,后继误差经过加权进入当前目标。这就是自举:用一个估计帮助构造另一个估计的目标。

TD常被描述为用一些偏差换取比完整蒙特卡洛回报更低的方差。这个对照在适当估计和任务下有用,却不是无条件不等式。考虑一个反例:某零奖励状态以相同概率进入两个零奖励状态,随后都终止。真值和所有完整回报均为零,但当前表随意给两个后继赋值+100和−100。gamma为0.9时:

Var⁡(Gt∣St=s)=0,Var⁡(Yt∣St=s,Vt)=902=8100.\operatorname{Var}(G_t\mid S_t=s)=0, \qquad \operatorname{Var}(Y_t\mid S_t=s,V_t)=90^2=8100.

两个误差在期望中抵消,因此这里的目标无偏,却有更大方差。偏差与方差是两回事。Silver幻灯片中的概括不能当作覆盖任意价值表的定理。

为什么反复更新可能有效

若步长在看到下一奖励与转移之前已经选定,条件平均更新为:

E[ΔV(s)∣St=s,Vt]=αt(rπ(s)+γ∑s′Pπ(s,s′)Vt(s′)−Vt(s)).\mathbb E[\Delta V(s)\mid S_t=s,V_t] =\alpha_t\bigl(r_\pi(s)+\gamma\sum_{s'}P_\pi(s,s')V_t(s')-V_t(s)\bigr).

因此,带噪转移在平均意义下把估计推向固定策略的贝尔曼备份。这个关系解释了算法,本身却不是收敛证明。标准表格同策略收敛条件包括:对每个要估计的状态进行适当采样、噪声矩有界,以及逐状态步长满足:

∑k=1∞αk(s)=∞,∑k=1∞αk(s)2<∞.\sum_{k=1}^{\infty}\alpha_k(s)=\infty, \qquad \sum_{k=1}^{\infty}\alpha_k(s)^2<\infty.

这里的k统计状态s的更新次数,不是全部全局转移。正常数步长不满足第二个条件,估计可能持续波动。固定策略、马尔可夫性和表格表示都重要;神经网络逼近器或异策略数据需要另一套分析。工作稿也区分了批量数据解与有限在线效率的主张。

把终止标记与采集限制分开

将标准库程序保存为td_prediction.py,用Python 3.12运行。step返回新表及目标/误差,不修改输入;replay展示每次转移;train则在原创街机中按固定前进/转盘策略实际交互。

"""Original td_prediction 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')


class Arcade:
    def __init__(self, seed):
        self.rng = random.Random(seed)
        self.state = 2

    def reset(self):
        self.state = 0
        return self.state

    def step(self, action):
        if type(action) is not int or action not in (0, 1) or self.state == 2:
            raise ValueError('valid action and a nonterminal state required')
        if self.state == 0:
            self.state, reward = (2, 2.0) if action == 0 else (1, 0.0)
        elif action == 0:
            self.state, reward = 2, 4.0
        else:
            u = self.rng.random()
            self.state = 0 if u < .4 else 1 if u < .8 else 2
            reward = 1.6
        return self.state, reward, self.state == 2


def step(values,state,reward,next_state,terminated,alpha=.5,gamma=.9):
    unit(alpha,'alpha');unit(gamma,'gamma')
    sequence([state,next_state],[reward],values,terminated)
    target=reward+(0 if terminated else gamma*values[next_state]);delta=target-values[state]
    out=list(values);out[state]+=alpha*delta
    return out,dict(target=target,delta=delta)


def replay(states,rewards,initial,alpha=.5,gamma=.9,terminated=True):
    sequence(states,rewards,initial,terminated);v=list(initial);trace=[]
    for t,r in enumerate(rewards):
        v,record=step(v,states[t],r,states[t+1],terminated and t==len(rewards)-1,alpha,gamma)
        trace.append(dict(time=t,**record,values=v.copy()))
    return dict(values=v,trace=trace)


def train(episodes=5000,seed=31):
    if type(episodes) is not int or episodes<1:raise ValueError('positive episode count required')
    env=Arcade(seed);v=[0.0]*3;counts=[0]*3;history=[]
    for episode in range(1,episodes+1):
        s=env.reset()
        for _ in range(10000):
            nxt,r,done=env.step(1);counts[s]+=1
            v,_=step(v,s,r,nxt,done,alpha=.8/counts[s]**.6)
            s=nxt
            if done:break
        else:raise RuntimeError('episode budget exhausted')
        if episode in (1,10,100,1000,episodes):history.append(dict(episode=episode,values=v.copy()))
    return dict(values=v,counts=counts,history=history)


def demo():
    a=replay([0,1,2],[0,4],[0,0,0]);b=replay([0,1,2],[0,4],a['values'])
    _,cut=step([0,4,0],0,0,1,False);_,end=step([0,4,0],0,0,2,True)
    return dict(first_episode=a,second_episode=b,cutoff_target=cut['target'],terminal_target=end['target'],
                trained=train(),model_reference=[360/79,400/79,0])


if __name__=='__main__':
    print(json.dumps(demo(),indent=2,allow_nan=False))

两次确定性路线回放得到[0, 2, 0],随后是[0.9, 3, 0]。另一个单转移前缀在价值4的非终止房间结束,目标为3.6;奖励0的真正终止转移,目标才是0。外部时间限制不能成为把前者改成后者的理由。若任务本身确实在截止时间结束,应将剩余时间纳入任务及其终止约定。

随机街机使用种子31,训练5,000回合,状态计数为[14816, 24696, 0],估计约[4.630453, 5.158160, 0]。步长为0.8 / N(s)^0.6。模型参照[360/79, 400/79, 0]在学习之外计算。第1,000回合的估计恰好比第5,000回合更接近真值:单条采样路径不一定单调改善。这些观测不是收敛证明,也不是误差证书。

单次表格TD算术只改一项,但这个教学函数还校验并复制整张S项表,实际每转移成本为O(S)。训练只保留选定快照;快照个数固定时,工作内存为O(S)。replay刻意保存全部T张中间表,额外占O(TS)。若超出10,000步安全预算,程序抛错,不报告成功完成了回合。

策略一变,预测问题也变

在所述假设下,TD预测估计产生数据的策略。若把采样或策略平均的继续价值换成动作最大值,更新就变成了控制方法。SARSA将动作依赖写清,n步回报则延后自举,以纳入更多已观察奖励。

自举既能传播有用信息,也能传播错误估计。状态表示不当、访问不足、步长不合适或终止掩码错误,都会影响结果。有限数据集反复批量TD的解,与一次在线运行单调进步,不是同一个主张;在未知环境中,经验TD误差下降本身也不能证明价值已经准确。

看学习曲线之前,先看目标

  1. 自转移、旧值2、奖励1、gamma0.9、alpha0.5,新值是多少?

    答案:目标用旧值:1 + 0.9 × 2 = 2.8,误差0.8,新值2.4。把刚更新的新值立即塞回同一个目标,就定义了另一种计算。

  2. 第一次走完开头路线得到[0,2,0],复算第二回合。

    答案:入口目标0 + 0.9 × 2 = 1.8,更新为0.9;房间到终止的目标为4,从2向4走一半,得到3。

  3. 无偏TD目标一定比完整回报方差小吗?

    答案:不一定。两个后继反例的目标等概率为+90和−90,均值是正确的零,方差却为8,100;每条完整回报则都恰好为零。

  4. 模拟器在墙钟预算用完时重置。在选择自举掩码前应记录什么?

    答案:记录环境是真的终止,还是只结束采集,并保存重置前的最后观测。持续任务的截断用该观测的继续价值;重置观测属于另一条轨迹。

原始结果有适用条件

Sutton1988将TD放在早期学习系统的脉络中,并陈述特定情形的形式结果。这里仅读其前两页,没有核完整证明或实验。工作稿与Silver讲义支持本文使用的表格更新与预测对照。本文自行推导条件目标恒等式,采用原创小例,不宣称TD总比蒙特卡洛学得快。

先判断,再看解释

时间限制在非终止状态切断了一次持续转移,自举值应自动设零吗?

选择一个答案

学习目标

  • 用更新前的价值表计算TD误差。
  • 解释自举偏差及表格收敛所需的独立条件。

先修与延伸

查看知识关联图 →

参考文献

  1. Reinforcement Learning: An Introduction — second-edition working draft (2014–2015)
    Richard S. Sutton; Andrew G. Barto · 2015
  2. Lecture 4: Model-Free Prediction
    David Silver · 2015
  3. Learning to Predict by the Methods of Temporal Differences
    Richard S. Sutton · 1988

版本1 · 编写状态: 已完成记录中的技术复核

查看技术检查记录(AI)

Codex · 2026-09-23 · Single AI author. Scoped reading: PDF158–159 §6.1 sample backups, TD(0) and fixed-policy target; PDF167–168 cautions about batch versus online comparisons. 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. Read physical PDF1–2 only: journal identity, received1987/revised1988, successive-prediction idea, earlier systems and the author's claim of special-case formal results. Did not inspect the full convergence proofs or reproduce experiments; do not present broad abstract superiority claims as universal guarantees. 6 paired equations and four explained exercises. Checked ordered TD updates, two-episode reward propagation, true termination versus cutoff bootstrap, diminishing visit steps and seeded training. Exact arithmetic verifies conditional bias and an unbiased TD target with larger variance than a return.

  • 核顺序TD更新、两回合奖励传播、终止与截断自举、递减访问步长和固定种子训练;精确算术核条件偏差及无偏TD目标方差仍可更大的反例。
  • 每题四张计算SVG,12数值/几何与36响应式组合通过;12张当前选定图均直接实看,浏览器输入由插图前SHA绑定,完整页面验收另记。

核对的来源位置:

  • Reinforcement Learning: An Introduction — second-edition working draft (2014–2015) · PDF158–159 §6.1 sample backups, TD(0) and fixed-policy target; PDF167–168 cautions about batch versus online comparisons. 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.
  • Learning to Predict by the Methods of Temporal Differences · Read physical PDF1–2 only: journal identity, received1987/revised1988, successive-prediction idea, earlier systems and the author's claim of special-case formal results. Did not inspect the full convergence proofs or reproduce experiments; do not present broad abstract superiority claims as universal guarantees.

相关主题

没有匹配结果,试试英文名或缩写。

已显示 0 条结果

将整个查询放入双引号,可按短语匹配。