AI Wiki中文/EN

Temporal-difference learning: update before the ending

时序差分学习

Derive TD(0), follow a reward across two episodes and separate terminal targets from artificial cutoffs.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

A reward moves backward over repeated experience

Imagine a two-step route: entry → room → terminal, with rewards 0 and 4. Start both nonterminal value estimates at zero, use discount 0.9 and step size 0.5. On the first transition, the room still looks worth zero, so entry does not change. On the second transition, the observed reward moves the room estimate to 2.

Repeat the route. Entry can now use the room estimate: its target is 1.8 and its new value is 0.9. The room moves from 2 to 3. The final reward has influenced an earlier prediction without waiting to compute a complete return for that earlier visit on the second episode.

This is temporal-difference learning, or TD. Sutton’s 1988 paper studies learning from differences between successive predictions; the textbook working draft gives the tabular TD(0) rule used here. The route is an authored example, not a reproduction of either source’s experiments.

Two episodes show a reward moving back to an earlier state. A separate boundary example distinguishes collection cutoff from true termination.
Two episodes show a reward moving back to an earlier state. A separate boundary example distinguishes collection cutoff from true termination.

A sample of a Bellman target

Fix a stationary policy pi in a finite Markov decision process. Let r_pi(s) be its expected immediate reward and P_pi(s,s') its state-transition probabilities. For bounded rewards and discount below 1, its value obeys

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').

Policy evaluation can average over that known transition table. A model-free learner instead observes one reward and one successor. TD(0) substitutes the current successor estimate for its unknown true value:

δ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.

Other state entries stay unchanged. Both terms on the right use the table before this update, including when the next state equals the current state. For a true terminal successor, its continuation value is zero, but the reward received on entering it is still included. Silver’s lecture calls the reward-plus-successor estimate the TD target and its difference from the current estimate the TD error.

Where the bias comes from

Write the target as Y_t. Conditional on the current state and a fixed current table, its difference in expectation from the desired value is

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).

Subtract the Bellman equation to obtain this identity. If the successor estimates are correct, the target is unbiased in this conditional sense. Otherwise their weighted errors propagate into the current target. This is bootstrapping: an estimate helps construct another estimate’s target.

TD is often described as trading some bias for lower variance than a complete Monte Carlo return. That is a useful comparison under suitable estimates and tasks, not an unconditional inequality. For a counterexample, suppose a zero-reward state leads equally often to two zero-reward states that then terminate. Their true values and all complete returns are zero. An arbitrary current table assigns them +100 and −100. At 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.

The target is unbiased here because the two errors cancel in expectation, but it has much greater variance. Bias and variance are different questions. The broad comparison in Silver’s slides should not be read as a theorem covering arbitrary value tables.

Why repeated updates can work

For a step size chosen before the next reward and transition are observed, the conditional mean update is

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).

Thus a noisy transition moves the estimate, on average, toward its fixed-policy Bellman backup. This relationship explains the algorithm; it does not by itself prove convergence. Standard tabular on-policy convergence conditions include suitable sampling of every estimated state, bounded noise moments and per-state step sizes satisfying

∑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.

Here k counts updates of state s, not all global transitions. A positive constant step size fails the second condition and can keep fluctuating. The fixed-policy, Markov and tabular assumptions matter; neural approximators or off-policy data require different analysis. The working draft also distinguishes batch-data solutions from claims about finite online efficiency.

Keep the terminal flag separate from the collection limit

Save the standard-library program as td_prediction.py and run with Python 3.12. step returns a new table and its target/error, leaving the input untouched. replay exposes each transition. train actually interacts with the original arcade under its fixed advance/spin policy.

"""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))

The two deterministic route replays give [0, 2, 0], then [0.9, 3, 0]. A separate one-transition prefix ending in a nonterminal room of value 4 has target 3.6; a true terminal transition with reward 0 has target 0. An external time limit does not justify changing the former into the latter. If the task itself ends at a deadline, remaining time should be represented in the task and its terminal convention.

For the stochastic arcade, seed 31 and 5,000 episodes yield state counts [14816, 24696, 0] and estimates approximately [4.630453, 5.158160, 0]. The program uses step size 0.8 / N(s)^0.6. Exact model references are [360/79, 400/79, 0], calculated outside learning. The estimate at episode 1,000 happens to be closer than at episode 5,000: a sample path need not improve monotonically. These observations are neither a convergence proof nor an error certificate.

A single tabular TD arithmetic update touches one entry. This teaching helper also validates and copies the whole S-entry table, so its actual cost is O(S) per transition. Training retains only selected table snapshots; its working memory is O(S) for a fixed number of snapshots. replay deliberately stores all T intermediate tables, costing O(TS) extra space. The 10,000-step safety budget raises an error if exceeded; it does not report a successfully completed episode.

A changed policy changes the prediction question

TD prediction estimates the policy that produces the data under the stated assumptions. Using a maximum over actions instead of the sampled or policy-averaged continuation changes the update toward a control method. SARSA makes the action dependence explicit; n-step returns delay the bootstrap to include more observed rewards.

Bootstrapping can propagate useful information and mistaken estimates. Bad state representations, insufficient visits, inappropriate step sizes and a wrong termination mask all affect the result. A finite dataset’s repeated batch-TD solution is not the same claim as monotonic progress in one online run. Nor does a decreasing empirical TD error alone certify accurate values in an unknown environment.

Inspect the target before inspecting the learning curve

  1. With a self-transition, old value 2, reward 1, gamma 0.9 and alpha 0.5, what is the new value?

    Answer: The target uses the old value: 1 + 0.9 × 2 = 2.8. The error is 0.8 and the new value is 2.4. Feeding the newly updated value back into the same target would define another computation.

  2. Reproduce the second episode of the opening route after the first gave values [0,2,0].

    Answer: Entry uses target 0 + 0.9 × 2 = 1.8, becoming 0.9. The terminal room transition has target 4, moving room value halfway from 2 to 4, to 3.

  3. Does an unbiased TD target necessarily have lower variance than the full return?

    Answer: No. In the two-successor counterexample, targets are +90 and −90 equally often, so their mean is the correct zero but variance is 8,100. Every complete return is exactly zero.

  4. A simulator resets when a wall-clock budget expires. What should be logged before choosing a bootstrap mask?

    Answer: Record whether the environment truly terminated or collection was merely cut short, plus the final pre-reset observation. A continuing-task cutoff uses that observation’s continuation estimate; the reset observation belongs to a new trajectory.

The original claim has conditions

Sutton 1988 places TD among earlier learning systems and states formal results for special cases. Our reading covers its first two pages, not the full proofs or experiments. The working draft and Silver’s lecture supply the tabular update and prediction comparison used here. This article derives its conditional target identities and uses original small examples; it does not claim that TD always learns faster than Monte Carlo.

Make a prediction, then check

A time limit stops a continuing transition at a nonterminal state. Should its bootstrap value automatically be zero?

Choose one answer

Learning objectives

  • Compute a TD error using the pre-update value table.
  • Explain bootstrapping bias and the separate assumptions required for tabular convergence.

Prerequisites & connections

Explore related knowledge →

References

  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

Version1 · Editorial status: Recorded technical checks completed

View technical check record (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.

  • 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.
  • Four computed SVG variants per topic;12 numeric/geometry tests and36 responsive cases passed. All twelve selected current captures directly viewed; browser inputs bound by SHA before integration. Full article acceptance recorded separately.

Source locations checked:

  • 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.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.