Value function approximation and the deadly triad
Study value-function approximation, projected Bellman equations, LSTD and the deadly triad, including gradient TD and fitted Q iteration.
After this lesson you can
- Explain feature construction and semi-gradient updates.
- Derive the projected Bellman fixed point and its on-policy contraction.
- Construct and solve empirical LSTD equations.
- Analyze off-policy instability and the assumptions of gradient TD.
- Compare fitted Q iteration and least-squares policy iteration.
Before you start
An update affecting many states
In a table, updating leaves other entries intact. But a car climbing a hill can be in innumerable positions and velocities: we cannot wait to visit each pair exactly. An approximate function shares parameters across similar states. Updating one state informs its neighbors, although it can also worsen their predictions.
Value function approximation replaces a table with or . In the linear case , with features . Choosing them determines representable values. A representation that generalizes well is an assumption about the task, not an automatic property of every flexible function.
Preparing Mountain Car.
One way of constructing features is tile coding: multiple grids shift their boundaries over the position–velocity plane. Each activates a tile for the observed state; the feature is a sparse indicator vector. An update changes weights of active tiles and thus the values of states sharing them. More grids smooth dependence on one boundary but also change update scale. Control uses separate parameters per action or features including action. The number of active tiles matters when choosing .
What are we trying to minimize?
If is a distribution over states, the mean squared value error is
The best representable value depends on both features and : a state given little weight by matters little for this objective. Generally is unknown, so we cannot directly use its exact gradient. An observed complete return is a possible sample of the target under suitable conditions; TD instead uses a one-step prediction.
Semi-gradient TD freezes the target when differentiating:
For linear features, . Semi-gradient SARSA uses the same idea with state–action features and the next action chosen by the behavior policy. True termination cancels bootstrapping; an external cutoff does not make it zero. The target also depends on , but the semi-gradient does not differentiate that dependence.
Thus TD is not generally gradient descent on squared Bellman error or value error. Nor is it true that its expected field is never the gradient of any function: in a single state with feature one, reward and , field is the negative gradient of . In higher dimensions, linear field is the Euclidean gradient of a quadratic if is symmetric; TD does not guarantee that symmetry.
The projected Bellman equation
Now consider a finite chain under a fixed policy, with stationary distribution positive on considered states, matrix , expected rewards and . Let , be the feature matrix and the orthogonal projection onto the column space of in norm . If features have full rank, is invertible.
The projected fixed point satisfies
The second equation says the Bellman residual is orthogonal to the representable space, not that it is zero in every state. Under these assumptions is invertible. The result is the root of the expected on-policy TD update; convergence of sampled iterations also requires conditions on the chain and learning steps.
Preparing geometry.
The geometric reason for on-policy stability is specific. By Jensen, ; weighting by and using gives . Orthogonal projection also does not expand the norm. Thus is a contraction with modulus at most .
Since , projection orthogonality and contraction give the bound
Indeed, decompose into orthogonal error and representable term . They are orthogonal, and the second has norm at most . The best projection of and the TD fixed point need not coincide. For convergence analysis and assumptions, see Tsitsiklis and Van Roy.
Solving the same fixed point by least squares
LSTD accumulates feature products instead of choosing an update rate for each transition. Given samples , construct
For a true terminal, take . If the matrix is singular there is no unique solution; adding regularization or choosing a least-squares solution changes the solved equation and must be declared. Under suitable on-policy sampling, a law of large numbers and invertibility of the unregularized limit, normalized sums estimate and . This does not imply that every off-policy or regularized dataset converges to the same fixed point.
LSPI extends the idea to action values: approximately evaluate a policy with LSTDQ, improve the policy and reuse data. Transitions must cover what is needed for informative evaluation; the inversion can be ill-conditioned and approximate improvement does not guarantee monotonic progress in every batch. Lagoudakis and Parr present the method.
The deadly triad and Baird’s example
The deadly triad combines function approximation, bootstrapping and off-policy learning. Their combination diverges in some problems, even with a linear function. This does not mean every instance with those ingredients diverges, or that removing one part solves every practical difficulty.
Preparing the counterexample.
Baird’s counterexample uses seven states and shared features to construct an unstable off-policy update. Target and behavior policies induce different distributions: the distribution used in projection need not be stationary for the target operator, so the preceding contraction proof no longer applies. Importance correction can make the average represent the target policy, but does not itself make projection contractive under the behavior distribution. Exact features, probabilities, weights and steps are specified in the figure and lab; an isolated plot from one finite run does not prove a theorem.
The difficulty also reaches control: linear Q-learning variants can diverge in this counterexample. The evaluation proof just seen and a control agent are different updates; Maei and colleagues study the control example and alternatives.
A common parameterization has eight weights for seven state values, so the feature matrix lacks full column rank. Weights can contain directions that change no predicted value. A weight norm alone therefore does not describe all value error, and results requiring invertible should not automatically be applied or each weight required to converge to zero.
Three different errors and gradient corrections
Value error compares with . Squared Bellman error compares with . Projected Bellman error compares with . One being small does not guarantee the others are, except under additional assumptions and bounds.
For linear approximation and invertible , mean squared projected Bellman error can be written . Gradient TD methods use an auxiliary vector to estimate terms arising when differentiating this quantity. TDC is a two-timescale variant; its guarantees require, among other conditions, coverage, suitable features and matrices, and appropriate steps. Renaming TD to TDC does not ensure stability in every configuration. See Sutton and colleagues and later analysis by Ghiassian and colleagues.
For example, with a behavior transition, features and importance ratio , one one-step TDC version uses previous values of and auxiliary in both updates:
The formula assumes target policy coverage by behavior and on true termination. The auxiliary estimates a correction, not an independent second value table; steps and rank conditions matter for the theoretical result.
Another family, emphatic TD, changes update weights using emphasis dependent on trajectory following, interest in states and importance ratios. The resulting weighting can recover stability properties not provided by behavior distribution alone. Its guarantees also require coverage, feature and step assumptions; see Sutton, Mahmood and White.
Another difficulty arises when minimizing unprojected Bellman error from samples. The gradient of a squared conditional expectation contains a product of two expectations depending on the same state; reusing one transition for both factors can introduce bias. Obtaining two independent next states from the same state and action is the double-sampling problem, and is not always possible with collected data. Gradient TD methods address a different objective and have their own assumptions.
Fitting a function by iteration
Fitted Q iteration turns each backup into supervised regression. Freeze and compute for each batch transition
and fit a new regressor to predict from . An external cutoff does not itself remove continuation. Trees, linear regression and networks give different families; evaluate the resulting policy on separate trajectories and do not confuse batch error with out-of-sample performance. Ernst, Geurts and Wehenkel study tree-based batch methods and guarantees under specific conditions, which do not automatically transfer to every ExtraTrees implementation.
In DQN, replay and target networks help control correlation among samples and target movement. These are design choices, not a general proof of convergence against the deadly triad. A dataset lacking coverage cannot reliably reveal consequences of actions it never contains.
Labs
The first experiment implements Mountain Car with state (posición, velocidad), three actions and eight shifted tilings. Each state–action pair activates one tile per layer; explicit dictionary keys avoid hash collisions. The 200-step external cutoff stops sampling, but only reaching the goal removes bootstrapping. This short run checks the mechanism, not a promise that the policy already solves the environment.
import math
import random
def tiles(position,velocity,action):
return [(action,t,math.floor((position+1.2)/.22+t/8),
math.floor((velocity+.07)/.014+((3*t)%8)/8)) for t in range(8)]
def q_value(weights,state,action):
return sum(weights.get(key,0.0) for key in tiles(*state,action))
def mountain_step(state,action):
position,velocity=state
velocity=max(-.07,min(.07,velocity+(action-1)*.001-.0025*math.cos(3*position)))
position=max(-1.2,min(.6,position+velocity))
if position<=-1.2 and velocity<0: velocity=0.0
return (position,velocity),-1.0,position>=.5
def select(weights,state,epsilon,rng):
if rng.random()<epsilon: return rng.randrange(3)
values=[q_value(weights,state,a) for a in range(3)]
maximum=max(values)
return rng.choice([a for a,v in enumerate(values) if v==maximum])
def train_car(seed,episodes=20,epsilon=.1,alpha=.1):
rng=random.Random(seed); weights={}; lengths=[]; successes=0
for _ in range(episodes):
state=(rng.uniform(-.6,-.4),0.0)
action=select(weights,state,epsilon,rng)
for t in range(200):
nxt,reward,terminated=mountain_step(state,action)
next_action=select(weights,nxt,epsilon,rng) if not terminated else None
target=reward if terminated else reward+q_value(weights,nxt,next_action)
delta=target-q_value(weights,state,action)
for key in tiles(*state,action): weights[key]=weights.get(key,0.0)+alpha/8*delta
if terminated:
successes+=1; break
if t==199: break # truncamiento externo: el objetivo ya incluyó bootstrap
state,action=nxt,next_action
lengths.append(t+1)
return weights,lengths,successes
assert len(tiles(-.5,0,1))==len(set(tiles(-.5,0,1)))==8
assert mountain_step((-1.2,-.07),0)[0]==(-1.2,0.0)
weights,lengths,successes=train_car(1201)
print('Mountain Car: episodios',len(lengths),'éxitos',successes,
'pasos medios',round(sum(lengths)/len(lengths),2),'teselas visitadas',len(weights))LSTD constructs a linear system from transitions. The example has two states, fixed policy, stationary distribution (0,6; 0,4), independent features [1,s] and discount 0,9. We compare the theoretical solution with one sample from the same chain. Regularization applies only if requested and changes the system solved; here it is zero.
import random
import numpy as np
P=np.array([[.8,.2],[.3,.7]])
r=np.array([1.,0.]); gamma=.9
Phi=np.array([[1.,0.],[1.,1.]])
D=np.diag([.6,.4])
A=Phi.T@D@(Phi-gamma*P@Phi)
b=Phi.T@D@r
theta_true=np.linalg.solve(A,b)
value_true=np.linalg.solve(np.eye(2)-gamma*P,r)
assert np.allclose(Phi@theta_true,value_true,atol=1e-11,rtol=0)
def lstd(phi,rewards,next_phi,gamma,reg=0.0):
A=phi.T@(phi-gamma*next_phi)/len(phi)+reg*np.eye(phi.shape[1])
b=phi.T@rewards/len(phi)
return np.linalg.solve(A,b),A,b
rng=random.Random(1202); state=1 if rng.random()<.4 else 0
current=[]; following=[]; rewards=[]
for _ in range(4000):
nxt=0 if rng.random()<P[state,0] else 1
current.append(Phi[state]); following.append(Phi[nxt]); rewards.append(r[state])
state=nxt
theta,As,bs=lstd(np.asarray(current),np.asarray(rewards),np.asarray(following),gamma)
assert np.allclose(As@theta,bs,atol=1e-10,rtol=0)
print('θ poblacional',np.round(theta_true,6),'θ LSTD muestral',np.round(theta,6),
'error de valor',round(float(np.linalg.norm(Phi@theta-value_true)),6))Baird’s counterexample has seven states and eight features: the six upper are (2eᵢ+e₈)/√5 and the lower (e₇+2e₈)/√5. The target policy always chooses the solid transition to the lower state; behavior chooses it with probability 1/7 and distributes the rest uniformly among the six upper states. Rewards are zero and γ=0,99. We calculate exact expected updates under the uniform behavior distribution: these are not a sampled trajectory. Eight features in seven states make the covariance matrix singular, so a theorem requiring full rank does not automatically apply.
import numpy as np
import math
Phi=np.zeros((7,8))
for s in range(6): Phi[s,s]=2; Phi[s,7]=1
Phi[6,6]=1; Phi[6,7]=2
Phi/=math.sqrt(5)
gamma=.99; C=Phi.T@Phi/7
initial=np.ones(8); initial[6]=10
def mean_step(w,h,alpha,beta,corrected):
delta=gamma*(Phi[6]@w)-Phi@w
td=Phi.T@delta/7
if corrected:
# E_b[ρ φ'(φᵀh)] = φ_sólido · E_b[φᵀh].
correction=gamma*Phi[6]*float(np.mean(Phi@h))
return w+alpha*(td-correction),h+beta*(td-C@h)
return w+alpha*td,h
print('Rango de C',np.linalg.matrix_rank(C),'de',len(initial),'dimensiones')
for label,corrected in [('TD',False),('TDC',True)]:
w=initial.copy(); h=np.zeros(8)
for t in range(10001):
if t in (0,100,1000,10000):
print(label,'paso',t,'norma pesos',round(float(np.linalg.norm(w)),6),
'RMS valor',round(float(np.sqrt(np.mean((Phi@w)**2))),6))
if t<10000: w,h=mean_step(w,h,.01,.05,corrected)True value is zero, but a null direction of Φ can leave nonzero parameters without changing values. Hence both predictions and weight norm are shown. TDC needs coverage and step and rank conditions for its guarantees; this finite expected calculation does not prove general convergence or independence of the two estimates.
Fitted Q iteration freezes the previous model before constructing targets and then fits trees. We compare linear LSPI on the same sample of 600 transitions of a pendulum with actions −2, 0, 2. Initial evaluation positions use another seed. The 50-step horizon is only for evaluation: dynamics are continuing and training targets retain bootstrapping. See Ernst, Geurts and Wehenkel; the guarantee of their totally random tree construction is not automatically attributed to ExtraTrees.
import numpy as np
from sklearn.ensemble import ExtraTreesRegressor
actions=np.array([-2.,0.,2.]); discount=.95
def angle_normalize(theta):
return (theta+np.pi)%(2*np.pi)-np.pi
def pendulum_step(state,action):
theta=state[:,0]; velocity=state[:,1]; torque=actions[action]
reward=-(angle_normalize(theta)**2+.1*velocity**2+.001*torque**2)
next_velocity=np.clip(velocity+(15*np.sin(theta)+3*torque)*.05,-8,8)
next_theta=angle_normalize(theta+next_velocity*.05)
return np.column_stack((next_theta,next_velocity)),reward
def sa_features(state,action):
theta=state[:,0]; velocity=state[:,1]
base=np.column_stack((np.ones(len(state)),np.sin(theta),np.cos(theta),velocity/8,(velocity/8)**2))
out=np.zeros((len(state),15))
for a in range(3):
selected=action==a; out[selected,5*a:5*(a+1)]=base[selected]
return out
def greedy_linear(state,theta):
values=np.column_stack([sa_features(state,np.full(len(state),a))@theta for a in range(3)])
return np.argmax(values,axis=1)
def tree_q(model,state,action):
return model.predict(np.column_stack((state,actions[action])))
rng=np.random.default_rng(1203); N=600
states=np.column_stack((rng.uniform(-np.pi,np.pi,N),rng.uniform(-8,8,N)))
chosen=rng.integers(0,3,N)
next_states,rewards=pendulum_step(states,chosen)
inputs=np.column_stack((states,actions[chosen]))
model=None
for iteration in range(5):
if model is None: targets=rewards.copy()
else:
next_q=np.column_stack([tree_q(model,next_states,np.full(N,a)) for a in range(3)])
targets=rewards+discount*np.max(next_q,axis=1)
model=ExtraTreesRegressor(n_estimators=6,max_depth=8,min_samples_leaf=5,
random_state=1204+iteration,n_jobs=1)
model.fit(inputs,targets)
features=sa_features(states,chosen)
theta=np.zeros(15)
for iteration in range(5):
next_action=greedy_linear(next_states,theta)
next_features=sa_features(next_states,next_action)
A=features.T@(features-discount*next_features)/N+1e-3*np.eye(15)
b=features.T@rewards/N
theta=np.linalg.solve(A,b)
def rollout(method,seed,episodes=12,horizon=50):
rng=np.random.default_rng(seed)
state=np.column_stack((rng.uniform(-np.pi,np.pi,episodes),rng.uniform(-1,1,episodes)))
total=np.zeros(episodes); factor=1.0
for _ in range(horizon):
if method=='fqi':
q=np.column_stack([tree_q(model,state,np.full(episodes,a)) for a in range(3)])
action=np.argmax(q,axis=1)
else: action=greedy_linear(state,theta)
state,reward=pendulum_step(state,action)
total+=factor*reward; factor*=discount
return float(np.mean(total)),float(np.std(total)),total
fqi_mean,fqi_std,fqi_returns=rollout('fqi',1205)
lspi_mean,lspi_std,lspi_returns=rollout('lspi',1205)
assert np.all(np.isfinite(fqi_returns)) and np.all(np.isfinite(lspi_returns))
print('Transiciones train',N,'evaluación independiente',len(fqi_returns),'horizonte',50)
print('FQI retorno descontado',round(fqi_mean,4),'desviación',round(fqi_std,4))
print('LSPI retorno descontado',round(lspi_mean,4),'desviación',round(lspi_std,4))Initial evaluation conditions are common to both methods and distinct from the fitting sample; the deviation describes those 12 returns, not calibrated population uncertainty. Changing representation, sample or seed can change the comparison. Regularization 10⁻³I changes LSPI’s system; it does not guarantee improved conditioning or invertibility of an arbitrary matrix. Equality with an unregularized equation is not assumed.
Exercises
Step 1 of 3. How is the norm of P applied to x bounded?
Step 1 of 3. What is the zero mean TD-update condition?
def lstd(features, rewards, next_features, gamma, reg):
pass
import numpy as np
P=np.array([[.8,.2],[.3,.7]])
gamma=.9
d=np.diag([.6,.4])
phi=np.array([[1.],[2.]])
r=np.array([0.,1.])
A=phi.T@d@(np.eye(2)-gamma*P)@phi
b=phi.T@d@r
v=np.linalg.solve(np.eye(2)-gamma*P,r)
w_td=np.linalg.solve(A,b)
w_projection=np.linalg.solve(phi.T@d@phi,phi.T@d@v)
print('A',A[0,0],'b',b[0],'TD',w_td[0])
print('Valor verdadero',v,'proyección',w_projection[0])