Linear Value Function Approximation
Features, semi-gradient TD and tile coding.
Give a learner a handful of features per state and one step size, and it can estimate the value of every state of a continuous problem, including states it has never visited. This lesson builds linear value-function approximation from its objective: gradient Monte Carlo, which descends it, semi-gradient TD, which does not, the fixed point TD converges to and how far that can be from the best fit, the features that make linear methods work, and semi-gradient SARSA on mountain car.
What you’ll learn
- Define the mean squared value error with its on-policy weighting, and derive gradient Monte Carlo as stochastic gradient descent on it.
- Derive semi-gradient TD(0), and prove that its expected update is not the gradient of any objective.
- Derive the TD fixed point , state when linear TD is stable, and state the bound on its error.
- Build polynomial, Fourier, coarse-coded, tile-coded and radial-basis features, and set a step size for them.
- Apply semi-gradient SARSA to mountain car, and say what is and is not guaranteed in control.
What should the approximation minimize?
With weights and many more states, cannot equal everywhere: making one state more accurate makes others less so. We must say which states matter. The standard answer weights each state by , the fraction of time the policy spends there (its stationary distribution in a continuing task, or the normalized expected number of visits per episode in an episodic one), and minimizes the mean squared value error:
Stochastic gradient descent on one visited state would update
but is what we are trying to learn. Replace it by any target with and the update is still an unbiased stochastic gradient step on : its expected direction is . The return qualifies, which gives gradient Monte Carlo: under the Robbins–Monro step-size conditions it converges to a local minimum of .
In the linear case, with feature vector , the gradient is simply , is a convex quadratic, and gradient Monte Carlo converges to its global minimum: the least-squares regression of returns on features, the solution of .
Semi-gradient TD: a gradient that isn’t one
Bootstrapping uses the target . It depends on , but semi-gradient TD(0) treats it as a constant and differentiates only the estimate:
The target is biased while is wrong, so the update is not an unbiased gradient of . It is not a gradient of anything else either.
Write . With states drawn from and the policy's transitions, the expected linear update is affine in :
Stack the features as rows of , put on the diagonal of , and let be the policy's transition matrix. Then
If for some twice-differentiable , its Jacobian would equal the Hessian , which is symmetric. In the tabular case (), is symmetric exactly when for all pairs, the detailed balance of a reversible chain:
A three-state cycle violates it: probability flows from 1 to 2 but never back. So TD is not descending any objective; it is a stochastic fixed-point iteration for the root of , and its stability must be proved directly.
import numpy as np
def semi_gradient_td0(env, policy, features, d, alpha=0.01, gamma=0.99, episodes=500):
w = np.zeros(d)
for _ in range(episodes):
s, _ = env.reset()
done = False
while not done:
s_next, r, terminated, truncated, _ = env.step(policy(s))
x = features(s)
v_next = 0.0 if terminated else w @ features(s_next) # bootstrap unless terminal
delta = r + gamma * v_next - w @ x # TD error
w += alpha * delta * x # target treated as a constant
s, done = s_next, terminated or truncated
return wLinear semi-gradient TD(0) for a Gymnasium environment. A time-limit truncation still bootstraps from ; only a true termination uses 0. Each step costs .
Which fact shows that linear TD(0)'s expected update is not the negative gradient of any smooth objective?
- is not invertible
- The TD targets are noisy
- is not symmetric in general, while a Hessian always is
- The features may be nonlinear functions of the state
Show the answer
C. is not symmetric in general, while a Hessian always is
A gradient field's Jacobian is a Hessian, hence symmetric. TD's Jacobian is , which is not symmetric unless probability flows balance in both directions. Noise and invertibility are separate questions: gradient Monte Carlo has noisy targets and is still a true stochastic gradient method.
Where linear TD converges, and how good that is
If linear TD converges, the expected update vanishes there, so the limit solves : the TD fixed point
Whether it converges depends on . The mean iteration is stable for small exactly when every eigenvalue of has positive real part, and a convenient sufficient condition is that is positive definite, for . On-policy it is: with stationary for , every column of sums to , and that makes the matrix positive definite (Sutton & Barto, §9.4; the argument is in Divergence: Baird’s Counterexample).
Episodes run end, with reward 1 only on the last transition and , so every true value is 1. Each state is visited once per episode, so is uniform. The single feature is . Compute , where (with after the end) and .
Show the answer
0.5
and , so and the estimates are . Gradient Monte Carlo instead converges to the least-squares fit , with estimates . TD's fixed point has the larger value error, against : it fits a Bellman consistency condition, not the values themselves.
Constructing features
A linear method is only as good as its features: they decide which states generalize to which. Each family below turns a state , a vector of numbers, into a feature vector. Assume each has been rescaled to .
| Features | Definition | Strengths | Weaknesses |
|---|---|---|---|
| State aggregation | One indicator per cell of a partition | Simple; a table of groups | No generalization across cell borders, none within finer detail |
| Polynomials | with : features | Captures interactions such as | Global and badly conditioned; count explodes with |
| Fourier basis | , : features | Smooth functions; as good as or better than polynomial and RBF bases in the experiments of Konidaris, Osentoski & Thomas (2011) | Ringing at discontinuities; same exponential count |
| Coarse coding | Binary features for overlapping regions (circles) containing | Generalization width set by region size | Many features for fine detail |
| Tile coding | offset grids (tilings); exactly one active tile per tiling | Sparse, cheap ( active features), flexible; hashing saves memory | Grid artifacts; still exponential in without hashing or partial tilings |
| Radial basis functions | Smooth, graded generalization | Dense, so more computation; rarely more accurate than tiles in practice |
Two rules of thumb from Sutton & Barto (§9.5–9.6) carry most of the practical weight.
Generalization width versus acuity. With coarse coding, the size of the regions sets how far one update spreads at first; the total number of features sets the finest distinction the approximation can eventually make. Broad features learn fast early and still end up precise if there are enough of them. For tile coding, offsetting the tilings asymmetrically, by multiples of the first odd integers with tilings, a power of 2 and , avoids diagonal artifacts (Miller & Glanz, 1996).
Step size. To learn a target in about presentations of similar feature vectors, set
With tilings every state has exactly active binary features, so and . Dividing by is why tile-coded step sizes are written as fractions such as .
Control: semi-gradient SARSA on mountain car
For control, approximate action values , for example with a separate set of tiles for each action, and act -greedily on them. Semi-gradient SARSA updates toward the next action actually taken:
Mountain car (Sutton & Barto, Example 10.1) has three actions (reverse, coast, forward), reward per step until the car passes , and starts at rest at a random position in . The physics:
semi-gradient SARSA (episodic), linear q(s, a, w) = w · x(s, a)
w ← 0 # optimistic here: every true value is negative
repeat for each episode:
S ← start state; A ← ε-greedy action for q(S, ·, w)
repeat:
take A, observe R and S′
if S′ is terminal:
w ← w + α · (R − q(S, A, w)) · x(S, A)
go to the next episode
A′ ← ε-greedy action for q(S′, ·, w)
δ ← R + γ · q(S′, A′, w) − q(S, A, w)
w ← w + α · δ · x(S, A)
S ← S′; A ← A′With all weights at 0 and every reward , unvisited actions look better than visited ones, which drives systematic exploration even with .
What is guaranteed? For a fixed policy, semi-gradient SARSA is linear TD on state–action features and converges on-policy to the analogous fixed point. When the policy changes with the estimates, the targets keep moving. Gordon (2001) proved that on-policy linear SARSA(0) cannot diverge: its weights converge to a bounded region, inside which they may keep oscillating ("chattering") rather than settle. Off-policy control is worse: linear Q-learning combines approximation, bootstrapping and off-policy updates, and counterexamples in the style of Baird's show it can diverge (The Deadly Triad).
Key takeaways
- Linear approximation minimizes weighted by the on-policy distribution; gradient Monte Carlo is true SGD on it and converges to the least-squares fit of returns.
- Semi-gradient TD ignores the target's dependence on ; its expected update is not a gradient field because is not symmetric.
- On-policy, is positive definite and linear TD converges to , whose value error is at most times the best possible.
- Features decide generalization: polynomial and Fourier bases suit smooth functions, tile coding gives sparse local features with for tilings.
- Semi-gradient SARSA solves mountain car with tile coding; in control, on-policy linear SARSA stays bounded but may chatter, and off-policy linear Q-learning can diverge.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Why is TD(0) with function approximation called a semi-gradient method?
- It updates only half of the weights at each step
- It differentiates the estimate but treats the bootstrapped target, which also depends on , as a constant
- It uses half the step size of gradient Monte Carlo
- It follows the gradient of only in expectation
Show the answer
B. It differentiates the estimate but treats the bootstrapped target, which also depends on , as a constant
The target depends on , and the full gradient of the squared TD error would include . Dropping that term gives the semi-gradient update, which is not the gradient of any objective but, on-policy with linear features, converges to the TD fixed point.
On-policy with , the bound allows TD's value error to be at most how many times the best achievable?
Show the answer
C.
. The factor grows like the effective horizon, reaching 100 at . In norm form the sharper factor is at , so the squared error ratio is at most about 5.3.
You use tile coding with 16 tilings and want each prediction to move most of the way to its target after about 10 presentations of similar states. Which step size does the rule give?
Show the answer
C.
Each state activates exactly one binary tile per tiling, so , and . With instead, a single update would move the prediction all the way to the target.
A full order-3 Fourier basis is built over a 4-dimensional state. How many features does it have?
Show the answer
D.
Each feature is indexed by a vector , so there are features, the same count as a full order-3 polynomial basis. The exponential growth in the dimension is why one often keeps only low-order interactions.
Go deeper
- The Projected Bellman Equation & LSTD · TD’s fixed point, least-squares TD, and how far that fixed point can be from the best fit.
- Representation Learning for RL · Auxiliary tasks, bisimulation and what makes a good state representation.
- Provably Efficient RL with Features · Linear MDPs, LSVI-UCB and the lower bounds that limit function approximation.
Further reading
- R. S. Sutton & A. G. Barto, Reinforcement Learning: An Introduction, ch. 9–10 (MIT Press, 2nd ed., 2018).
- J. N. Tsitsiklis & B. Van Roy, "An analysis of temporal-difference learning with function approximation", IEEE Transactions on Automatic Control 42(5) (1997).
- G. Konidaris, S. Osentoski & P. Thomas, "Value function approximation in reinforcement learning using the Fourier basis", AAAI (2011).
- G. J. Gordon, "Reinforcement learning with function approximation converges to a region", Advances in Neural Information Processing Systems 13 (2001).