Week 06 · Temporal-difference learning
Compare learning from a one-step target with learning from a complete return.
← Week 5 · Subject contents · Week 7 →
Compare learning from a one-step target with learning from a complete return.
Work through the problem
TD(0) updates V(s) toward r+γV(s′) after each transition. Monte Carlo uses the realized return at episode end. TD bootstraps from its current estimate of the successor. This can reduce variance at the cost of depending on that estimate.
A symmetric random walk starts at state 3 on a line with absorbing endpoints 0 and 6. The right endpoint pays 1 and the left pays 0. At γ=1, interior values solve vᵢ=(vᵢ₋₁+vᵢ₊₁)/2 with those endpoints, giving vᵢ=i/6. Use this exact curve to compare learning traces.
TD and Monte Carlo use different targets.
Run the Python lab
import numpy as np
rng = np.random.default_rng(16)
td,mc = np.full(7,.5),np.full(7,.5)
td[[0,6]]=mc[[0,6]]=0
exact = np.arange(1,6)/6
curves = {"TD":[],"Monte Carlo":[]}
for _ in range(150):
s,path = 3,[]
while s not in (0,6):
t = s+rng.choice([-1,1])
r = int(t==6)
td[s] += .08*(r+td[t]-td[s])
path.append(s)
s=t
for a in set(path):
mc[a] += .08*(int(s==6)-mc[a])
for label,v in [("TD",td),("Monte Carlo",mc)]:
curves[label].append(np.sqrt(np.mean((v[1:6]-exact)**2)))
print("Exact:",exact.round(2))
print("Final TD and Monte Carlo RMSE:",[round(v[-1],3) for v in curves.values()])
Output from the lab
Exact: [0.17 0.33 0.5 0.67 0.83]
Final TD and Monte Carlo RMSE: [np.float64(0.049), np.float64(0.121)]
Practice
- Why are endpoint table values zero if the right endpoint pays 1?
Check your reasoning
- The reward arrives on entry. There are no subsequent rewards after termination.