Appendix A
Mathematical Toolkit
A handful of mathematical tools carry almost every argument in this companion: conditional expectations turn the recursive definition of the return into Bellman equations; contraction mappings make dynamic programming converge; Markov chains supply the distributions over which approximation errors are measured; stochastic approximation explains why sample-based updates with decreasing step sizes find what their expectations point to; importance sampling and the log-derivative trick turn expectations under one distribution into expectations under another, or into gradients; and the Sherman–Morrison formula makes least-squares TD incremental. This appendix states each tool precisely, proves it (or sketches the proof where the full argument belongs to a specialist text), and checks it in the Wolfram Language.
A.1Expectations and Conditioning#
All random variables in the book live on finite or countable sets unless stated otherwise, so expectations are sums: . For an event or a random variable with , the conditional expectation is , and denotes the random variable with .
Lemma A.1 (Law of Total Expectation). . More generally, if is a function of (so that carries more information), then , and for any function , .
Proof. , the exchange of sums being legitimate when . The general form is the same computation restricted to the event , which is a union of events . The last identity holds because is constant on . □
How it produces the Bellman equation. Starting from ((3.5)), condition on and then on the finer information , writing for the event :
The Markov property says that the last conditional expectation depends on only, and equals ; this gives (3.9). The same two steps, total expectation and the Markov property, produce every Bellman equation in the book, the policy gradient theorem (Theorem 13.2) included. A second use, in Monte Carlo and TD methods, is that is the best predictor of from in mean square: (expand and apply the lemma to the cross term), which is why averaging sampled returns estimates values.
A symbolic joint distribution of on with values : .const towJoint = await wl`{{Subscript[p, 1, 1], Subscript[p, 1, 2]}, {Subscript[p, 2, 1], Subscript[p, 2, 2]}}`
const towX = await wl`{Subscript[x, 1], Subscript[x, 2]}`
await show`Simplify[Sum[Total[${towJoint}[[y]]] (${towJoint}[[y]] . ${towX})/Total[${towJoint}[[y]]], {y, 2}] - Total[${towJoint} . ${towX}]]`A.2Contractions and Banach’s Fixed-Point Theorem#
A norm on is a function that is positive except at , homogeneous () and satisfies the triangle inequality. Three appear in the book: the max norm , natural for dynamic programming; the weighted Euclidean norm , natural for approximation (Chapter 9); and the induced matrix norm , the largest factor by which can stretch a vector in max norm. In particular for every stochastic matrix. All norms on are equivalent and make it complete: every Cauchy sequence converges.
Definition A.2 (Contraction). A map from a metric space to itself is a contraction with modulus if for all .
Theorem A.3 (Banach Fixed-Point Theorem). Let be a complete metric spaceStefan Banach. Sur les opérations dans les ensembles abstraits et leur application aux équations intégrales. Fundamenta Mathematicae, 3(1):133–181, Institute of Mathematics, Polish Academy of Sciences, 1922. doi: 10.4064/fm-3-1-133-181 and a contraction with modulus . Then has exactly one fixed point ; for every the iterates converge to , and
(A.1)Proof. By induction , so for , by the triangle inequality and the geometric series,
The sequence is Cauchy, hence converges to some . A contraction is continuous, so . If is another fixed point, forces . The first bound is iterated; the second (a priori) follows by letting in the display; the third (a posteriori) is the second applied with as the starting point and one step. □
The a priori bound says how many iterations will suffice before starting; the a posteriori bound gives a stopping rule from observed quantities: if then , which is how value iteration (Algorithm 4.10) should be stopped.
Proposition A.4 (The Bellman Operators Are Max-Norm Contractions). For , the operators and are contractions with modulus in . Their fixed points are and .
Proof. , and . For , use the elementary inequality (if the first maximum is the larger and is attained at , the difference is at most ), with , which is at most in absolute value. The fixed points are the solutions of the Bellman equations (3.9) and (3.17), unique by the theorem. □
The first check iterates symbolically on a two-state chain from an arbitrary start and confirms that the error after steps is exactly , whence the rate . The second proves the inequality used for by quantifier elimination over the reals.
Three applications of from , minus with .const bnP = await wl`{{p, 1 - p}, {1 - q, q}}`
const bnR = await wl`{Subscript[r, 1], Subscript[r, 2]}`
const bnT = await wl`Function[v, ${bnR} + \[Gamma] ${bnP} . v]`
const bnV = await wl`Inverse[IdentityMatrix[2] - \[Gamma] ${bnP}] . ${bnR}`
await show`Simplify[Nest[${bnT}, {Subscript[u, 1], Subscript[u, 2]}, 3] - ${bnV} - MatrixPower[\[Gamma] ${bnP}, 3] . ({Subscript[u, 1], Subscript[u, 2]} - ${bnV})]`await show`Resolve[ForAll[{a, b, c, d}, Abs[Max[a, b] - Max[c, d]] <= Max[Abs[a - c], Abs[b - d]]], Reals]`A.3Finite Markov Chains#
Fixing a policy turns an MDP into a Markov chain on the states, with transition matrix . Distributions are row vectors and evolve by . Two structures occur in the book: continuing chains, which run forever and settle into a stationary distribution, and episodic chains, which are absorbed in a terminal state and are described by expected numbers of visits.
A.3.1Stationary Distributions and the Ergodic Theorem#
A distribution is stationary if : starting from it, the chain stays in it. The chain is irreducible if every state can reach every other with positive probability, and aperiodic if, for every state, the greatest common divisor of the lengths of the paths returning to it is (a self-loop suffices).
Theorem A.5 (Ergodic Theorem for Finite Chains). Let be the transition matrix of an irreducible chain on a finite set. Then (i) there is a unique stationary distribution , and for every ; (ii) for every function and every initial state, almost surely; (iii) if the chain is also aperiodic, for all , geometrically fast.
We do not reprove it; see Levin and Peres for a complete treatment.David A. Levin and Yuval Peres. Markov Chains and Mixing Times. American Mathematical Society, Providence, RI, second edition, 2017. ISBN 978-1-4704-2962-1. doi: 10.1090/mbk/107. With contributions by Elizabeth L. Wilmer; with an appendix by James G. Propp and David B. Wilson Part (i) is linear algebra (Perron–Frobenius: is a simple eigenvalue of with a positive left eigenvector). Part (ii) is the strong law of large numbers applied to the independent excursions between visits to a fixed state, with . Part (iii) is where aperiodicity enters: the chain has and satisfies (ii), but its distribution oscillates forever. Part (ii) is what the book needs for the average-reward setting (Section 10.3): it guarantees that does not depend on the start state, and that time averages of rewards along one trajectory estimate it. A useful shortcut for computing is balance across a cut: in stationarity the probability flow from a set to its complement equals the flow back. For two states with and this gives .
The normalized left eigenvector for eigenvalue of a two-state chain.const mkP = await wl`{{1 - a, a}, {b, 1 - b}}`
await show`Simplify[With[{m = First[NullSpace[Transpose[${mkP}] - IdentityMatrix[2]]]}, m/Total[m]]]`A.3.2The Neumann Series and Expected Visits#
Proposition A.6 (Neumann Series). If is a square matrix with for some and some induced norm (equivalently, spectral radius ), then is invertible and .
Proof. Grouping the terms in blocks of , , so the series converges absolutely. The telescoping identity and give the result in the limit. □
Two cases cover the book. Discounting: for any stochastic and , , so has nonnegative entries and row sums , and is the expected discounted sum of rewards term by term. Episodes: let be the transition matrix restricted to the non-terminal states, substochastic because rows lose the probability of terminating. If from every state termination happens within steps with probability at least , then every row of sums to at most , so and the proposition applies even with . The entry is the probability of being in at time , not yet terminated, having started in , so
(A.2)for a start distribution (row vector); summing over gives the expected episode length, . Equivalently , the “expected visits” equation from which the book defines the on-policy distribution of episodic tasks (Chapter 9). The matrix is the fundamental matrix of the absorbing chain. With discounting, gives the discounted visit counts used in the policy gradient theorem.
summed in closed form, minus .await show`Assuming[0 < \[Gamma] < 1 && 0 < a < 1 && 0 < b < 1, Simplify[Sum[MatrixPower[\[Gamma] ${mkP}, k], {k, 0, Infinity}] - Inverse[IdentityMatrix[2] - \[Gamma] ${mkP}]]]`The random walk of Chapter 6 (five non-terminal states, start in the center, left or right with probability ) is a clean example of (A.2).
Expected visits for the symmetric five-state random walk started in the center.const rwQ = await wl`Normal[SparseArray[{Band[{1, 2}] -> 1/2, Band[{2, 1}] -> 1/2}, {5, 5}]]`
const rwEta = await show`UnitVector[5, 3] . Inverse[IdentityMatrix[5] - ${rwQ}]`The episode lasts steps on average, and the on-policy distribution is : the center state receives a third of the visits, which is the weighting under which is measured for this task.
A.4Stochastic Approximation#
Almost every learning rule in the book has the form
(A.3)where is the expected update direction and is zero-mean noise from sampling. The sample average is the simplest instance: with and , (Chapter 2). TD(0) is another, with (Chapter 9), and so are Q-learning, REINFORCE and the actor–critics. The question is when converges to a zero of despite the noise. Robbins and Monro answered it in 1951 for root finding in one dimension;Herbert Robbins and Sutton Monro. A Stochastic Approximation Method. The Annals of Mathematical Statistics, 22(3):400–407, Institute of Mathematical Statistics, 1951. doi: 10.1214/aoms/1177729586 the following version, with a Lyapunov-function proof, is the one used most often in reinforcement learning.
Theorem A.7 (Robbins–Monro Conditions). Let be the history up to step and consider (A.3) under the following assumptions.
- Step sizes: is determined by , and almost surely (A.4)
- Noise: and .
- Drift: , and there is such that for , uniformly on every set .
Then almost surely.
Proof. Sketch. Let . Expanding the square and using assumption 2 to remove the cross term with ,
where and the growth bounds were used with . The Robbins–Siegmund theorem on almost supermartingalesHerbert Robbins and David Siegmund. A Convergence Theorem for Non Negative Almost Supermartingales and Some Applications. In Jagdish S. Rustagi, editor, Optimizing Methods in Statistics, pages 233–257. Academic Press, New York, 1971. doi: 10.1016/B978-0-12-604550-5.50015-8 applies because : converges almost surely to a finite limit and . If , then eventually stays in a shell where by assumption 3, and , a contradiction. Hence . □
The two conditions (A.4) have transparent roles. lets the iterates travel any distance, so the initial condition is eventually forgotten; makes the total noise injected, whose variance is of order , finite, so it averages out. Steps satisfy both exactly when . A constant step size violates the second condition: the iterates then do not converge but keep fluctuating in a neighborhood of size around , which is precisely what one wants when tracking a nonstationary target.
The harmonic series diverges (its convergence test is false), , and the conditions for : iff , iff .await show`{SumConvergence[1/n, n], Sum[1/n^2, {n, 1, Infinity}], SumConvergence[1/n^p, n, Assumptions -> Element[p, Reals]], SumConvergence[1/n^(2 p), n, Assumptions -> Element[p, Reals]]}`await show`Simplify[First[Fold[{#1[[1]] + (#2 - #1[[1]])/#1[[2]], #1[[2]] + 1} &, {Subscript[Q, 1], 1}, Table[Subscript[R, i], {i, 4}]]]]`The ODE method. The theorem asks for a global Lyapunov function, which is often unavailable. The more general and more useful view, developed by Kushner, Ljung and othersHarold J. Kushner and G. George Yin. Stochastic Approximation and Recursive Algorithms and Applications, volume 35 of Stochastic Modelling and Applied Probability. Springer, New York, second edition, 2003. ISBN 978-0-387-00894-3. doi: 10.1007/b97441 and given a clean form by Borkar and Meyn,Vivek S. Borkar and Sean P. Meyn. The O.D.E. Method for Convergence of Stochastic Approximation and Reinforcement Learning. SIAM Journal on Control and Optimization, 38(2):447–469, SIAM, 2000. doi: 10.1137/S0363012997331639 is that with small steps the noise averages out and the iterates follow the trajectories of the ordinary differential equation
(A.5)with as the time increment. Informally: if the iterates remain bounded and the ODE has a globally asymptotically stable equilibrium , then almost surely under the step-size conditions (A.4). Borkar and Meyn’s contribution is a test for boundedness: it suffices that the scaled ODE , with , has the origin as globally asymptotically stable equilibrium. For linear TD(0), , so , and everything reduces to the stability of : on-policy, is positive definite and TD converges to the TD fixed point (9.5); off-policy it may not be, which is the deadly triad of Chapter 11. Two learning processes running at different speeds, such as a critic and an actor, are handled by two-timescale versions in which the slow iterate sees the fast one at its equilibrium.A thorough reference for the classical theory, including the convergence of TD and Q-learning, is Bertsekas and Tsitsiklis (1996); the ODE method is developed in full by Kushner and Yin (2003).Dimitri P. Bertsekas and John N. Tsitsiklis. Neuro-Dynamic Programming. Athena Scientific, Belmont, MA, 1996. ISBN 1-886529-10-8
A.5Importance Sampling#
To estimate an expectation under a target distribution from samples drawn from a behavior distribution , reweight by the likelihood ratio . If wherever (coverage),
(A.6)The estimator is unbiased, but the second moment involves and is large, possibly infinite, when puts little mass where puts much. For trajectories, the probability of under a policy is a product of policy and dynamics factors; the dynamics factors are the same under and and cancel, leaving the ratio of (5.2), computable without a model. Its variance grows exponentially with the horizon in general, which is the motivation for weighted importance sampling (biased, consistent, of bounded variance) and for the per-decision and control-variate methods of Chapter 11.
Two outcomes: , , and , the excess second moment, with target and behavior .const isPi = await wl`{\[Pi], 1 - \[Pi]}`
const isB = await wl`{\[Beta], 1 - \[Beta]}`
const isF = await wl`{Subscript[f, 1], Subscript[f, 2]}`
await show`Simplify[{${isB} . (${isPi}/${isB} ${isF}) - ${isPi} . ${isF}, ${isB} . (${isPi}/${isB}), ${isB} . (${isPi}/${isB} ${isF})^2 - ${isPi} . ${isF}^2}]`The excess second moment vanishes when and blows up as or whenever the corresponding outcome matters under .
A.6The Log-Derivative Trick#
For a family of distributions and a function that does not depend on ,
(A.7)using wherever (for densities, under the usual conditions for differentiating under the integral). The vector is the score; taking shows that it has mean zero, so any constant can be subtracted from without bias (the baseline of Proposition 13.5). Its covariance is the Fisher information . The estimator needs only samples of and the ability to differentiate , not : this is why it works with unknown environments. Applied to a trajectory, whose probability is , the logarithm turns the product into a sum and the dynamics, independent of , drop out of the gradient: . That is REINFORCE (Algorithm 13.4). When can instead be written as a differentiable function of parameter-free noise , and is differentiable, the reparameterization (pathwise) estimator is an alternative, usually of much lower variance; deterministic policy gradients and soft actor–critic rely on it.
For : , its score-function form , and the Fisher information computed as and as .await show`Assuming[\[Sigma] > 0, Simplify[With[{d = NormalDistribution[\[Mu], \[Sigma]]}, {D[Expectation[x^2, x \[Distributed] d], \[Mu]], Expectation[x^2 D[Log[PDF[d, x]], \[Mu]], x \[Distributed] d], Expectation[D[Log[PDF[d, x]], \[Mu]]^2, x \[Distributed] d], -Expectation[D[Log[PDF[d, x]], {\[Mu], 2}], x \[Distributed] d]}]]]`A.7The Sherman–Morrison Formula#
Lemma A.8 (Sherman–Morrison). Let be invertible and vectors with . ThenJack 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
(A.8)Proof. Multiply by the right-hand side and write , a scalar:
For the determinant, , and has eigenvalue on and on the hyperplane . □
A rank-one change to a matrix costs a rank-one change to its inverse: operations instead of . Least-squares TD (Chapter 9) accumulates , a rank-one update with and , so its inverse can be maintained incrementally; the same device gives recursive least squares.
Both identities of the lemma for a generic matrix and symbolic vectors: the differences simplify to zero.const smA = await wl`{{Subscript[a, 1, 1], Subscript[a, 1, 2]}, {Subscript[a, 2, 1], Subscript[a, 2, 2]}}`
const smU = await wl`{Subscript[u, 1], Subscript[u, 2]}`
const smV = await wl`{Subscript[v, 1], Subscript[v, 2]}`
await show`Simplify[{Inverse[${smA} + Outer[Times, ${smU}, ${smV}]] - (Inverse[${smA}] - Inverse[${smA}] . Outer[Times, ${smU}, ${smV}] . Inverse[${smA}]/(1 + ${smV} . Inverse[${smA}] . ${smU})), Det[${smA} + Outer[Times, ${smU}, ${smV}]] - Det[${smA}] (1 + ${smV} . Inverse[${smA}] . ${smU})}]`