Simple Algorithm
Reinforcement Learning · Bootstrapping · 22 min

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 wTD=A−1b\mathbf w_{\mathrm{TD}}=\mathbf A^{-1}\mathbf b, 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 dd weights and many more states, v^(s,w)\hat v(s,\mathbf w) cannot equal Vπ(s)V^\pi(s) everywhere: making one state more accurate makes others less so. We must say which states matter. The standard answer weights each state by μ(s)\mu(s), 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:

VE‾(w)=∑sμ(s) [Vπ(s)−v^(s,w)]2\overline{\mathrm{VE}}(\mathbf w)=\sum_{s}\mu(s)\,\big[V^\pi(s)-\hat v(s,\mathbf w)\big]^2
Errors in states the policy rarely visits are cheap, errors in its usual haunts expensive. The choice of weighting will matter again below: linear TD is guaranteed stable only when updates are distributed according to μ\mu.

Stochastic gradient descent on one visited state St∼μS_t\sim\mu would update

wt+1=wt+α [Vπ(St)−v^(St,wt)] ∇v^(St,wt),\mathbf w_{t+1}=\mathbf w_t+\alpha\,\big[V^\pi(S_t)-\hat v(S_t,\mathbf w_t)\big]\,\nabla\hat v(S_t,\mathbf w_t),

but Vπ(St)V^\pi(S_t) is what we are trying to learn. Replace it by any target UtU_t with E[Ut∣St]=Vπ(St)\E[U_t\mid S_t]=V^\pi(S_t) and the update is still an unbiased stochastic gradient step on VE‾/2\overline{\mathrm{VE}}/2: its expected direction is −12∇VE‾(wt)-\tfrac12\nabla\overline{\mathrm{VE}}(\mathbf w_t). The return Ut=GtU_t=G_t qualifies, which gives gradient Monte Carlo: under the Robbins–Monro step-size conditions it converges to a local minimum of VE‾\overline{\mathrm{VE}}.

In the linear case, v^(s,w)=w⊤x(s)\hat v(s,\mathbf w)=\mathbf w^\top\mathbf x(s) with feature vector x(s)∈Rd\mathbf x(s)\in\R^d, the gradient is simply x(s)\mathbf x(s), VE‾\overline{\mathrm{VE}} is a convex quadratic, and gradient Monte Carlo converges to its global minimum: the least-squares regression of returns on features, the solution of E[xx⊤] w=E[G x]\E[\mathbf x\mathbf x^\top]\,\mathbf w=\E[G\,\mathbf x].

Semi-gradient TD: a gradient that isn’t one

Bootstrapping uses the target Ut=Rt+1+γ v^(St+1,wt)U_t=R_{t+1}+\gamma\,\hat v(S_{t+1},\mathbf w_t). It depends on w\mathbf w, but semi-gradient TD(0) treats it as a constant and differentiates only the estimate:

wt+1=wt+α δt ∇v^(St,wt),δt=Rt+1+γ v^(St+1,wt)−v^(St,wt).\mathbf w_{t+1}=\mathbf w_t+\alpha\,\delta_t\,\nabla\hat v(S_t,\mathbf w_t),\qquad \delta_t=R_{t+1}+\gamma\,\hat v(S_{t+1},\mathbf w_t)-\hat v(S_t,\mathbf w_t).

The target is biased while v^\hat v is wrong, so the update is not an unbiased gradient of VE‾\overline{\mathrm{VE}}. It is not a gradient of anything else either.

