Chapter 9
On-policy Prediction with Approximation
A table cannot generalize. Every method of Part I, up to the Dyna and tree-search planners of Chapter 8, stores one number per state (or per state–action pair), and learning about one state teaches nothing about any other. In a game of backgammon, a camera image or a robot’s sensor readings, almost every state the agent meets is new, so this is no longer a question of memory alone: a table would never be filled. In this chapter we replace the table by a parameterized function with a weight vector , , and ask what happens to the prediction problem of Chapter 6 when changing one weight changes the estimated value of many states at once.Richard S. Sutton and Andrew G. Barto. Reinforcement Learning: An Introduction. Adaptive Computation and Machine Learning. MIT Press, Cambridge, MA, second edition, 2018. ISBN 978-0-262-03924-6. URL http://incompleteideas.net/book/the-book-2nd.html The answer has three parts: an objective that says which errors matter, the semi-gradient methods that bootstrap towards it, and, for linear functions, a complete theory of where semi-gradient TD converges and how far that point can be from the best possible one.
The policy is fixed throughout; control is the subject of Chapter 10. One consequence of approximation is worth stating at once. If cannot depend on some aspect of the state, the agent behaves as if that aspect were unobservable; all results of this chapter therefore hold unchanged for partially observable problems, in which the “state” is whatever the features see. What approximation cannot do is add memory of past observations to the state.
9.1Value Prediction as Supervised Learning#
Every prediction method of Part I can be written as a sequence of individual updates : the estimated value of state is moved towards an update target . Monte Carlo uses , TD(0) uses , -step TD uses , and the DP backup uses . In the tabular case an update touched one entry; now we hand the pair to a learning method as a training example of the input–output behavior we want, and let it decide how to change . Value prediction becomes regression, and in principle any method of supervised learning may be used.
Two features of reinforcement learning restrict the choice. First, data arrive one at a time while the agent acts, so the learner must be incremental and online; methods that need a fixed training set and many passes over it fit poorly. Second, the targets are nonstationary. In control the policy, and with it , changes as learning proceeds; and even for a fixed policy every bootstrapped target contains the current estimate , so the regression problem moves as we solve it. Supervised learning with moving targets is the theme of the chapter.
9.2The Prediction Objective#
With fewer weights than states we cannot make every value right: improving one state makes others worse. We must say which states we care about, through a distribution , , and measure the mean squared value error
(9.1)Its square root is a typical size of the error in value units. The natural weighting, and the only one studied in this chapter, is the fraction of time spent in each state while following : the on-policy distribution. In a continuing task it is the stationary distribution of the Markov chain that induces, with (see Section A.3). In an episodic task, let be the probability that an episode starts in and the expected number of visits to in one episode. Time is spent in either by starting there or by arriving from a state in which time was spent:
(9.2)In matrix form , where is now substochastic (rows of states that may terminate sum to less than one). Discounting can be folded in as a probability of terminating at each step, by writing in place of .
A weight vector is a global optimum if for all , a local one if this holds in a neighborhood of . For linear the two coincide; for neural networks a local optimum is usually the best that can be promised.It is not obvious that is the right objective: we learn values in order to choose better actions, and the value function that ranks actions best need not have the smallest squared error. Other objectives, built on the Bellman error, appear in Chapter 11. For on-policy prediction is clear and measurable, and it will turn out that the bootstrapping methods we use do not even minimize it; they come provably close.
9.3Stochastic-Gradient and Semi-Gradient Methods#
Assume for a moment that each training example carries the true value, , with . Stochastic gradient descent (SGD) moves the weights a small step against the gradient of the squared error on that one example:
where . Its expectation over is exactly : the per-example step is an unbiased sample of the full gradient step. The step is small on purpose: correcting each example completely would undo the balance between states that an approximation must strike.
The true value is unknown, so we substitute a target :
(9.3)The derivation above needed only and that does not depend on . The Monte Carlo return satisfies both.
Proposition 9.1 (Gradient Monte Carlo Descends the Value Error). Let in (9.3), with the weights held fixed during each episode and the accumulated update applied at its end. The expected update of one episode is
with the episodic on-policy distribution (9.2). Consequently, under the step-size conditions of Theorem A.7 and standard regularity (bounded rewards, smooth , bounded iterates), gradient Monte Carlo converges with probability one to a stationary point, in practice a local minimum, of .
Proof. Write the sum over time as a sum over states visited: . By the Markov property, given the return has mean whatever happened before , so
Multiplying by and summing over gives . The update is therefore a noisy gradient step whose noise has conditional mean zero given the past episodes, which is the setting of the Robbins–Monro theorem for stochastic gradient descent. □
Algorithm 9.2 (Gradient Monte Carlo Prediction). Input: the policy ; a differentiable . Parameter: step size . Initialize: arbitrarily (e.g. ).
- Loop for each episode:
- Generate following .
- For : .
9.3.1Why “Semi”#
Now let the target bootstrap, . The target depends on , so (9.3) is no longer the gradient of the squared error on the example. Differentiating honestly would give
with the TD error (6.2) computed with . The update (9.3) keeps only the first term: it accounts for the effect of on the estimate but ignores its effect on the target. It includes only part of a gradient, and we call such methods semi-gradient methods.The name is new in the second edition of Sutton and Barto. The observation that bootstrapping methods are not gradient descent goes back at least to Barnard (1993).Etienne Barnard. Temporal-Difference Methods and Markov Models. IEEE Transactions on Systems, Man, and Cybernetics, 23(2):357–365, 1993 Worse, the expected semi-gradient TD update is in general not the gradient of any function of , as we will see for linear in Section 9.4: the matrix that drives it is not symmetric. So the convergence theory of SGD does not apply, and a different argument is needed. What semi-gradient methods offer in exchange is what we valued in Part I: lower variance and faster learning, and the ability to learn online and in continuing tasks without waiting for returns.
Algorithm 9.3 (Semi-gradient TD(0) Prediction). Input: the policy ; a differentiable with . Parameter: step size . Initialize: arbitrarily.
- Loop for each episode: initialize ; then repeat until is terminal:
- Choose , take it, observe .
- .
- .
This is tabular TD(0), Algorithm 6.1, with the table entry replaced by and the unit change of one entry replaced by the gradient. The simplest generalizing approximator shows the connection most plainly. In state aggregation the states are partitioned into groups, each group has one weight, and is the weight of ’s group. The gradient is the indicator of that group, so an update changes exactly one weight, which is shared by all the states in the group.
9.4Linear Methods#
The most important special case, and the one with a complete theory, represents each state by a feature vector and sets
The functions are the basis functions of the approximation. Tabular methods are the special case of one-hot features, (Exercise 9.10), and state aggregation is the case of one-hot group indicators. is a convex quadratic in , so its local minima are global, and gradient Monte Carlo finds the global minimum.
9.4.1The TD Fixed Point#
Consider a continuing task and write . Linear semi-gradient TD(0) reads
The update is linear in . Once the chain is in its stationary regime, , the expected next weight is
(9.4)If the iteration converges, it can only converge to the point where the expected update vanishes, the TD fixed point
(9.5)To study , collect the features as the rows of the matrix , put on the diagonal of , and let be the state-transition matrix under and the expected reward. Conditioning on and then on ,
(9.6)Everything about linear TD is in the key matrix . A real (not necessarily symmetric) matrix is called positive definite if for every ; since , this holds exactly when the symmetric part is positive definite in the usual sense.
Theorem 9.4 (Stability of On-policy Linear TD(0)). Let , let be the stationary distribution of with for all , and let have linearly independent columns. Then the key matrix and are positive definite. Hence is invertible, every eigenvalue of has positive real part, and the expected iteration converges to for every sufficiently small .
Proof. The key matrix. Let and . The diagonal entries of are and the off-diagonal entries are . A symmetric matrix whose diagonal entries are positive and exceed the sum of the absolute values of the other entries in their row is positive definite: by Gershgorin’s theorem each eigenvalue lies in a disc centered at a diagonal entry with radius smaller than that entry. Because the off-diagonal entries are nonpositive, this strict diagonal dominance says precisely that every row sum of is positive, and the row sums of are the row sums of plus its column sums. The row sums are . The column sums form the row vector
where stationarity is used exactly once. Each row of sums to , so , and with it , is positive definite.
The matrix . For , by independence of the columns, so .
Eigenvalues and the iteration. If with complex , then while ; so , and in particular . The error of the expected iteration obeys , and the eigenvalues of satisfy as soon as for all . Then . □
The proof never asked to be symmetric, and it is not. That settles the remark of Section 9.3.1: the expected update field has Jacobian , and a vector field is the gradient of a function only if its Jacobian is symmetric. Linear TD follows no objective’s gradient, yet the field still points inwards, which is all stability needs. Two remarks on the hypotheses. Stationarity of entered only through the column sums; if states are updated with some other distribution, the column sums can be negative and TD can diverge, the phenomenon studied in Section 11.3. And the theorem is about the expected update; with probability one convergence of the stochastic iterates requires in addition decreasing step sizes and mixing of the chain, and was proved by Tsitsiklis and Van Roy.John N. Tsitsiklis and Benjamin Van Roy. An Analysis of Temporal-Difference Learning with Function Approximation. IEEE Transactions on Automatic Control, 42(5):674–690, 1997. doi: 10.1109/9.580874
9.4.2How Good Is the TD Fixed Point?#
Gradient Monte Carlo finds ; TD finds . To compare them, it helps to look at functions on as vectors in with the inner product and norm , so that . The representable functions form the subspace , and the closest one to any is its orthogonal projection
(9.7)So , the best that any method can do with these features. The Bellman operator has as its fixed point; TD has its own:
Proposition 9.5 (TD Solves the Projected Bellman Equation). if and only if .
Proof. . This vanishes iff the residual is -orthogonal to every column of , that is, iff is the projection of . □
TD does not look for the representable function nearest to ; it looks for the representable function that reproduces itself when backed up once and projected back. Two inequalities show that this is a well-posed and nearly optimal request.
Lemma 9.6 (Nonexpansiveness in the μ-norm). If is stationary for , then for every , and . Consequently is a -contraction in .
Proof. By Jensen’s inequality ; multiplying by , summing over and using gives . The gap is exactly , a weighted variance. An orthogonal projection never increases a norm: . Finally . □
By Theorem A.3 the projected Bellman operator has a unique fixed point in the subspace, which by Proposition 9.5 is : a second proof that the TD fixed point exists, and one that explains why the on-policy distribution matters. In any other norm can expand, and need not contract.
Theorem 9.7 (Error Bound at the TD Fixed Point). Under the hypotheses of Theorem 9.4,
(9.8)Proof. Write and . The vector lies in the subspace and is orthogonal to it, so by Pythagoras
For the second term use the two fixed points, and , and the lemma: . Hence . The second inequality is . □
Sutton and Barto state the weaker factor ; the Pythagorean step gives for free.Tsitsiklis and Van Roy (1997) proved, for linear TD(), the bound on the root error. The Pythagorean refinement used here, giving the factor on the root error for , is standard in the later literature on projected equations (Bertsekas’s books, for instance). Either way the factor blows up as , and this is the asymptotic price of bootstrapping: the representation errors made at successor states are backed up and accumulate. Monte Carlo pays no such price but learns slowly; as in Part I the right compromise is usually in between. The same argument applies to every on-policy bootstrapping method that solves a projected Bellman equation: linear semi-gradient DP with updates distributed according to converges to the same point, -step methods replace by (Exercise 9.13), and semi-gradient Sarsa with a fixed policy has the analogous bound for action values.
9.4.3In Wolfram Language#
All of this can be computed exactly on a three-state chain. From state 1 the agent moves to state 2 with probability and otherwise stays; from state 2 it moves to 1 or 3 with equal probability; state 3 returns to state 1 and pays a reward of 1. Two features, , , , cannot represent every value function. We first find the on-policy distribution, then build from its definition as an expectation and check it against .
The stationary distribution spans the left null space of ; normalize it to sum to one.const P = await wl`{{1 - p, p, 0}, {1/2, 0, 1/2}, {1, 0, 0}}`
const mu = await show`With[{n = First[NullSpace[Transpose[${P}] - IdentityMatrix[3]]]}, Simplify[n/Total[n]]]`const X = await wl`{{1, 0}, {1, 1}, {0, 1}}`
const rpi = await wl`{0, 0, 1}`
const Dmu = await wl`DiagonalMatrix[${mu}]`
const A = await show`With[{byExpectation = Sum[${mu}[[s]] ${P}[[s, s2]] Outer[Times, ${X}[[s]], ${X}[[s]] - \[Gamma] ${X}[[s2]]], {s, 3}, {s2, 3}]},
If[Simplify[byExpectation - Transpose[${X}] . ${Dmu} . (IdentityMatrix[3] - \[Gamma] ${P}) . ${X}] === {{0, 0}, {0, 0}}, Simplify[byExpectation], $Failed]]`const wTD = await wl`Simplify[Inverse[${A}] . (Transpose[${X}] . ${Dmu} . ${rpi})]`
await show`Column[${wTD}]`The stability argument rests on the row and column sums of the key matrix, both , and on the positive definiteness of its symmetric part, which we confirm for all and through the leading principal minors (Sylvester’s criterion).
Column sums (first row of the output) and row sums (second row) of : both equal .const M = await wl`${Dmu} . (IdentityMatrix[3] - \[Gamma] ${P})`
await show`Simplify[{Total[${M}], Total[${M}, {2}]}]`await show`With[{S = ${M} + Transpose[${M}]}, Resolve[ForAll[{\[Gamma], p}, 0 < \[Gamma] < 1 && 0 < p < 1, And @@ Table[Det[S[[1 ;; k, 1 ;; k]]] > 0, {k, 3}]], Reals]]`The contraction lemma hides an identity: the loss of -norm under is a variance. With a symbolic vector we check that vanishes identically, and that is the fixed point of the projected Bellman operator.
The gap equals a -weighted conditional variance, hence is ; this uses .await show`With[{y = {Subscript[y, 1], Subscript[y, 2], Subscript[y, 3]}}, Simplify[y . ${Dmu} . y - (${P} . y) . ${Dmu} . (${P} . y) - Sum[${mu}[[s]] ${P}[[s, s2]] (y[[s2]] - (${P} . y)[[s]])^2, {s, 3}, {s2, 3}]]]`const Proj = await wl`Simplify[${X} . Inverse[Transpose[${X}] . ${Dmu} . ${X}] . Transpose[${X}] . ${Dmu}]`
await show`Simplify[{${Proj} . ${Proj} - ${Proj}, ${X} . ${wTD} - ${Proj} . (${rpi} + \[Gamma] ${P} . ${X} . ${wTD})}]`Finally the bound. We compute , the best weights , and the ratio for .
The ratio is at , where the TD target is the reward itself, and grows with .const vpi = await wl`Simplify[Inverse[IdentityMatrix[3] - \[Gamma] ${P}] . ${rpi}]`
const ve = await wl`Function[w, Simplify[(${vpi} - ${X} . w) . ${Dmu} . (${vpi} - ${X} . w)]]`
const wMin = await wl`Simplify[Inverse[Transpose[${X}] . ${Dmu} . ${X}] . Transpose[${X}] . ${Dmu} . ${vpi}]`
const ratio = await show`Factor[(${ve}[${wTD}]/${ve}[${wMin}]) /. p -> 1/2]`await show`{Resolve[ForAll[\[Gamma], 0 < \[Gamma] < 1, ${ratio} <= 1/(1 - \[Gamma]^2)], Reals], N[{${ratio}, 1/(1 - \[Gamma]^2), 1/(1 - \[Gamma])} /. \[Gamma] -> 9/10, 3]}`9.4.4State Aggregation on a Long Random Walk#
The same linear algebra applies to episodic tasks, with , the substochastic and the episodic of (9.2). Sutton and Barto’s running example is a random walk on states that starts in state 500 and jumps uniformly to one of the 100 states on either side; a jump past either end terminates with reward on the left and on the right. Aggregating the states into ten groups of 100 gives ten weights. Rather than simulate, we solve for (an episode lasts steps on average; the start state gets of the time, its neighbors about each and the end states ), , the minimizer of (the -weighted average of within each group) and exactly (Figure 9.1).
The TD staircase is visibly shrunk towards zero. Each group’s TD value is built from the values of the groups it jumps into, which are themselves averages, so representation error propagates inwards from both ends. Within each Monte Carlo group, by contrast, the weight is pulled towards the states that weights most, which near the ends are the inner ones.
9.4.5n-step Semi-gradient TD#
The -step return of (7.1), with in place of ,
(9.9)used as in (9.3), interpolates between TD(0) () and gradient Monte Carlo (). With state aggregation on the random walk, the error curves as a function of and look strikingly like the tabular ones of Chapter 7, with intermediate best.
Algorithm 9.8 (n-step Semi-gradient TD Prediction). Input: ; differentiable with . Parameters: , integer . Initialize: arbitrarily. Indices of stored may be taken mod .
- Loop for each episode: store ; .
- For :
- If : act with , store ; if is terminal, .
- (the time being updated). If :
- ; if , .
- .
- Stop when .
9.5Feature Construction for Linear Methods#
The theory above holds for any features; how well a linear method works depends almost entirely on which features it is given. Features are the main channel for prior knowledge: they should vary along the directions in which values vary, and coincide along the directions in which generalization is safe. Their great limitation is that a linear function cannot express interactions by itself. In pole balancing a high angular velocity is good when the pole is falling back to vertical and bad when it is falling away; a value linear in separate angle and velocity features cannot say this, so we need features of combinations.
9.5.1Polynomials and the Fourier Basis#
If the state is a vector of numbers , the order- polynomial basis consists of the monomials with exponents ; the constant feature allows affine functions and the mixed monomials express interactions. There are of them, exponential in , so in practice a subset is chosen. Polynomials generalize globally and poorly in online learning, and are not recommended.
The Fourier basis of Konidaris, Osentoski and Thomas does better.George Konidaris, Sarah Osentoski, and Philip Thomas. Value Function Approximation in Reinforcement Learning Using the Fourier Basis. In Proceedings of the Twenty-Fifth AAAI Conference on Artificial Intelligence (AAAI-11), pages 380–385, 2011 On a bounded interval rescaled to , extend a function evenly to and then periodically: the extension is continuous at the boundary, so its Fourier series contains cosines only and converges well. The order- cosine basis in dimensions is
(9.10)again features. A zero in makes the feature constant along that coordinate; nonzero entries in several coordinates encode an interaction, with frequencies and a direction given by their ratios. Sine features would be odd, and an odd function is generally discontinuous at the origin, which is why cosines are preferred. Konidaris et al. suggest the per-feature step size (with for ), so that high frequencies learn more slowly. The cosine features are orthogonal on , so with uniform the least-squares weights decouple into Fourier coefficients:
for : the Gram matrix of the 1-D basis is diagonal.await show`Table[Integrate[Cos[i Pi s] Cos[j Pi s], {s, 0, 1}], {i, 0, 3}, {j, 0, 3}]`Being nonzero almost everywhere, Fourier features describe global properties of a state; they struggle with discontinuities (ringing) and with sharply local structure, which is what the next family is for.
9.5.2Coarse Coding and Tile Coding#
Cover a continuous state space with overlapping regions, say circles, and give each region a binary feature that is when the state lies inside it. This is coarse coding. Training at one state changes the weights of all regions containing it, so the value changes at every state sharing a region with it, in proportion to the number of shared regions. The size and shape of the regions determine generalization (wide regions generalize far; elongated ones generalize along their long axis), but the finest discrimination finally achievable, the acuity, is governed by the number of features. Wide receptive fields do not doom the approximation to be coarse.
Tile coding is coarse coding organized for speed.James S. Albus. A Theory of Cerebellar Function. Mathematical Biosciences, 10(1–2):25–61, 1971. doi: 10.1016/0025-5564(71)90051-4 Each tiling is a partition of the state space into tiles (a grid, say), and several tilings are used, each offset from the others by a fraction of the tile width. A state activates exactly one tile in each tiling, so with tilings exactly features are and the rest . Computing amounts to summing weights found by index arithmetic; and since for every state, the step size has a simple meaning: moves the trained state’s value all the way to the target, and one tenth of the way.
The generalization from a trained state to another state is proportional to the number of tiles they share. In one dimension with tilings of width offset by , two points at distance share, on average over the position of , tiles: a triangular kernel, and exactly tiles, wherever lies, when with : the interval between the two points contains tile boundaries, each from a different tiling.
With tilings of unit width: first, the tiles shared by and for ; second, the exact average over for , which is .const shared = await wl`Function[{s, d, m}, Sum[Boole[Floor[s + k/m] == Floor[s + d + k/m]], {k, 0, m - 1}]]`
await show`{Table[${shared}[1/8, d, 4], {d, 0, 5/4, 1/4}], Table[Integrate[${shared}[s, d, 4], {s, 0, 1}], {d, {0, 1/10, 3/10, 1/2, 9/10, 6/5}}]}`In several dimensions the offsets shape the kernel. Offsetting every tiling by the same displacement along each axis, the vector in units of , produces generalization patterns elongated along the diagonal; Miller and Glanz recommend the displacement vector of the first odd integers with a power of two at least , which gives nearly isotropic patterns. Tiles need not be squares: stripes promote generalization along one dimension (ignoring others), log-spaced stripes give finer resolution where needed, and mixing stripe tilings with conjunctive ones lets a learner both generalize along each dimension and represent specific conjunctions. Finally hashing collapses a huge tiling pseudo-randomly onto a much smaller table: each table entry then stands for many scattered tiles, but since high resolution matters in only a small part of the state space, memory can track the needs of the task instead of growing exponentially with .
9.5.3Radial Basis Functions#
A radial basis function feature responds by degree, , with center and width . RBFs are the graded version of coarse coding and give smooth, differentiable approximations, which rarely matters in practice and costs computation; in more than two dimensions tile coding usually works at least as well. Learning the centers and widths too turns an RBF network into a nonlinear approximator.
9.5.4Choosing the Step Size#
The classical conditions of Theorem A.7 guarantee convergence but learn too slowly, and suits neither bootstrapping nor nonstationarity. In the tabular case means that a state’s estimate approaches the recent average of its targets after about visits. For linear methods, the same intuition gives a rule of thumb. One update at with target changes the value of itself by
so the fraction of the error removed is . To learn in about presentations of similar feature vectors, set
(9.11)with the expectation over the feature vectors met in training. The rule is exact when is constant, as in tile coding.
9.6Nonlinear Function Approximation: Neural Networks#
An artificial neural network computes through layers of units, each applying a nonlinearity (logistic, tanh, rectifier) to a weighted sum of the previous layer’s outputs; collects all the connection weights. One hidden layer of enough units can approximate any continuous function on a compact set,George Cybenko. Approximation by Superpositions of a Sigmoidal Function. Mathematics of Control, Signals and Systems, 2(4):303–314, 1989. doi: 10.1007/BF02551274 but deep networks, with many layers composing simple features into abstract ones, are far more economical for the functions that matter, and their hidden layers learn the features that linear methods must be given.
Nothing in (9.3) needs to change: backpropagation computes , and semi-gradient TD, gradient Monte Carlo and -step methods run as before. What changes is the theory. Gradient Monte Carlo still descends towards a local minimum, but semi-gradient TD with a nonlinear has no general convergence guarantee, and classic counterexamples diverge. The practical toolkit of deep learning (careful initialization, rectifiers, batch normalization, residual connections, dropout against overfitting, convolutional layers that share weights across positions in an image) is what made the large applications of Chapter 15 possible. Deep Q-networks, which combine semi-gradient Q-learning with a convolutional network, a replay memory and a periodically frozen target network, are off-policy learners and are described in Section 15.5; why their training tricks are needed is the subject of Chapter 11.
9.7Least-Squares TD#
Semi-gradient TD reaches by small steps, discarding each transition after one use. Why not estimate and from all the data and solve? This is least-squares TD (LSTD) of Bradtke and Barto:Steven J. Bradtke and Andrew G. Barto. Linear Least-Squares Algorithms for Temporal Difference Learning. Machine Learning, 22:33–57, 1996. doi: 10.1007/BF00114723
(9.12)Both sums estimate times their expectations (9.4), and the factors cancel; the small keeps invertible. Maintaining costs per step, but inverting it afresh would cost . Because each step adds a rank-one matrix, the inverse can be updated directly by the Sherman–Morrison formulaJack Sherman and Winifred J. Morrison. Adjustment of an Inverse Matrix Corresponding to a Change in One Element of a Given Matrix. The Annals of Mathematical Statistics, 21(1):124–127, Institute of Mathematical Statistics, 1950. doi: 10.1214/aoms/1177729893
(9.13)which needs only matrix–vector products. Proof: multiply the right-hand side by ; the scalar factors out and everything except cancels. The kernel confirms it on a general matrix:
The difference between the two sides of the Sherman–Morrison formula, for symbolic , , .await show`Simplify[With[{B = {{Subscript[b, 11], Subscript[b, 12]}, {Subscript[b, 21], Subscript[b, 22]}}, u = {Subscript[u, 1], Subscript[u, 2]}, v = {Subscript[v, 1], Subscript[v, 2]}},
Inverse[B + Outer[Times, u, v]] - (Inverse[B] - Inverse[B] . Outer[Times, u, v] . Inverse[B]/(1 + v . Inverse[B] . u))]]`Algorithm 9.9 (LSTD, O(d²) Version). Input: features with . Parameter: small . Initialize: , .
- Loop for each episode: initialize , ; repeat until is terminal:
- Choose and take ; observe ; .
- .
- .
- ; .
- , .
The recursion is exact, not an approximation of (9.12). We run it on a short trajectory of the three-state chain, with exact rationals, and compare it with the direct solution:
Fold the Sherman–Morrison step of Algorithm 9.9 over eight transitions with , ; the output is and its difference from .const traj = await wl`{1, 2, 3, 1, 1, 2, 1, 2, 3}`
await show`With[{g = 9/10, eps = 1/100, xs = ${X}[[${traj}]], rs = ${rpi}[[Most[${traj}]]]},
With[{fold = Fold[Function[{acc, k}, With[{Ai = acc[[1]], x = xs[[k]], v = Transpose[acc[[1]]] . (xs[[k]] - g xs[[k + 1]])},
{Ai - Outer[Times, Ai . x, v]/(1 + v . x), acc[[2]] + rs[[k]] x}]], {IdentityMatrix[2]/eps, {0, 0}}, Range[8]],
direct = Inverse[eps IdentityMatrix[2] + Sum[Outer[Times, xs[[k]], xs[[k]] - g xs[[k + 1]]], {k, 8}]] . Sum[rs[[k]] xs[[k]], {k, 8}]},
{fold[[1]] . fold[[2]], fold[[1]] . fold[[2]] - direct}]]`LSTD is the most data-efficient form of linear TD(0), and it has no step size; but it has instead (too small and the early inverses swing wildly, too large and learning slows), its cost is against , and having no step size it never forgets, which is a defect once the policy changes, as in control.LSTD was extended to control as least-squares policy iteration by Lagoudakis and Parr (2003), which evaluates each policy by LSTD on action values.Michail G. Lagoudakis and Ronald Parr. Least-Squares Policy Iteration. Journal of Machine Learning Research, 4:1107–1149, 2003
9.8Memory-based and Kernel-based Approximation#
Parametric methods compress experience into and discard the examples. Memory-based methods do the opposite: they store the examples and, when a query state needs a value, compute one from the stored examples near it. Nearest-neighbor returns the target of the closest stored state; weighted averaging combines several neighbors with weights decreasing in distance; locally weighted regression fits a small parametric surface around the query and discards it after answering. Such nonparametric methods are not confined to a fixed functional form, so their accuracy keeps improving with data; they concentrate effort on the states that trajectories actually visit, which is all that matters in many problems; and their memory grows with the number of examples, not exponentially with the dimension. The price is query time, mitigated by data structures such as -d trees.
The function that weights stored examples is a kernel , the strength of generalization from to , and kernel regression sets
(9.14)with the stored examples and their targets. The link with linear methods is immediate. One linear update at changes the value at every by
so a linear method generalizes according to the kernel ; the shared-tile counts of Section 9.5.2 are exactly this kernel for tile coding. Conversely, any linear regression can be rewritten as kernel regression with this inner-product kernel, and for many feature maps the kernel has a closed form that never builds the (possibly huge) feature vectors: the kernel trick.
9.9Interest and Emphasis#
On-policy methods weight every visited state equally. Sometimes we care about some states more: the start state of a discounted episodic task, say, or the greedy action rather than the poor ones. Let the interest express how much we care about valuing accurately (set causally, possibly from the trajectory so far), and let in (9.1) be the on-policy distribution weighted by interest. The emphasis multiplies the update,
(9.15)with for ; in the Monte Carlo case . The recursion is the point: a state of no interest still receives emphasis if an interesting state bootstraps from it steps earlier, because the accuracy of the interesting state depends on it. Exercise 9.12 works through Sutton and Barto’s four-state example. Emphasis returns in off-policy learning, where emphatic TD uses it to restore stability (Chapter 11).
9.10Beyond the Book: Finite-Time Theory, Deep TD and Learned Representations#
9.10.1How Fast Does Linear TD Converge?#
The results above are asymptotic. Bhandari, Russo and Singal gave a short finite-time analysis of linear TD(0) that mirrors textbook SGD proofs.Jalaj Bhandari, Daniel Russo, and Raghav Singal. A Finite Time Analysis of Temporal Difference Learning with Linear Function Approximation. Operations Research, 69(3):950–973, 2021. doi: 10.1287/opre.2020.2024. Extended abstract in Proceedings of the 31st Conference on Learning Theory (COLT 2018), PMLR 75; arXiv:1806.02450; and R. Srikant and Lei Ying. Finite-Time Error Bounds for Linear Stochastic Approximation and TD Learning. In Proceedings of the Thirty-Second Conference on Learning Theory, volume 99 of Proceedings of Machine Learning Research, pages 2803–2830. PMLR, 2019Beyond Sutton and Barto (2018). Bhandari, Russo and Singal’s analysis appeared on arXiv in June 2018, as a COLT 2018 extended abstract, and in full in Operations Research 69(3), 2021. Srikant and Ying (COLT 2019) soon obtained constant-step-size bounds under Markovian sampling without the projection step, by Lyapunov drift arguments. The key is an inequality we have essentially proved: with the expected TD direction and features scaled so that ,
(9.16)The first is Lemma 9.6 in disguise: with , the left side is , by Cauchy–Schwarz. This is a quantitative version of Theorem 9.4: the symmetric part of dominates . Together the two inequalities say that the TD direction behaves like the gradient of a strongly convex function, even though it is no gradient. From them follow, with i.i.d. sampling of and the smallest eigenvalue of : an bound on the value error of the averaged iterate with step size , independent of ; geometric decay, at rate , down to a noise floor proportional to with a small constant step; and with steps decaying like . For Markovian data analogous bounds hold, inflated by the mixing time of the chain, for a variant that projects the iterates onto a ball containing .
9.10.2Deep TD and the Tangent Kernel#
Linearize a network around its current weights: . Locally, semi-gradient TD on the network is linear TD with the features , and by Section 9.8 it generalizes through the kernel , the neural tangent kernel.Arthur Jacot, Franck Gabriel, and Clément Hongler. Neural Tangent Kernel: Convergence and Generalization in Neural Networks. In Advances in Neural Information Processing Systems 31 (NeurIPS 2018), pages 8571–8580, 2018 The stability question of Theorem 9.4 therefore becomes a question about this kernel: when it generalizes too strongly between a state and its successor, a TD update can raise the target as much as the estimate and the iteration runs away.Beyond Sutton and Barto (2018). Achiam, Knight and Abbeel (arXiv, 2019) analyzed divergence of deep Q-learning through this first-order expansion and proposed PreQN, which preconditions the TD errors with the inverse Gram matrix of gradients. Cai, Yang, Lee and Wang (NeurIPS 2019) proved that for sufficiently overparameterized two-layer networks, which stay close to their linearization, neural TD converges at a sublinear rate to the global optimum of the projected Bellman error. Achiam et al. used this expansion to explain divergence in deep Q-learning,Joshua Achiam, Ethan Knight, and Pieter Abbeel. Towards Characterizing Divergence in Deep Q-Learning, 2019 and Cai et al. proved that sufficiently wide networks, which barely leave their linearization, inherit convergence to a projected-Bellman fixed point.Qi Cai, Zhuoran Yang, Jason D. Lee, and Zhaoran Wang. Neural Temporal-Difference Learning Converges to Global Optima. In Advances in Neural Information Processing Systems 32 (NeurIPS 2019), pages 11315–11326, 2019 For narrow networks trained far from initialization the linear picture breaks down, and there is still no general theory.
9.10.3Learning the Representation#
A network learns its own features, but the value signal is a single scalar per step, often sparse, and a poor teacher for a large representation. Jaderberg et al.’s UNREAL agent trains the shared layers on several auxiliary tasks at once: predicting immediate rewards, controlling changes in the pixels of the input, and replaying the value loss, with the auxiliary predictions thrown away and only the representation kept.Max Jaderberg, Volodymyr Mnih, Wojciech Marian Czarnecki, Tom Schaul, Joel Z. Leibo, David Silver, and Koray Kavukcuoglu. Reinforcement Learning with Unsupervised Auxiliary Tasks. In International Conference on Learning Representations (ICLR), 2017Beyond Sutton and Barto (2018). Jaderberg et al. (ICLR 2017) reported mean expert-human-normalized performance of 880% on Atari and a tenfold mean speed-up in learning on 3-D Labyrinth tasks from auxiliary tasks alone. The general lesson, that predictions about many signals shape features good for value, is also the motivation of Sutton’s general value functions, discussed in Chapter 16. In the language of this chapter, the auxiliary tasks choose the feature map on which the final, nearly linear, value layer runs.
Everything in this chapter evaluated a fixed policy. Chapter 10 lets the policy change: semi-gradient methods carry over to action values almost verbatim, but continuing control without discounting needs a new objective, the average reward.
9.11Exercises#
Exercise 9.10. Show that tabular TD(0) is linear semi-gradient TD(0) with one-hot features . What are , and , and what does Theorem 9.7 say in this case?
Solution
With the update (9.3) changes only component of , by : this is tabular TD(0) with . Now , so and , and . Since , the minimum of is , and the bound says : TD’s fixed point is exact. On the chain of Section 9.4.3:
With , the TD fixed point minus is zero for all and .await show`Simplify[Inverse[${Dmu} . (IdentityMatrix[3] - \[Gamma] ${P})] . (${Dmu} . ${rpi}) - ${vpi}]`Exercise 9.11. A seven-dimensional state is tile coded with eight stripe tilings of each dimension separately ( tilings) and two conjunctive tilings of each of the pairs of dimensions ( tilings). You want learning to approach its asymptote after about ten presentations of the same feature vector. Which step size should you use?
Solution
Each tiling contributes exactly one active binary feature, so for every state. By (9.11) with , . Each update then removes one tenth of the error at the trained state, and less at states sharing only some of its tiles.
Exercise 9.12. Episodes of a four-state chain start in the leftmost state and move one state right on each step, with reward , until termination after the fourth state; , so the true values are . The approximation is for the first two states and for the last two. Only the first state is of interest: . Find the limits of gradient Monte Carlo and of two-step semi-gradient TD, each without and with emphasis.
Solution
Each state is visited once per episode, so the expected update is the sum over states of , and the limit is where it vanishes. Monte Carlo, no emphasis: averages the returns and , averages and : . Monte Carlo with emphasis: , only the first state updates, . Two-step TD, no emphasis: states 1 and 2 have targets ; state 3 has target and state 4 target . With emphasis: , , , : state 3 is emphasized because state 1 bootstraps from it.
Zero of the expected two-step update, without and with emphasis .await show`With[{feat = {{1, 0}, {1, 0}, {0, 1}, {0, 1}}, w = {Subscript[w, 1], Subscript[w, 2]}},
With[{targets = {2 + w[[2]], 2 + w[[2]], 2, 1}},
Table[Solve[Thread[Sum[em[[s]] (targets[[s]] - feat[[s]] . w) feat[[s]], {s, 4}] == 0], w], {em, {{1, 1, 1, 1}, {1, 0, 1, 0}}}]]]`Without emphasis two-step TD also converges to ; with emphasis it converges to , exact for the first state and for the state it bootstraps from, while states 2 and 4 are never updated.
Exercise 9.13. Show that the expected update of linear -step semi-gradient TD (continuing case, ) vanishes exactly when , with , and deduce at the fixed point.
Solution
Conditioning on , the expected -step return with fixed is , so the expected update is , which vanishes iff is the -projection of , as in Proposition 9.5. By Lemma 9.6, , and . The proof of Theorem 9.7 goes through with in place of . As the factor tends to one, the Monte Carlo limit.