DerivationLinear TD’s expected update is not a gradient field
  1. E[δtxt]=E[Rt+1xt]−E[xt(xt−γxt+1)⊤]w=b−Aw\E[\delta_t\mathbf x_t]=\E\big[R_{t+1}\mathbf x_t\big]-\E\big[\mathbf x_t(\mathbf x_t-\gamma\mathbf x_{t+1})^\top\big]\mathbf w=\mathbf b-\mathbf A\mathbf w

    Write xt=x(St)\mathbf x_t=\mathbf x(S_t). With states drawn from μ\mu and the policy's transitions, the expected linear update is affine in w\mathbf w:

  2. A=∑sμ(s) x(s)(x(s)−γ∑s′Pπ(s,s′) x(s′)) ⁣⊤=X⊤D (I−γPπ) X\mathbf A=\sum_s\mu(s)\,\mathbf x(s)\Big(\mathbf x(s)-\gamma\sum_{s'}P^\pi(s,s')\,\mathbf x(s')\Big)^{\!\top}=\mathbf X^\top\mathbf D\,(\mathbf I-\gamma P^\pi)\,\mathbf X

    Stack the features as rows of X∈R∣S∣×d\mathbf X\in\R^{|\mathcal S|\times d}, put μ\mu on the diagonal of D\mathbf D, and let PπP^\pi be the policy's transition matrix. Then

  3. A symmetric  ⟺  DPπ=(DPπ)⊤\mathbf A\ \text{symmetric}\iff\mathbf D P^\pi=(\mathbf D P^\pi)^\top

    If b−Aw=−∇J(w)\mathbf b-\mathbf A\mathbf w=-\nabla J(\mathbf w) for some twice-differentiable JJ, its Jacobian −A-\mathbf A would equal the Hessian −∇2J-\nabla^2J, which is symmetric. In the tabular case (X=I\mathbf X=\mathbf I), A=D−γDPπ\mathbf A=\mathbf D-\gamma\mathbf DP^\pi is symmetric exactly when μ(s)Pπ(s,s′)=μ(s′)Pπ(s′,s)\mu(s)P^\pi(s,s')=\mu(s')P^\pi(s',s) for all pairs, the detailed balance of a reversible chain:

  4. μ(1)Pπ(1,2)=13≠0=μ(2)Pπ(2,1)\mu(1)P^\pi(1,2)=\tfrac13\ne0=\mu(2)P^\pi(2,1)

    A three-state cycle 1→2→3→11\to2\to3\to1 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 b−Aw=0\mathbf b-\mathbf A\mathbf w=\mathbf 0, and its stability must be proved directly.

python
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 w

Linear semi-gradient TD(0) for a Gymnasium environment. A time-limit truncation still bootstraps from v^(St+1)\hat v(S_{t+1}); only a true termination uses 0. Each step costs O(d)\order{d}.

Check your understanding

Which fact shows that linear TD(0)'s expected update b−Aw\mathbf b-\mathbf A\mathbf w is not the negative gradient of any smooth objective?

  1. A\mathbf A is not invertible
  2. The TD targets are noisy
  3. A\mathbf A is not symmetric in general, while a Hessian always is
  4. The features may be nonlinear functions of the state
Show the answer

C. A\mathbf A is not symmetric in general, while a Hessian always is

A gradient field's Jacobian is a Hessian, hence symmetric. TD's Jacobian is −A=−X⊤D(I−γPπ)X-\mathbf A=-\mathbf X^\top\mathbf D(\mathbf I-\gamma P^\pi)\mathbf X, 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 Aw=b\mathbf A\mathbf w=\mathbf b: the TD fixed point

wTD=A−1b.\mathbf w_{\mathrm{TD}}=\mathbf A^{-1}\mathbf b.

Whether it converges depends on A\mathbf A. The mean iteration w←(I−αA)w+αb\mathbf w\leftarrow(\mathbf I-\alpha\mathbf A)\mathbf w+\alpha\mathbf b is stable for small α\alpha exactly when every eigenvalue of A\mathbf A has positive real part, and a convenient sufficient condition is that A\mathbf A is positive definite, y⊤Ay>0\mathbf y^\top\mathbf A\mathbf y>0 for y≠0\mathbf y\ne\mathbf 0. On-policy it is: with μ\mu stationary for PπP^\pi, every column of D(I−γPπ)\mathbf D(\mathbf I-\gamma P^\pi) sums to (1−γ)μ(s)>0(1-\gamma)\mu(s)>0, and that makes the matrix positive definite (Sutton & Barto, §9.4; the argument is in Divergence: Baird’s Counterexample).

Predict before you look

Episodes run 1→2→3→1\to2\to3\to end, with reward 1 only on the last transition and γ=1\gamma=1, so every true value is 1. Each state is visited once per episode, so μ\mu is uniform. The single feature is x(s)=sx(s)=s. Compute wTD=b/Aw_{\mathrm{TD}}=b/A, where A=13∑sx(s)(x(s)−x(s′))A=\tfrac13\sum_s x(s)\big(x(s)-x(s')\big) (with x=0x=0 after the end) and b=13∑sx(s) r(s)b=\tfrac13\sum_s x(s)\,r(s).

Show the answer

0.5

A=13[1(1−2)+2(2−3)+3(3−0)]=13(−1−2+9)=2A=\tfrac13\big[1(1-2)+2(2-3)+3(3-0)\big]=\tfrac13(-1-2+9)=2 and b=13(3⋅1)=1b=\tfrac13(3\cdot1)=1, so wTD=12w_{\mathrm{TD}}=\tfrac12 and the estimates are (0.5, 1, 1.5)(0.5,\,1,\,1.5). Gradient Monte Carlo instead converges to the least-squares fit w=1+2+31+4+9=37≈0.43w=\frac{1+2+3}{1+4+9}=\tfrac37\approx0.43, with estimates (0.43, 0.86, 1.29)(0.43,\,0.86,\,1.29). TD's fixed point has the larger value error, 16\tfrac16 against 17\tfrac17: 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 s=(s1,…,sk)s=(s_1,\dots,s_k), a vector of kk numbers, into a feature vector. Assume each sjs_j has been rescaled to [0,1][0,1].

FeaturesDefinitionStrengthsWeaknesses
State aggregationOne indicator per cell of a partitionSimple; a table of groupsNo generalization across cell borders, none within finer detail
Polynomialsxi(s)=∏j=1ksjcijx_i(s)=\prod_{j=1}^ks_j^{c_{ij}} with cij∈{0,…,n}c_{ij}\in\{0,\dots,n\}: (n+1)k(n+1)^k featuresCaptures interactions such as s1s2s_1s_2Global and badly conditioned; count explodes with kk
Fourier basisxi(s)=cos⁡(π ci⊤s)x_i(s)=\cos(\pi\,\mathbf c_i^\top s), ci∈{0,…,n}k\mathbf c_i\in\{0,\dots,n\}^k: (n+1)k(n+1)^k featuresSmooth 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 codingBinary features for overlapping regions (circles) containing ssGeneralization width set by region sizeMany features for fine detail
Tile codingnn offset grids (tilings); exactly one active tile per tilingSparse, cheap (nn active features), flexible; hashing saves memoryGrid artifacts; still exponential in kk without hashing or partial tilings
Radial basis functionsxi(s)=exp⁡ ⁣(−∥s−ci∥2/2σi2)x_i(s)=\exp\!\big(-\norm{s-\mathbf c_i}^2/2\sigma_i^2\big)Smooth, graded generalizationDense, so more computation; rarely more accurate than tiles in practice
For the Fourier basis, Konidaris et al. suggest a step size per feature, αi=α/∥ci∥\alpha_i=\alpha/\norm{\mathbf c_i} (and α\alpha for ci=0\mathbf c_i=\mathbf 0), so high-frequency features move less.

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 (1,3,5,…,2k−1)(1,3,5,\dots,2k-1) with nn tilings, nn a power of 2 and n≥4kn\ge4k, avoids diagonal artifacts (Miller & Glanz, 1996).

Step size. To learn a target in about τ\tau presentations of similar feature vectors, set

α=(τ E[x⊤x])−1.\alpha=\big(\tau\,\E[\mathbf x^\top\mathbf x]\big)^{-1}.

With nn tilings every state has exactly nn active binary features, so x⊤x=n\mathbf x^\top\mathbf x=n and α=1/(τn)\alpha=1/(\tau n). Dividing by nn is why tile-coded step sizes are written as fractions such as 0.5/80.5/8.

Control: semi-gradient SARSA on mountain car

For control, approximate action values q^(s,a,w)=w⊤x(s,a)\hat q(s,a,\mathbf w)=\mathbf w^\top\mathbf x(s,a), for example with a separate set of tiles for each action, and act ε\varepsilon-greedily on them. Semi-gradient SARSA updates toward the next action actually taken:

w←w+α [Rt+1+γ q^(St+1,At+1,w)−q^(St,At,w)] x(St,At).\mathbf w\leftarrow\mathbf w+\alpha\,\big[R_{t+1}+\gamma\,\hat q(S_{t+1},A_{t+1},\mathbf w)-\hat q(S_t,A_t,\mathbf w)\big]\,\mathbf x(S_t,A_t).

Mountain car (Sutton & Barto, Example 10.1) has three actions At∈{−1,0,+1}A_t\in\{-1,0,+1\} (reverse, coast, forward), reward −1-1 per step until the car passes x=0.5x=0.5, and starts at rest at a random position in [−0.6,−0.4)[-0.6,-0.4). The physics:

x˙t+1=bound⁡[x˙t+0.001 At−0.0025cos⁡(3xt)],xt+1=bound⁡[xt+x˙t+1]\dot x_{t+1}=\operatorname{bound}\big[\dot x_t+0.001\,A_t-0.0025\cos(3x_t)\big],\qquad x_{t+1}=\operatorname{bound}\big[x_t+\dot x_{t+1}\big]
Position is clipped to [−1.2,0.5][-1.2,0.5] and velocity to [−0.07,0.07][-0.07,0.07]; hitting the left wall resets the velocity to 0. Gravity (0.0025cos⁡3x0.0025\cos 3x) beats the engine (0.0010.001) on the steep slope, so the car must first back up the left hill.
text
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 −1-1, unvisited actions look better than visited ones, which drives systematic exploration even with ε=0\varepsilon=0.

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 VE‾\overline{\mathrm{VE}} 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 w\mathbf w; its expected update b−Aw\mathbf b-\mathbf A\mathbf w is not a gradient field because A=X⊤D(I−γPπ)X\mathbf A=\mathbf X^\top\mathbf D(\mathbf I-\gamma P^\pi)\mathbf X is not symmetric.
  • On-policy, A\mathbf A is positive definite and linear TD converges to wTD=A−1b\mathbf w_{\mathrm{TD}}=\mathbf A^{-1}\mathbf b, whose value error is at most 1/(1−γ)1/(1-\gamma) times the best possible.
  • Features decide generalization: polynomial and Fourier bases suit smooth functions, tile coding gives sparse local features with α=1/(τn)\alpha=1/(\tau n) for nn 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.

Question 1

Why is TD(0) with function approximation called a semi-gradient method?

  1. It updates only half of the weights at each step
  2. It differentiates the estimate v^(St,w)\hat v(S_t,\mathbf w) but treats the bootstrapped target, which also depends on w\mathbf w, as a constant
  3. It uses half the step size of gradient Monte Carlo
  4. It follows the gradient of VE‾\overline{\mathrm{VE}} only in expectation
Show the answer

B. It differentiates the estimate v^(St,w)\hat v(S_t,\mathbf w) but treats the bootstrapped target, which also depends on w\mathbf w, as a constant

The target Rt+1+γv^(St+1,w)R_{t+1}+\gamma\hat v(S_{t+1},\mathbf w) depends on w\mathbf w, and the full gradient of the squared TD error would include −γ∇v^(St+1,w)-\gamma\nabla\hat v(S_{t+1},\mathbf w). 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.

Question 2

On-policy with γ=0.9\gamma=0.9, the bound VE‾(wTD)≤11−γmin⁡wVE‾(w)\overline{\mathrm{VE}}(\mathbf w_{\mathrm{TD}})\le\frac{1}{1-\gamma}\min_{\mathbf w}\overline{\mathrm{VE}}(\mathbf w) allows TD's value error to be at most how many times the best achievable?

  1. 0.90.9
  2. 1.91.9
  3. 1010
  4. 100100
Show the answer

C. 1010

1/(1−0.9)=101/(1-0.9)=10. The factor grows like the effective horizon, reaching 100 at γ=0.99\gamma=0.99. In norm form the sharper factor is 1/1−γ2≈2.291/\sqrt{1-\gamma^2}\approx2.29 at γ=0.9\gamma=0.9, so the squared error ratio is at most about 5.3.

Question 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 α=(τE[x⊤x])−1\alpha=(\tau\E[\mathbf x^\top\mathbf x])^{-1} give?

  1. 1/101/10
  2. 1/161/16
  3. 1/1601/160
  4. 1/25601/2560
Show the answer

C. 1/1601/160

Each state activates exactly one binary tile per tiling, so x⊤x=16\mathbf x^\top\mathbf x=16, and α=1/(10⋅16)=1/160\alpha=1/(10\cdot16)=1/160. With α=1/16\alpha=1/16 instead, a single update would move the prediction all the way to the target.

Question 4

A full order-3 Fourier basis is built over a 4-dimensional state. How many features does it have?

  1. 1212
  2. 6464
  3. 8181
  4. 256256
Show the answer

D. 256256

Each feature is indexed by a vector c∈{0,1,2,3}4\mathbf c\in\{0,1,2,3\}^4, so there are (3+1)4=256(3+1)^4=256 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

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